Pregunta

Necesito instalar módulos para que ocurran los cambios en la base de datos. No puedo dejar que sea una instalación en el enfoque de registro al tipo de administración, ya que tengo un script bash que estoy usando para aprovisionar mis servidores de prueba. Parece que cuando clonos módulos de mi repose Git, algunos de ellos no están instalados, por lo que necesito instalarlos con fuerza en el script PHP que ejecuto que agrega mis tiendas de prueba y qué no. He revisado todo tipo de clase y lo mejor que he encontrado es

isModuleOutPutenable ()

Pero eso no va a cortarlo. ¿Ideas sobre cómo hacer una instalación contundente?


posible identificación del problema

Parece que la simple limpieza del caché y llamando al Mage::app() E incluso tratar de iniciar sesión en un usuario administrador no puede activar los módulos para instalar. Pero si borra el caché a mano, justo antes de la primera vez que vaya a la pantalla de inicio de sesión /administrador, instalará las cosas como era de esperar. Hasta ahora en obtener la página (wget) Antes de borrar el caché, tampoco puede instalar los módulos.


Actualización 1

He tratado de hacer algo de forzamiento aquí, pero no entiendo lo que está sucediendo ... las extensiones se cargan bien cuando espero hasta después de la instalación fresca y simplemente coloco los archivos en las carpetas, pero cuando lo clono de antemano No lo veo en el core_resource tabla o la tabla para los módulos. Ejemplo de prueba para el script de instalación posterior es

$resource = Mage::getSingleton('core/resource');
$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;
echo "Test modules";
if(isset($modulesArray['Aoe_AsyncCache'])) {
    echo "AsyncCache exists.";
    $tableName = $resource->getTableName('asynccache');

    /**
     * if prefix was 'mage_' then the below statement
     * would print out mage_catalog_product_entity
     */
    echo "known as ".$tableName;
} else {
    echo "AsyncCachedoesn't exist.";
}  

Cuando corrí veo AsyncCache exists. known as 'asynccache' Sin embargo, no está en la base de datos. Esa tabla no estaba instalada. No de nuevo, el módulo se instala bien si espero ... pero curiosamente, si hago este clon Git, nunca se instala. Realmente no estoy seguro de lo que está pasando.


Actualización 2

Parece que cualquier módulo que tenga una base de datos vinculada a ella no se está instalando. Así que antecedentes sobre lo que está pasando. Estoy usando vagrant y está en una url de http://local.mage.dev como la url. Ahora, cuando uso el script provision.sh, tengo que instalar magento desde el ssh. Lo hago en el puesto. Pero un gran ejemplo del problema es que cuando soy tan simple,

./mage config-set preferred_state alpha
./mage clear-cache
./mage sync
./mage download community BL_CustomGrid
./mage install community BL_CustomGrid

La tabla no está instalada. No entiendo por qué. Magento está instalado. Si espero el primer inicio de sesión, puedo usar Connect para hacer la instalación. Recibo notificación en la línea de comando que ha instalado el BL_CustomeGrid bien, pero no lo ha hecho ... las tablas no están allí.


Actualización3

Traté de combinar todas las sugerencias en una. Tengo la aplicación Mage que se invoca después de cada clon de GitHub, luego se borra el caché. Luego borro el caché por última vez antes de ir a iniciar sesión. No puedo ver que la mesa instale. Casi me pregunto si tiene algo que ver con el vagabundo, pero parece poco probable que Magento instale. Pero prueba de lo que hice, aquí está el Sub Pregunta sobre llamar al script PHP que no está haciendo nada más que invocar mago y limpiar el caché.


Actualización4

Nota IMPORTANTE:

No solo he realizado una prueba en la que reconfirmé que si hago la instalación después de la instalación de Magento. Iniciar sesión normal, cargar archivos, borrar caché, iniciar sesión, volver a iniciar sesión y el módulo está instalado. Pero cuando agrego un inicio de sesión mediante programación del usuario administrador, me hago eco de que el usuario está iniciado, e incluso borro el caché, todavía falla.

