Guia do Desenvolvedor de Empacotamento de Aplicativos

Acomodando a relocação

Embora você possa selecionar os diretórios base de vários pacotes que são exclusivos de uma arquitetura ou versão, esse procedimento cria níveis desnecessários de hierarquia de diretórios. Por exemplo, em um produto criado para processadores baseados em SPARC e em x86, você poderia organizar os diretórios base por processador e versão conforme ilustrado abaixo.

Diretório base 

Versão e processador 

/opt/SUNWstuf/sparc/1.0

Versão 1.0, SPARC 

/opt/SUNWstuf/sparc/1.2

Versão 1.2, SPARC 

/opt/SUNWstuf/x86/1.0

Versão 1.0, x86 

Esse procedimento está bem e funciona, mas você está tratando os nomes e os números como se eles tivessem algum significado para o administrador. Uma abordagem mais apropriada é fazê-lo automaticamente depois de explicar ao administrador e pedir permissão.

Isso significa que você pode realizar todo o trabalho no pacote sem pedir ao administrador que o faça manualmente. Você pode atribuir o diretório base arbitrariamente e, a seguir, estabelecer com clareza os links de cliente apropriados em um script postinstall. Você também pode usar o comando pkgadd para instalar todo o pacote ou parte dele nos clientes do script postinstall. Você pode, até mesmo, perguntar ao administrador quais os usuários ou clientes que precisam ter informações sobre este pacote e atualizar automaticamente as variáveis de ambiente PATH e os arquivos /etc. Isso é totalmente aceitável contanto que qualquer ação realizada pelo pacote na instalação seja desfeita durante a remoção.

Deslocando diretórios base

Você pode tirar vantagem dos dois métodos para controlar o diretório base no momento da instalação. O primeiro é melhor para novos pacotes que serão instalados somente no Solaris 2.5 e versões compatíveis. Ele oferece dados muito úteis para o administrador e oferece suporte a várias versões e arquiteturas instaladas, além de exigir pouco trabalho especial. O segundo método pode ser usado por qualquer pacote e faz uso do controle inerente do script request sobre os parâmetros de construção para garantir que as instalações sejam bem-sucedidas.

Usando o parâmetro BASEDIR

O script checkinstall pode selecionar o diretório base apropriado no tempo de instalação, o que significa que o diretório base pode ser posicionado bem abaixo na árvore de diretórios. Este exemplo aumenta o diretório base seqüencialmente, levando a diretórios na forma /opt/SUNWstuf, /opt/SUNWstuf.1 e /opt/SUNWstuf.2. O administrador pode usar o comando pkginfo para determinar que arquitetura e versão são instalados em cada diretório base.

Se o pacote SUNWstuf (que contém um conjunto de utilitários que realizam ações) usasse este método, os arquivos pkginfo e pkgmap teriam a seguinte aparência.

O arquivo pkginfo

# pkginfo file
PKG=SUNWstuf
NAME=software stuff 
ARCH=sparc
VERSION=1.0.0,REV=1.0.5
CATEGORY=application
DESC=a set of utilities that do stuff
BASEDIR=/opt/SUNWstuf
VENDOR=Sun Microsystems, Inc.
HOTLINE=Please contact your local service provider
EMAIL=
MAXINST=1000
CLASSES=none daemon
PSTAMP=hubert990707141632

O arquivo pkgmap

: 1 1758
1 d none EZstuf 0775 root bin
1 f none EZstuf/dirdel 0555 bin bin 40 773 751310229
1 f none EZstuf/usrdel 0555 bin bin 40 773 751310229
1 f none EZstuf/filedel 0555 bin bin 40 773 751310229
1 d none HRDstuf 0775 root bin
1 f none HRDstuf/mksmart 0555 bin bin 40 773 751310229
1 f none HRDstuf/mktall 0555 bin bin 40 773 751310229
1 f none HRDstuf/mkcute 0555 bin bin 40 773 751310229
1 f none HRDstuf/mkeasy 0555 bin bin 40 773 751310229
1 d none /etc	? ? ?
1 d none /etc/rc2.d ? ? ?
1 f daemon /etc/rc2.d/S70dostuf 0744 root sys 450 223443
1 i pkginfo 348 28411 760740163
1 i postinstall 323 26475 751309908
1 i postremove 402 33179 751309945
1 i preinstall 321 26254 751310019
1 i preremove 320 26114 751309865
1 i i.daemon 509 39560 752978103
1 i r.daemon 320 24573 742152591

