Scalr_Scripting_Manager::prepareScript PHP Method

prepareScript() public static method

public static prepareScript ( $scriptSettings, DBServer $targetServer, AbstractServerEvent $event = null )
$targetServer DBServer
$event AbstractServerEvent
    public static function prepareScript($scriptSettings, DBServer $targetServer, AbstractServerEvent $event = null)
    {
        $template = ['type' => isset($scriptSettings['type']) ? $scriptSettings['type'] : null, 'timeout' => isset($scriptSettings['timeout']) ? $scriptSettings['timeout'] : null, 'issync' => isset($scriptSettings['issync']) ? $scriptSettings['issync'] : null, 'run_as' => isset($scriptSettings['run_as']) ? $scriptSettings['run_as'] : null, 'execution_id' => Scalr::GenerateUID()];
        if ($scriptSettings['type'] == self::ORCHESTRATION_SCRIPT_TYPE_SCALR) {
            /* @var $script Script */
            $script = Script::findPk($scriptSettings['scriptid']);
            if (!$script) {
                return false;
            }
            // TODO: validate permission to access script ?
            if ($script->os && $targetServer->osType && $script->os != $targetServer->osType) {
                return false;
            }
            if ($scriptSettings['version'] == 'latest' || (int) $scriptSettings['version'] == -1) {
                $version = $script->getLatestVersion();
            } else {
                $version = $script->getVersion((int) $scriptSettings['version']);
            }
            if (empty($version)) {
                return false;
            }
            $template['name'] = $script->name;
            $template['id'] = $script->id;
            $template['body'] = $version->content;
            $template['scriptVersion'] = $version->version;
            // variables could be null
            $scriptParams = $script->allowScriptParameters ? (array) $version->variables : [];
            foreach ($scriptParams as &$val) {
                $val = "";
            }
            $params = array_merge($scriptParams, $targetServer->GetScriptingVars(), (array) unserialize($scriptSettings['params']));
            if ($event) {
                $eventServer = $event->DBServer;
                foreach ($eventServer->GetScriptingVars() as $k => $v) {
                    $params["event_{$k}"] = $v;
                }
                foreach ($event->GetScriptingVars() as $k => $v) {
                    $params[$k] = $event->{$v};
                }
                if (isset($event->params) && is_array($event->params)) {
                    foreach ($event->params as $k => $v) {
                        $params[$k] = $v;
                    }
                }
                $params['event_name'] = $event->GetName();
            }
            if ($event instanceof CustomEvent && count($event->params) > 0) {
                $params = array_merge($params, $event->params);
            }
            // Prepare keys array and array with values for replacement in script
            $keys = array_keys($params);
            $keys = array_map(function ($item) {
                return '%' . $item . '%';
            }, $keys);
            $values = array_values($params);
            $script_contents = str_replace($keys, $values, $template['body']);
            $template['body'] = str_replace('\\%', "%", $script_contents);
            // Generate script contents
            $template['name'] = preg_replace("/[^A-Za-z0-9]+/", "_", $template['name']);
        } elseif ($scriptSettings['type'] == self::ORCHESTRATION_SCRIPT_TYPE_LOCAL) {
            $template['path'] = $targetServer->applyGlobalVarsToValue($scriptSettings['script_path']);
        } elseif ($scriptSettings['type'] == self::ORCHESTRATION_SCRIPT_TYPE_CHEF) {
            $chef = new stdClass();
            $chefSettings = (array) unserialize($scriptSettings['params']);
            if ($chefSettings['chef.cookbook_url']) {
                $chef->cookbookUrl = $chefSettings['chef.cookbook_url'];
            }
            if ($chefSettings['chef.cookbook_url_type']) {
                $chef->cookbookUrlType = $chefSettings['chef.cookbook_url_type'];
            }
            if ($chefSettings['chef.relative_path']) {
                $chef->relativePath = $chefSettings['chef.relative_path'];
            }
            if ($chefSettings['chef.ssh_private_key']) {
                $chef->sshPrivateKey = $chefSettings['chef.ssh_private_key'];
            }
            if ($chefSettings['chef.role_name']) {
                $chef->role = $chefSettings['chef.role_name'];
            } else {
                $chef->runList = $chefSettings['chef.runlist'];
            }
            $chef->jsonAttributes = $chefSettings['chef.attributes'];
            $template['chef'] = $chef;
        }
        return $template;
    }

Usage Example