El objetivo es ese, necesito encontrar el install('module_name') O algo así, o dos, poder hacer el 100% lo que sucede cuando el usuario firma los cachés y se registra.

La replicación programática de cómo se instala un módulo, sabemos (cierre de sesión, caché, etc.) falla



Los guiones en juego

El script que invoca instalación-invoke-app.php y, por lo tanto, hay un contexto completo, aquí está la función.sh que se llama y donde puede ver que la invocación de mago está realizada

provisión.shEsto es lo que se llama desde vagrant que configurará mi cama de prueba e instalará una instalación de magento completa programáticamente

start_seconds=`date +%s`
echo -en "\a" > /dev/tty5 | echo -e "\a"
cd /srv/www/
. scripts/install-functions.sh

if [[ has_network ]]
then
    apt-get install pv

    cd /srv/www/
    . scripts/install-prep.sh

    cd /srv/www/
    . scripts/main-install.sh

else
    echo -e "\nNo network connection available, skipping package installation"
fi

#double check the network
if [[ has_network ]]
then

    #check and install wp
    cd /srv/www/
    . scripts/db-install.sh   

    #check and install magento
    cd /srv/www/
    . scripts/mage-install.sh      

else
    echo -e "\nNo network available, skipping network installations"
fi
# Add any custom domains to the virtual machine's hosts file so that it
# is self-aware. Enter domains space delimited as shown with the default.
DOMAINS='local.mage.dev'
if ! grep -q "$DOMAINS" /etc/hosts
then echo "127.0.0.1 $DOMAINS" >> /etc/hosts
fi

end_seconds=`date +%s`
echo "-----------------------------"

Install-Functions.shEsta es solo algunas de las funciones de este script bash. Es solo lo que se usa en este conjunto de instalación del servidor. Tenga en cuenta que aquí es donde estamos llamando php "/srv/www/scripts/mage/install-invoke-app.php" Que es lo que debería ser invocar al mago e instalar cualquier módulo. Ahora las extensiones deberían haberse instalado programáticamente. Esto no está ocurriendo.