Exemplo — Scripts de análise que deslocam um BASEDIR

Suponha que a versão x86 de SUNWstuf já esteja instalada no servidor em /opt/SUNWstuf. Quando o administrador usa o comando pkgadd para instalar a versão SPARC, o script request precisa detectar a existência da versão x86 e interagir com o administrador em relação à instalação.


Observação –

O diretório base pode ser deslocado sem a interação do administrador em um script checkinstall, mas se operações arbitrárias como essa ocorrerem constantemente, os administradores perdem a confiança no processo.


Os scripts request e checkinstall de um pacote que manipula esta situação podem ter a seguinte aparência.

O script request

# request script
for SUNWstuf to walk the BASEDIR parameter.
 
PATH=/usr/sadm/bin:${PATH}	# use admin utilities
 
GENMSG="The base directory $LOCAL_BASE already contains a \
different architecture or version of $PKG."
 
OLDMSG="If the option \"-a none\" was used, press the  \
key and enter an unused base directory when it is requested."
 
OLDPROMPT="Do you want to overwrite this version? "
 
OLDHELP="\"y\" will replace the installed package, \"n\" will \
stop the installation."
 
SUSPEND="Suspending installation at user request using error \
code 1."
 
MSG="This package could be installed at the unused base directory $WRKNG_BASE."
 
PROMPT="Do you want to use to the proposed base directory? "
 
HELP="A response of \"y\" will install to the proposed directory and continue,
\"n\" will request a different directory. If the option \"-a none\" was used,
press the  key and enter an unused base directory when it is requested."
 
DIRPROMPT="Select a preferred base directory ($WRKNG_BASE) "
 
DIRHELP="The package $PKG will be installed at the location entered."
 
NUBD_MSG="The base directory has changed. Be sure to update \
any applicable search paths with the actual location of the \
binaries which are at $WRKNG_BASE/EZstuf and $WRKNG_BASE/HRDstuf."
 
OldSolaris=""
Changed=""
Suffix="0"
 
#
# Determine if this product is actually installed in the working
# base directory.
#
Product_is_present () {
	  if [ -d $WRKNG_BASE/EZstuf -o -d $WRKNG_BASE/HRDstuf ]; then
		    return 1
	  else
		    return 0
	  fi
}
 
if [ ${BASEDIR} ]; then
	  # This may be an old version of Solaris. In the latest Solaris
	  # CLIENT_BASEDIR won't be defined yet. In older version it is.
	  if [ ${CLIENT_BASEDIR} ]; then
		    LOCAL_BASE=$BASEDIR
		    OldSolaris="true"
	  else	# The base directory hasn't been processed yet
		    LOCAL_BASE=${PKG_INSTALL_ROOT}$BASEDIR
fi
 
WRKNG_BASE=$LOCAL_BASE
 
	# See if the base directory is already in place and walk it if
	# possible
while [ -d ${WRKNG_BASE} -a Product_is_present ]; do
		 # There is a conflict
		 # Is this an update of the same arch & version?
		 if [ ${UPDATE} ]; then
			   exit 0	# It's out of our hands.
		 else
			   # So this is a different architecture or
			   # version than what is already there.
			   # Walk the base directory
			   Suffix=`expr $Suffix + 1`
			   WRKNG_BASE=$LOCAL_BASE.$Suffix
			   Changed="true"
		 fi
done
 
	# So now we can propose a base directory that isn't claimed by
	# any of our other versions.