コード例 #1
0
ファイル: SchedulerTask.php プロジェクト: rickb838/scalr
 /**
  * @return bool
  * @throws Exception
  */
 public function execute($manual = false)
 {
     $farmRoleNotFound = false;
     $logger = Logger::getLogger(__CLASS__);
     switch ($this->type) {
         case self::LAUNCH_FARM:
             try {
                 $farmId = $this->targetId;
                 $DBFarm = DBFarm::LoadByID($farmId);
                 if ($DBFarm->Status == FARM_STATUS::TERMINATED) {
                     // launch farm
                     Scalr::FireEvent($farmId, new FarmLaunchedEvent(true));
                     $logger->info(sprintf("Farm #{$farmId} successfully launched"));
                 } elseif ($DBFarm->Status == FARM_STATUS::RUNNING) {
                     // farm is running
                     $logger->info(sprintf("Farm #{$farmId} is already running"));
                 } else {
                     // farm can't be launched
                     $logger->info(sprintf("Farm #{$farmId} can't be launched because of it's status: {$DBFarm->Status}"));
                 }
             } catch (Exception $e) {
                 $farmRoleNotFound = true;
                 $logger->info(sprintf("Farm #{$farmId} was not found and can't be launched"));
             }
             break;
         case self::TERMINATE_FARM:
             try {
                 // get config settings
                 $farmId = $this->targetId;
                 $deleteDNSZones = (int) $this->config['deleteDNSZones'];
                 $deleteCloudObjects = (int) $this->config['deleteCloudObjects'];
                 $keepCloudObjects = $deleteCloudObjects == 1 ? 0 : 1;
                 $DBFarm = DBFarm::LoadByID($farmId);
                 if ($DBFarm->Status == FARM_STATUS::RUNNING) {
                     // terminate farm
                     $event = new FarmTerminatedEvent($deleteDNSZones, $keepCloudObjects, false, $keepCloudObjects);
                     Scalr::FireEvent($farmId, $event);
                     $logger->info(sprintf("Farm successfully terminated"));
                 } else {
                     $logger->info(sprintf("Farm #{$farmId} can't be terminated because of it's status"));
                 }
             } catch (Exception $e) {
                 $farmRoleNotFound = true;
                 $logger->info(sprintf("Farm #{$farmId} was not found and can't be terminated"));
             }
             break;
         case self::SCRIPT_EXEC:
             // generate event name
             $eventName = "Scheduler (TaskID: {$this->id})";
             if ($manual) {
                 $eventName .= ' (manual)';
             }
             try {
                 if (!\Scalr\Model\Entity\Script::findPk($this->config['scriptId'])) {
                     throw new Exception('Script not found');
                 }
                 // get executing object by target_type variable
                 switch ($this->targetType) {
                     case self::TARGET_FARM:
                         $DBFarm = DBFarm::LoadByID($this->targetId);
                         $farmId = $DBFarm->ID;
                         $farmRoleId = null;
                         $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE `status` IN (?,?) AND farm_id = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmId));
                         break;
                     case self::TARGET_ROLE:
                         $farmRoleId = $this->targetId;
                         $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE `status` IN (?,?) AND farm_roleid = ?", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $farmRoleId));
                         break;
                     case self::TARGET_INSTANCE:
                         $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE `status` IN (?,?) AND farm_roleid = ? AND `index` = ? ", array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING, $this->targetId, $this->targetServerIndex));
                         break;
                 }
                 if ($servers) {
                     $scriptSettings = array('version' => $this->config['scriptVersion'], 'scriptid' => $this->config['scriptId'], 'timeout' => $this->config['scriptTimeout'], 'issync' => $this->config['scriptIsSync'], 'params' => serialize($this->config['scriptOptions']), 'type' => Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR);
                     // send message to start executing task (starts script)
                     foreach ($servers as $server) {
                         $DBServer = DBServer::LoadByID($server['server_id']);
                         $msg = new Scalr_Messaging_Msg_ExecScript($eventName);
                         $msg->setServerMetaData($DBServer);
                         $script = Scalr_Scripting_Manager::prepareScript($scriptSettings, $DBServer);
                         $itm = new stdClass();
                         // Script
                         $itm->asynchronous = $script['issync'] == 1 ? '0' : '1';
                         $itm->timeout = $script['timeout'];
                         if ($script['body']) {
                             $itm->name = $script['name'];
                             $itm->body = $script['body'];
                         } else {
                             $itm->path = $script['path'];
                         }
                         $itm->executionId = $script['execution_id'];
                         $msg->scripts = array($itm);
                         $msg->setGlobalVariables($DBServer, true);
                         /*
                         if ($DBServer->IsSupported('2.5.12')) {
                             $api = $DBServer->scalarizr->system;
                             $api->timeout = 5;
                         
                             $api->executeScripts(
                                 $msg->scripts,
                                 $msg->globalVariables,
                                 $msg->eventName,
                                 $msg->roleName
                             );
                         } else
                         */
                         $DBServer->SendMessage($msg, false, true);
                     }
                 } else {
                     $farmRoleNotFound = true;
                 }
             } catch (Exception $e) {
                 // farm or role not found.
                 $farmRoleNotFound = true;
                 $logger->warn(sprintf("Farm, role or instances were not found, script can't be executed"));
             }
             break;
     }
     return !$farmRoleNotFound;
 }
All Usage Examples Of Scalr_Scripting_Manager::prepareScript