install_repo(){
    if [ $2 ]
    then
        echo "just 1"
        git clone $1 -q
    else
        echo "just 1 and 2"
        git clone $1 $2 -q
    fi
    success=$?
    if [[ $success -eq 0 ]];
    then
        echo "Repository successfully cloned."
        echo "cleaning"
        cd $r/
        rm -rf LICENSE.txt STATUS.txt README.md RELEASE_NOTES.txt modman
        cd ../
        cp -af $r/* .
        rm -rf $r/

        #eval $3
        php "/srv/www/scripts/mage/install-invoke-app.php"

        #if [ -z "$3" ]
        #then
        #    echo "no callback"
        #else
        #    eval $3
        #fi
    else
        echo "Something went wrong!"
    fi
    sleep 1 # slow it down to insure that we have the items put in place.
}

#declare -A list = ( [repo]=gitUser )
install_repolist(){
    gitRepos=$1
    for r in "${!gitRepos[@]}" #loop with key as the var
    do
        giturl="git://github.com/${gitRepos[$r]}/$r.git"
        echo "Adding $r From $giturl"
        if [ -z "$r" ];
        then
            echo
        else
            install_repo $giturl $2 $3
        fi
        echo
    done
    return 1
}

Install-Mage.shEsto se llama después del script Provision.SH ha instalado todos los conceptos básicos del servidor. Ya debería tener nginx y php5/php-fpm y todo el resto de los módulos necesarios.

#!/bin/bash
cd /srv/www/mage/ #move to the root web folder


dbhost="localhost"
dbname="mage"
dbuser="devsqluser"
dbpass="devsqluser"
url="local.mage.dev"
adminuser="admin"
adminpass="admin2013"
adminfname="Mc"       
adminlname="Lovin"
adminemail="test.user@wsu.edu"

echo
echo "We will clear any past install"
echo
echo "--Clear old caches reports and sessions"
cd /srv/www/mage/ #move to the root web folder
rm -rf ./var/cache/* ./var/session/* ./var/report/* ./var/locks/*
rm -rf ./var/log/* ./app/code/core/Zend/Cache/* ./media/css/* ./media/js/*
echo
if [ -f /srv/www/scripts/mage/clean.sql ]
then
    mysql -u root -pblank $dbname < /srv/www/scripts/mage/clean.sql | echo -e "\n Initial custom mage cleaning MySQL scripting..."
else
    echo -e "\n COUNLDN'T FIND THE CLEANER SQL FILE"
fi



echo "Now installing Magento with sample data..."



#chack to see if there is already the files ready for instalation
if [ ! -f /srv/www/mage/app/Mage.php ]
then

    if [ ! -f /srv/www/mage/magento-1.7.0.2.tar.gz ]
    then

        echo
        echo "didn't find the packages, so now Downloading them..."
        echo

        wget http://www.magentocommerce.com/downloads/assets/1.7.0.2/magento-1.7.0.2.tar.gz
        wget http://www.magentocommerce.com/downloads/assets/1.6.1.0/magento-sample-data-1.6.1.0.tar.gz
    fi

    echo
    echo "Extracting data..."
    echo    
        pv -per magento-1.7.0.2.tar.gz | tar xzf - -C ./
        pv -per magento-sample-data-1.6.1.0.tar.gz | tar xzf - -C ./

    echo
    echo "Moving files..."
    echo        
        cp -af magento-sample-data-1.6.1.0/media/* media/
        cp -af magento-sample-data-1.6.1.0/magento_sample_data_for_1.6.1.0.sql data.sql
        cp -af magento/* magento/.htaccess .

        cd /srv/www/mage/ #move to the root web folder
    echo
    echo "Setting permissions..."
    echo

    chmod o+w var var/.htaccess app/etc
    chmod -R o+w media

fi

echo
echo "Installing Adminer..."
if [ ! -f /srv/www/mage/adminer.php ]
then
    wget http://downloads.sourceforge.net/adminer/adminer-3.7.1-mysql-en.php > adminer.php
fi

echo
echo "Importing sample products..."
mysql -h $dbhost -u $dbuser -p$dbpass $dbname < data.sql




#pear mage-setup .
#pear install magento-core/Mage_All_Latest-stable

#./mage mage-setup .
#./mage config-set preferred_state stable

echo
echo "Initializing PEAR registry..."


pear mage-setup .

echo
echo "Downloading packages..."


pear install magento-core/Mage_All_Latest


echo
echo "Cleaning up files..."


rm -rf downloader/pearlib/cache/* downloader/pearlib/download/*
rm -rf magento/ magento-sample-data-1.6.1.0/
#rm -rf magento-1.7.0.2.tar.gz magento-sample-data-1.6.1.0.tar.gz data.sql
rm -rf index.php.sample .htaccess.sample php.ini.sample LICENSE.txt
rm -rf STATUS.txt LICENSE.html LICENSE_AFL.txt  RELEASE_NOTES.txt

echo
echo "Installing Magento..."

    php -f install.php --\
    --license_agreement_accepted yes \
    --locale en_US \
    --timezone America/Los_Angeles \
    --default_currency USD \
    --db_host $dbhost \
    --db_name $dbname \
    --db_user $dbuser \
    --db_pass $dbpass \
    --url $url \
    --use_rewrites yes \
    --skip_url_validation yes \
    --use_secure no \
    --secure_base_url "" \
    --use_secure_admin no \
    --admin_firstname "$adminfname" \
    --admin_lastname "$adminlname" \
    --admin_email "$adminemail" \
    --admin_username "$adminuser" \
    --admin_password "$adminpass"

if [ ! -f /srv/www/mage/app/etc/local.xml ]
then
    echo "failed install try it again"
else


    if [ -f /srv/database/init-mage.sql ]
    then
        mysql -u root -pblank < /srv/database/init-mage.sql | echo -e "\nInitial custom mage MySQL scripting..."
    else
        echo -e "\nNo custom MySQL scripting found in database/init-mage.sql, skipping..."
    fi

    cd /srv/www/mage/
    echo "Starting to import base WSU modules from connect"
    #./mage install http://connect20.magentocommerce.com/community Flagbit_ChangeAttributeSet
    ./mage config-set preferred_state alpha
    ./mage clear-cache
    ./mage sync
    ./mage download community Flagbit_ChangeAttributeSet
    ./mage download community BL_CustomGrid
    ./mage install community Flagbit_ChangeAttributeSet
    #./mage install community BL_CustomGrid


    echo "Starting to import base WSU modules fro github"
    declare -A gitRepos
    #[repo]=gitUser
    gitRepos=(
        [wsu_admin_base]=jeremyBass
        [wsu_base_theme]=jeremyBass
        [Storeutilities]=jeremyBass
        [StructuredData]=jeremyBass
        #[Storeuser]=jeremyBass
        [sitemaps]=jeremyBass
        [webmastertools]=jeremyBass 
        [ldap]=jeremyBass 
        [Aoe_FilePicker]=jeremyBass         #https://github.com/fbrnc/Aoe_FilePicker.git
        [Aoe_ClassPathCache]=jeremyBass     #https://github.com/fbrnc/Aoe_ClassPathCache.git
        [Aoe_Profiler]=jeremyBass           #https://github.com/fbrnc/Aoe_Profiler.git
        [Aoe_ManageStores]=jeremyBass       #https://github.com/fbrnc/Aoe_ManageStores.git
        [Aoe_LayoutConditions]=jeremyBass   #https://github.com/fbrnc/Aoe_LayoutConditions.git
        [Aoe_AsyncCache]=jeremyBass         #https://github.com/fbrnc/Aoe_AsyncCache.git
        [Aoe_ApiLog]=jeremyBass             #https://github.com/fbrnc/Aoe_ApiLog.git
        #[mage-enhanced-admin-grids]=mage-eag
    )
    cd /srv/www/mage/
    install_repolist $gitRepos 0 "wget http://$url"
    unset gitRepos         #unset and re-declare to clear associative arrays
    declare -A gitRepos

    cd /srv/www/mage/

    echo "importing WSU favicon"
    wget -q http://images.dev.edu/favicon.ico -O favicon.ico

    #run actions that are hard to do direct sql quries on 

    php /srv/www/scripts/mage/install-post.php


    echo
    echo "doing the first index"
    echo
    cd shell && php -f indexer.php reindexall


    mysql -u root -pblank $dbname -e "DELETE FROM $dbname.adminnotification_inbox;" | echo -e "\n >> Removed admin notifications ..."

    # Enable developer mode
    #if [ $MAG_DEVELOPER_MODE == 1 ]; then
    #    sed -i -e '/Mage::run/i\
    #Mage::setIsDeveloperMode(true);
    #' -e '1,$s//Mage::run/' $WWW_PATH/index.php
    #fi


    echo
    echo "Finished installing Magento"
    echo

 fi

install-post.phpEste archivo ocurre después de que el archivo Install-Mage.sh haya completado la instalación de Magento. Todos los módulos han sido descargados y Lo que necesitamos es haber instalado todas las tablas del módulo. Es decir: las instalaciones de SQL para los módulos ya deberían haberse ejecutado

<?php
//just as a guide, no real purpose
echo getcwd() . " (working from)\n";

//set up the store instance
require_once "app/Mage.php";
umask(0);
Mage::app();
Mage::app()->getTranslator()->init('frontend');
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::registry('isSecureArea'); // acting is if we are in the admin
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getConfig()->init();
/**
 * Get the resource model
 */
$resource = Mage::getSingleton('core/resource');

/**
 * Retrieve the read connection
 */
$readConnection = $resource->getConnection('core_read');

/**
 * Retrieve the write connection
 */
$writeConnection = $resource->getConnection('core_write');

// switch off error reporting
error_reporting ( E_ALL & ~ E_NOTICE );

$changeData = new Mage_Core_Model_Config();

echo "applying default store settings\n";
//pattern
//\((.*?),  '(.*?)',    (.*?),  '(.*?)',    '?(.*?)'?\),
//$changeData->saveConfig('$4', "$5", 'default', 0);
echo " - applying design settings\n";
    $changeData->saveConfig('design/package/name', "wsu_base", 'default', 0);
    $changeData->saveConfig('design/theme/template', "default", 'default', 0);
    $changeData->saveConfig('design/theme/skin', "default", 'default', 0);
    $changeData->saveConfig('design/theme/layout', "default", 'default', 0);
    $changeData->saveConfig('design/theme/default', "default", 'default', 0);
    $changeData->saveConfig('design/theme/locale', "NULL", 'default', 0);

function make_store($categoryName,$site,$store,$view){
    //#adding a root cat for the new store we will create
    // Create category object
    $category = Mage::getModel('catalog/category');
    $category->setStoreId(0); // No store is assigned to this category

    $rootCategory['name'] = $categoryName;
    $rootCategory['path'] = "1"; // this is the catgeory path - 1 for root category
    $rootCategory['display_mode'] = "PRODUCTS";
    $rootCategory['is_active'] = 1;

    $category->addData($rootCategory);
    $rootCategoryId=0;
    try {
        $category->save();
        $rootCategoryId = $category->getId();
    }
        catch (Exception $e){
        echo $e->getMessage();
    }
    if($rootCategoryId>0){
    //#addWebsite
        /** @var $website Mage_Core_Model_Website */
        $website = Mage::getModel('core/website');
        $website->setCode($site['code'])
            ->setName($site['name'])
            ->save();

    //#addStoreGroup
        /** @var $storeGroup Mage_Core_Model_Store_Group */
        $storeGroup = Mage::getModel('core/store_group');
        $storeGroup->setWebsiteId($website->getId())
            ->setName($store['name'])
            ->setRootCategoryId($rootCategoryId)
            ->save();

    //#addStore
        /** @var $store Mage_Core_Model_Store */
        $store = Mage::getModel('core/store');
        $store->setCode($view['code'])
            ->setWebsiteId($storeGroup->getWebsiteId())
            ->setGroupId($storeGroup->getId())
            ->setName($view['name'])
            ->setIsActive(1)
            ->save();
    }
    return $rootCategoryId;
}
echo "Applying the default multi-store setup\n";
$installed_stores = array();
$installed_stores['studentstore'] = make_store("Student store root",
                array('code'=>'studentstore','name'=>'Student store'),
                array('name'=>'Student Store'),
                array('code'=>'studentstore','name'=>'base default veiw')
              );
$installed_stores['teststore'] = make_store("Test store root",
                array('code'=>'teststore','name'=>'Test store'),
                array('name'=>'Test Store'),
                array('code'=>'teststore','name'=>'base default veiw')
              );

// let us refresh the cache
try {
    $allTypes = Mage::app()->useCache();
    foreach($allTypes as $type => $blah) {
      Mage::app()->getCacheInstance()->cleanType($type);
    }
} catch (Exception $e) {
    // do something
    error_log($e->getMessage());
}

$types = Mage::app()->getCacheInstance()->getTypes();
try {
    echo "Cleaning data cache... \n";
    flush();
    foreach ($types as $type => $data) {
        echo "Removing $type ... ";
        echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "[OK]" : "[ERROR]";
        echo "\n";
    }
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}

echo "\n";

try {
    echo "Cleaning stored cache... ";
    flush();
    echo Mage::app()->getCacheInstance()->clean() ? "[OK]" : "[ERROR]";
    echo "\n\n";
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}

$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;
echo "Test modules";
if(isset($modulesArray['Aoe_AsyncCache'])) {
    echo "AsyncCache exists.";
    $tableName = $resource->getTableName('asynccache');

    /**
     * if prefix was 'mage_' then the below statement
     * would print out mage_catalog_product_entity
     */
    echo "known as ".$tableName;
} else {
    echo "AsyncCachedoesn't exist.";
}   

instalar-invoke-app.php

<?php
//just as a guide, no real purpose
echo getcwd() . " (working from)\n";

//set up the store instance
require_once "app/Mage.php";
umask(0);
Mage::app();
Mage::app()->getTranslator()->init('frontend');
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::registry('isSecureArea'); // acting is if we are in the admin
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getConfig()->init();

// switch off error reporting
error_reporting ( E_ALL & ~ E_NOTICE );

// let us refresh the cache
try {
    $allTypes = Mage::app()->useCache();
    foreach($allTypes as $type => $blah) {
      Mage::app()->getCacheInstance()->cleanType($type);
    }
} catch (Exception $e) {
    // do something
    error_log($e->getMessage());
}


$types = Mage::app()->getCacheInstance()->getTypes();
try {
    echo "Cleaning data cache... \n";
    flush();
    foreach ($types as $type => $data) {
        echo "Removing $type ... ";
        echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "[OK]" : "[ERROR]";
        echo "\n";
    }
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}

echo "\n";

try {
    echo "Cleaning stored cache... ";
    flush();
    echo Mage::app()->getCacheInstance()->clean() ? "[OK]" : "[ERROR]";
    echo "\n\n";
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}
echo "finish invoking the mage app.";

//time to login as admin
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getSingleton('core/session', array('name' => 'adminhtml'));

// supply username
$user = Mage::getModel('admin/user')->loadByUsername('admin'); // user your admin username

if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
   Mage::getSingleton('adminhtml/url')->renewSecretUrls();
}