if [ $Changed ]; then
		 puttext "$GENMSG"
		 if [ $OldSolaris ]; then
			   puttext "$OLDMSG"
			   result=`ckyorn -Q -d "a" -h "$OLDHELP" -p "$OLDPROMPT"`
			   if [ $result="n" ]; then
				     puttext "$SUSPEND"
				     exit 1	# suspend installation
			   else
				     exit 0
			   fi
		 else	# The latest functionality is available
			   puttext "$MSG"
			   result=`ckyorn -Q -d "a" -h "$HELP" -p "$PROMPT"`
			   if [ $? -eq 3]; then
				     echo quitinstall >> $1
				     exit 0
			   fi
 
			   if [ $result="n" ]; then
				     WRKNG_BASE=`ckpath -ayw -d "$WRKNG_BASE" \
				     -h "$DIRHELP" -p "$DIRPROMPT"`
			   else if [ $result="a" ]
				     exit 0
			   fi
		    fi
		    echo "BASEDIR=$WRKNG_BASE" >> $1
		    puttext "$NUBD_MSG"
	  fi
fi
exit 0

O script checkinstall

# checkinstall
script for SUNWstuf to politely suspend
 
grep quitinstall $1
if [ $? -eq 0 ]; then
	exit 3		# politely suspend installation
fi
 
exit 0

Esta abordagem não funcionaria muito bem se o diretório base fosse simplesmente /opt. Este pacote tem que chamar mais precisamente o BASEDIR visto que /opt seria difícil de deslocar. De fato, dependendo do esquema de montagem, isso pode não ser possível. O exemplo desloca o diretório base criando um novo diretório em /opt, que não apresenta nenhum problema.

Este exemplo usa um script request e um script checkinstall embora as versões do Solaris anteriores à versão 2.5 não possam executar o script checkinstall. O script checkinstall deste exemplo é usado a fim de interromper educadamente a instalação em resposta a uma mensagem privada na forma da seqüência quitinstall. Se este script for executado no Solaris 2.3, o script checkinstall é ignorado e o script request interrompe a instalação com uma mensagem de erro.

Lembre-se que nas versões anteriores ao Solaris 2.5 e versões compatíveis, o parâmetro BASEDIR é um parâmetro somente de leitura e não pode ser alterado pelo script request. Por essa razão, se uma versão antiga do sistema operacional SunOS for detectada (através do teste de uma variável de ambiente CLIENT_BASEDIR condicionada), o script request tem apenas duas opções — continuar ou sair.

Usando caminhos paramétricos relativos

Se o seu produto de software puder ser instalado em versões antigas do sistema operacional SunOS, o script request precisa realizar todas as ações necessárias. Esta abordagem também pode ser usada para manipular vários diretórios. Se forem necessários diretórios adicionais, estes ainda precisam ser incluídos em um único diretório base a fim de oferecer um produto facilmente administrável. Embora o parâmetro BASEDIR não ofereça o nível de granularidade disponível na última versão do Solaris, seu pacote ainda pode deslocar o diretório base usando o script request para manipular caminhos paramétricos. Os arquivos pkginfo e pkgmap podem ter a aparência seguinte.

O arquivo pkginfo

# pkginfo file
PKG=SUNWstuf
NAME=software stuff 
ARCH=sparc
VERSION=1.0.0,REV=1.0.5
CATEGORY=application
DESC=a set of utilities that do stuff
BASEDIR=/opt
SUBBASE=SUNWstuf
VENDOR=Sun Microsystems, Inc.
HOTLINE=Please contact your local service provider
EMAIL=
MAXINST=1000
CLASSES=none daemon
PSTAMP=hubert990707141632

O arquivo pkgmap

: 1 1758
1 d none $SUBBASE/EZstuf 0775 root bin
1 f none $SUBBASE/EZstuf/dirdel 0555 bin bin 40 773 751310229
1 f none $SUBBASE/EZstuf/usrdel 0555 bin bin 40 773 751310229
1 f none $SUBBASE/EZstuf/filedel 0555 bin bin 40 773 751310229
1 d none $SUBBASE/HRDstuf 0775 root bin
1 f none $SUBBASE/HRDstuf/mksmart 0555 bin bin 40 773 751310229
1 f none $SUBBASE/HRDstuf/mktall 0555 bin bin 40 773 751310229
1 f none $SUBBASE/HRDstuf/mkcute 0555 bin bin 40 773 751310229
1 f none $SUBBASE/HRDstuf/mkeasy 0555 bin bin 40 773 751310229
1 d none /etc	? ? ?
1 d none /etc/rc2.d ? ? ?
1 f daemon /etc/rc2.d/S70dostuf 0744 root sys 450 223443
1 i pkginfo 348 28411 760740163
1 i postinstall 323 26475 751309908
1 i postremove 402 33179 751309945
1 i preinstall 321 26254 751310019
1 i preremove 320 26114 751309865
1 i i.daemon 509 39560 752978103
1 i r.daemon 320 24573 742152591