$session = Mage::getSingleton('admin/session');
$session->setIsFirstVisit(true);
$session->setUser($user);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
Mage::dispatchEvent('admin_session_user_login_success',array('user'=>$user));
if ($session->isLoggedIn()) { echo "Logged in \n"; } else{ echo "Not Logged \n"; }
¿Fue útil?

Solución

Responder

Resulta que solo borrar el caché y hacer un WGET, o iniciar sesión en un usuario en programación, o incluso ambos no fueron suficientes para activar el código para instalar un módulo.

Esto es lo que funciona.

rm -rf var/cache/*
php "/srv/www/mage/index.php"

Dónde /mage es la carpeta de la raíz de la tienda, solo necesitaba ejecutar el index.php archivo y luego funcionó. No puedo decir por qué no lo haría wget, o por qué llamar MAGE:app() Y todas las combinaciones no funcionaron, pero borrar la carpeta de caché y llamar al archivo es el boleto para reconstruir establemente el caché de la línea de comando.

Espero que esto salve a alguien en algún momento. Salud

Otros consejos

No estoy seguro si recibí bien su pregunta, pero si desea activar el script de configuración sin abrir el sitio web en su navegador, ¿por qué no simplemente crear el script de shell que solo wget ¿La página de inicio de su instalación de Magento?

Puede usar el siguiente script PHP para borrar el caché de la línea de comandos después de aplicar todas las actualizaciones a través de GIT. Después de esto, puede usar WGET para obtener la página de inicio de su sitio para reconstruir el caché y ejecutar todos los cambios en la base de datos.

(código de http://www.yamevo.com/development/php/flush-every-magento-cache-from-the-command-line):

<?php
date_default_timezone_set("Europe/Madrid");
echo "Start Cleaning all caches at ... " . date("Y-m-d H:i:s") . "\n\n";
ini_set("display_errors", 1);

require '../app/Mage.php';
Mage::app('admin')->setUseSessionInUrl(false);
Mage::getConfig()->init();

$types = Mage::app()->getCacheInstance()->getTypes();

try {
    echo "Cleaning data cache... \n";
    flush();
    foreach ($types as $type => $data) {
        echo "Removing $type ... ";
        echo Mage::app()->getCacheInstance()->clean($data["tags"]) ? "[OK]" : "[ERROR]";
        echo "\n";
    }
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}

echo "\n";

try {
    echo "Cleaning stored cache... ";
    flush();
    echo Mage::app()->getCacheInstance()->clean() ? "[OK]" : "[ERROR]";
    echo "\n\n";
} catch (exception $e) {
    die("[ERROR:" . $e->getMessage() . "]");
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top