Este exemplo não é perfeito. Um comando pkginfo -r retorna /opt para a base de instalação, que é um pouco ambíguo. Muitos pacotes estão em /opt, mas pelo menos é um diretório significativo. Igual ao exemplo anterior, o próximo exemplo oferece suporte completo a várias arquiteturas e versões. O script request pode ser adaptado às necessidades de determinado pacote e resolver quaisquer dependências aplicáveis.

Exemplo — Um script request que desloca um caminho paramétrico relativo

# request script
for SUNWstuf to walk a parametric path
 
PATH=/usr/sadm/bin:${PATH}	# use admin utilities
 
MSG="The target directory $LOCAL_BASE already contains \
different architecture or version of $PKG. This package \
could be installed at the unused target directory $WRKNG_BASE."
 
PROMPT="Do you want to use to the proposed directory? "
 
HELP="A response of \"y\" will install to the proposed directory \
and continue, \"n\" will request a different directory. If \
the option \"-a none\" was used, press the <RETURN> key and \
enter an unused base directory when it is requested."
 
DIRPROMPT="Select a relative target directory under $BASEDIR/"
 
DIRHELP="The package $PKG will be installed at the location entered."
 
SUSPEND="Suspending installation at user request using error \
code 1."
 
NUBD_MSG="The location of this package is not the default. Be \
sure to update any applicable search paths with the actual \
location of the binaries which are at $WRKNG_BASE/EZstuf \
and $WRKNG_BASE/HRDstuf."
 
Changed=""
Suffix="0"
 
#
# Determine if this product is actually installed in the working
# base directory.
#
Product_is_present () {
	  if [ -d $WRKNG_BASE/EZstuf -o -d $WRKNG_BASE/HRDstuf ]; then
		    return 1
	  else
		    return 0
 
	  fi
}
 
if [ ${BASEDIR} ]; then
	  # This may be an old version of Solaris. In the latest Solaris
	  # CLIENT_BASEDIR won't be defined yet. In older versions it is.
	  if [ ${CLIENT_BASEDIR} ]; then
		    LOCAL_BASE=$BASEDIR/$SUBBASE
	  else	# The base directory hasn't been processed yet
		    LOCAL_BASE=${PKG_INSTALL_ROOT}$BASEDIR/$SUBBASE
	  fi
 
WRKNG_BASE=$LOCAL_BASE
 
# See if the base directory is already in place and walk it if
# possible
while [ -d ${WRKNG_BASE} -a Product_is_present ]; do
		 # There is a conflict
		 # Is this an update of the same arch & version?
		 if [ ${UPDATE} ]; then
			   exit 0	# It's out of our hands.
		 else
			   # So this is a different architecture or
			   # version than what is already there.
			   # Walk the base directory
			   Suffix=`expr $Suffix + 1`
			   WRKNG_BASE=$LOCAL_BASE.$Suffix
			   Changed="true"
		 fi
done
 
# So now we can propose a base directory that isn't claimed by
# any of our other versions.
if [ $Changed ]; then
		 puttext "$MSG"
		 result=`ckyorn -Q -d "a" -h "$HELP" -p "$PROMPT"`
		 if [ $? -eq 3 ]; then
			   puttext "$SUSPEND"
			   exit 1
		 fi
 
		 if [ $result="n" ]; then
			   WRKNG_BASE=`ckpath -lyw -d "$WRKNG_BASE" -h "$DIRHELP" \
			   -p "$DIRPROMPT"`
 
		    elif [ $result="a" ]; then
			       exit 0
		    else
			       exit 1
		    fi
		    echo SUBBASE=$SUBBASE.$Suffix >> $1
		    puttext "$NUBD_MSG"
	  fi
fi
exit 0