当前位置: 首页>>代码示例>>PHP>>正文


PHP Scalr::FireEvent方法代码示例

本文整理汇总了PHP中Scalr::FireEvent方法的典型用法代码示例。如果您正苦于以下问题:PHP Scalr::FireEvent方法的具体用法?PHP Scalr::FireEvent怎么用?PHP Scalr::FireEvent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Scalr的用法示例。


在下文中一共展示了Scalr::FireEvent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: worker

 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::worker()
  */
 public function worker($request)
 {
     //Warming up static DI cache
     \Scalr::getContainer()->warmup();
     // Reconfigure observers
     \Scalr::ReconfigureObservers();
     try {
         $dbFarm = DBFarm::LoadByID($request->farmId);
         $curDate = new DateTime();
         $tdValue = $dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE);
         if ($tdValue) {
             $td = new DateTime($tdValue);
             if ($td < $curDate) {
                 //Terminates farm
                 $event = new FarmTerminatedEvent(0, 1, false, 1);
                 SettingEntity::increase(SettingEntity::LEASE_TERMINATE_FARM);
                 \Scalr::FireEvent($request->farmId, $event);
                 $this->log('INFO', sprintf('Farm: %s [ID: %d] was terminated by lease manager', $dbFarm->Name, $dbFarm->ID));
             } else {
                 // only inform user
                 $days = $td->diff($curDate)->days;
                 $notifications = json_decode($dbFarm->GetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND), true);
                 $governance = new Scalr_Governance($dbFarm->EnvID);
                 $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, 'notifications');
                 if (is_array($settings)) {
                     foreach ($settings as $n) {
                         if (!$notifications[$n['key']] && $n['period'] >= $days) {
                             $mailer = \Scalr::getContainer()->mailer;
                             $tdHuman = Scalr_Util_DateTime::convertDateTime($td, $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'M j, Y');
                             if ($n['to'] == 'owner') {
                                 $user = new Scalr_Account_User();
                                 $user->loadById($dbFarm->createdByUserId);
                                 if (\Scalr::config('scalr.auth_mode') == 'ldap') {
                                     $email = $user->getSetting(Scalr_Account_User::SETTING_LDAP_EMAIL);
                                     if (!$email) {
                                         $email = $user->getEmail();
                                     }
                                 } else {
                                     $email = $user->getEmail();
                                 }
                                 $mailer->addTo($email);
                             } else {
                                 foreach (explode(',', $n['emails']) as $email) {
                                     $mailer->addTo(trim($email));
                                 }
                             }
                             $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_terminate.eml', array('{{terminate_date}}' => $tdHuman, '{{farm}}' => $dbFarm->Name, '{{envName}}' => $dbFarm->GetEnvironmentObject()->name, '{{envId}}' => $dbFarm->GetEnvironmentObject()->id));
                             $notifications[$n['key']] = 1;
                             $dbFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, json_encode($notifications));
                             $this->log('INFO', "Notification was sent by key: %s about farm: %s [ID: %d] by lease manager", $n['key'], $dbFarm->Name, $dbFarm->ID);
                         }
                     }
                 }
             }
         }
     } catch (Exception $e) {
         throw $e;
     }
     return $request;
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:64,代码来源:LeaseManager.php

示例2: tearDownAfterClass

 /**
  * {@inheritdoc}
  * @see Scalr\Tests\TestCase::tearDownAfterClass()
  */
 public static function tearDownAfterClass()
 {
     foreach (static::$testData as $rec) {
         if ($rec['class'] === Farm::class) {
             $entry = $rec['pk'];
             $farm = Farm::findPk(...$entry);
             /* @var $farm Farm */
             if (!empty($farm)) {
                 try {
                     \Scalr::FireEvent($farm->id, new FarmTerminatedEvent(false, false, false, false, true, static::$user->id));
                     foreach ($farm->servers as $server) {
                         try {
                             $dbServer = Server::findPk($server->serverId);
                             /* @var $dbServer Server */
                             $dbServer->terminate(Server::TERMINATE_REASON_FARM_TERMINATED, true, static::$user);
                         } catch (Exception $e) {
                             \Scalr::logException($e);
                         }
                         $server->delete();
                     }
                 } catch (Exception $e) {
                     \Scalr::logException($e);
                 }
             }
         }
     }
     parent::tearDownAfterClass();
 }
开发者ID:scalr,项目名称:scalr,代码行数:32,代码来源:ServersTest.php

示例3: xSaveAction

 public function xSaveAction()
 {
     $this->request->defineParams(array('presetId' => array('type' => 'int'), 'config' => array('type' => 'array')));
     if (!$this->getParam('presetId')) {
         if (!in_array($this->getParam('roleBehavior'), array(ROLE_BEHAVIORS::MYSQL, ROLE_BEHAVIORS::MYSQL2, ROLE_BEHAVIORS::PERCONA, ROLE_BEHAVIORS::APACHE, ROLE_BEHAVIORS::MEMCACHED, ROLE_BEHAVIORS::NGINX, ROLE_BEHAVIORS::REDIS))) {
             $err['roleBehavior'] = _("Please select service name");
         }
         if (!$this->getParam('presetName')) {
             $err['presetName'] = _("Preset name required");
         } else {
             if (strlen($this->getParam('presetName')) < 5) {
                 $err['presetName'] = _("Preset name should be 5 chars or longer");
             } elseif (!preg_match("/^[A-Za-z0-9-]+\$/", $this->getParam('presetName'))) {
                 $err['presetName'] = _("Preset name should be alpha-numeric");
             } elseif (strtolower($this->getParam('presetName')) == "default") {
                 $err['presetName'] = _("default is reserverd name");
             } elseif ($this->getParam('roleBehavior') && $this->db->GetOne("SELECT id FROM service_config_presets WHERE name = ? AND role_behavior = ? AND id != ? AND env_id = ? LIMIT 1", array($this->getParam('presetName'), $this->getParam('roleBehavior'), (int) $this->getParam('presetId'), $this->getEnvironmentId()))) {
                 $err['presetName'] = _("Preset with selected name already exists");
             }
         }
     }
     if (count($err) == 0) {
         $serviceConfiguration = Scalr_ServiceConfiguration::init();
         if ($this->getParam('presetId')) {
             $serviceConfiguration->loadById($this->getParam('presetId'));
             $this->user->getPermissions()->validate($serviceConfiguration);
         } else {
             $serviceConfiguration->loadBy(array('client_id' => $this->user->getAccountId(), 'env_id' => $this->getEnvironmentId(), 'name' => $this->getParam('presetName'), 'role_behavior' => $this->getParam('roleBehavior')));
         }
         $config = $this->getParam('config');
         foreach ($config as $k => $v) {
             $serviceConfiguration->setParameterValue($k, $v);
         }
         foreach ($serviceConfiguration->getParameters() as $param) {
             if ($param->getType() == 'boolean') {
                 if (!$config[$param->getName()]) {
                     $serviceConfiguration->setParameterValue($param->getName(), '0');
                 }
             }
         }
         $serviceConfiguration->name = $this->getParam('presetName');
         $serviceConfiguration->save();
         //TODO:
         $resetToDefaults = false;
         Scalr::FireEvent(null, new ServiceConfigurationPresetChangedEvent($serviceConfiguration, $resetToDefaults));
         $this->response->success('Preset successfully saved');
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => $err));
     }
 }
开发者ID:recipe,项目名称:scalr,代码行数:51,代码来源:Presets.php

示例4: FireCustomEvent

 public function FireCustomEvent($ServerID, $EventName, array $Params = array())
 {
     $this->restrictAccess(Acl::RESOURCE_GENERAL_CUSTOM_EVENTS);
     $dbServer = DBServer::LoadByID($ServerID);
     if ($dbServer->envId != $this->Environment->id) {
         throw new Exception(sprintf("Server ID #%s not found", $ServerID));
     }
     if (\Scalr\Model\Entity\EventDefinition::isExist($EventName, $this->user->getAccountId(), $this->Environment->id)) {
         $event = new CustomEvent($dbServer, $EventName, (array) $Params);
     } else {
         throw new Exception(sprintf("Event %s is not defined", $EventName));
     }
     Scalr::FireEvent($dbServer->farmId, $event);
     $response = $this->CreateInitialResponse();
     $response->EventID = $event->GetEventID();
     return $response;
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:17,代码来源:class.ScalrAPI_2_3_0.php

示例5: xTroubleshootAction

 public function xTroubleshootAction()
 {
     $this->request->defineParams(array('serverId'));
     $dbServer = DBServer::LoadByID($this->getParam('serverId'));
     $this->user->getPermissions()->validate($dbServer);
     $dbServer->status = SERVER_STATUS::TROUBLESHOOTING;
     $dbServer->Save();
     // Send before host terminate to the server to detach all used volumes.
     $msg = new Scalr_Messaging_Msg_BeforeHostTerminate($dbServer);
     if ($dbServer->farmRoleId != 0) {
         foreach (Scalr_Role_Behavior::getListForFarmRole($dbServer->GetFarmRoleObject()) as $behavior) {
             $msg = $behavior->extendMessage($msg, $dbServer);
         }
     }
     $dbServer->SendMessage($msg);
     Scalr::FireEvent($dbServer->farmId, new HostDownEvent($dbServer));
     $this->response->success();
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:18,代码来源:Servers.php

示例6: FireCustomEvent

 public function FireCustomEvent($ServerID, $EventName, array $Params = array())
 {
     $this->restrictAccess(Acl::RESOURCE_GENERAL_CUSTOM_EVENTS);
     $isEventExist = $this->DB->GetOne("\n            SELECT id FROM event_definitions\n            WHERE name = ? AND env_id = ?\n            LIMIT 1\n        ", array($EventName, $this->Environment->id));
     $dbServer = DBServer::LoadByID($ServerID);
     if ($dbServer->envId != $this->Environment->id) {
         throw new Exception(sprintf("Server ID #%s not found", $ServerID));
     }
     if ($isEventExist) {
         $event = new CustomEvent($dbServer, $EventName, (array) $Params);
     } else {
         throw new Exception(sprintf("Event %s is not defined", $EventName));
     }
     Scalr::FireEvent($dbServer->farmId, $event);
     $response = $this->CreateInitialResponse();
     $response->EventID = $event->GetEventID();
     return $response;
 }
开发者ID:rickb838,项目名称:scalr,代码行数:18,代码来源:class.ScalrAPI_2_3_0.php

示例7: farmUpdateRoleSettings

 public static function farmUpdateRoleSettings(DBFarmRole $DBFarmRole, $oldSettings, $newSettings)
 {
     $db = Core::GetDBInstance();
     $DBFarm = $DBFarmRole->GetFarmObject();
     if (!$oldSettings[DBFarmRole::SETTING_AWS_USE_ELASIC_IPS] && $newSettings[DBFarmRole::SETTING_AWS_USE_ELASIC_IPS]) {
         $servers = $DBFarmRole->GetServersByFilter(array('status' => SERVER_STATUS::RUNNING));
         if (count($servers) == 0) {
             return;
         }
         $AmazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($DBFarmRole->CloudLocation, $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE));
         foreach ($servers as $DBServer) {
             $address = $AmazonEC2Client->AllocateAddress();
             $db->Execute("INSERT INTO elastic_ips SET env_id=?, farmid=?, farm_roleid=?, ipaddress=?, state='0', instance_id='', clientid=?, instance_index=?", array($DBServer->envId, $DBServer->farmId, $DBServer->farmRoleId, $address->publicIp, $DBServer->clientId, $DBServer->index));
             Logger::getLogger(__CLASS__)->info(sprintf(_("Allocated new IP: %s"), $address->publicIp));
             // Waiting...
             Logger::getLogger(__CLASS__)->debug(_("Waiting 5 seconds..."));
             sleep(5);
             $assign_retries = 1;
             while (true) {
                 try {
                     // Associate elastic ip address with instance
                     $AmazonEC2Client->AssociateAddress($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $address->publicIp);
                 } catch (Exception $e) {
                     if (!stristr($e->getMessage(), "does not belong to you") || $assign_retries == 3) {
                         throw new Exception($e->getMessage());
                     } else {
                         // Waiting...
                         Logger::getLogger(__CLASS__)->debug(_("Waiting 2 seconds..."));
                         sleep(2);
                         $assign_retries++;
                         continue;
                     }
                 }
                 break;
             }
             Logger::getLogger(__CLASS__)->info(sprintf(_("IP: %s assigned to instance '%s'"), $address->publicIp, $DBServer->serverId));
             // Update leastic IPs table
             $db->Execute("UPDATE elastic_ips SET state='1', server_id=? WHERE ipaddress=?", array($DBServer->serverId, $address->publicIp));
             Scalr::FireEvent($DBFarmRole->FarmID, new IPAddressChangedEvent($DBServer, $address->publicIp));
         }
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:42,代码来源:Eip.php

示例8: handleMessage

 public function handleMessage(Scalr_Messaging_Msg $message, DBServer $dbServer)
 {
     try {
         $dbFarmRole = $dbServer->GetFarmRoleObject();
     } catch (Exception $e) {
     }
     switch (get_class($message)) {
         case "Scalr_Messaging_Msg_HostUp":
             if ($message->dbType && in_array($message->dbType, array(ROLE_BEHAVIORS::REDIS, ROLE_BEHAVIORS::POSTGRESQL, ROLE_BEHAVIORS::MYSQL2))) {
                 $dbMsrInfo = Scalr_Db_Msr_Info::init($dbFarmRole, $dbServer, $message->dbType);
                 $dbMsrInfo->setMsrSettings($message->{$message->dbType});
             }
             break;
         case "Scalr_Messaging_Msg_DbMsr_PromoteToMasterResult":
             if (Scalr_Db_Msr::onPromoteToMasterResult($message, $dbServer)) {
                 Scalr::FireEvent($dbServer->farmId, new NewDbMsrMasterUpEvent($dbServer));
             }
             break;
         case "Scalr_Messaging_Msg_DbMsr_CreateDataBundleResult":
             if ($message->status == "ok") {
                 Scalr_Db_Msr::onCreateDataBundleResult($message, $dbServer);
             } else {
                 $dbFarmRole->SetSetting(Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, 0);
                 //TODO: store last error
             }
             break;
         case "Scalr_Messaging_Msg_DbMsr_CreateBackupResult":
             if ($message->status == "ok") {
                 Scalr_Db_Msr::onCreateBackupResult($message, $dbServer);
             } else {
                 $dbFarmRole->SetSetting(Scalr_Db_Msr::DATA_BACKUP_IS_RUNNING, 0);
                 //TODO: store last error
             }
             break;
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:36,代码来源:DbMsrBehavior.php

示例9: terminateAction

 /**
  * Terminates specified farm
  *
  * @param   int     $farmId Unique farm identifier
  * @param   bool    $force  If true skip all shutdown routines (do not process the BeforeHostTerminate event)
  *
  * @return ResultEnvelope
  * @throws ApiErrorException
  */
 public function terminateAction($farmId, $force = false)
 {
     $farm = $this->getFarm($farmId, Acl::PERM_FARMS_LAUNCH_TERMINATE);
     try {
         $farm->checkLocked();
         \Scalr::FireEvent($farm->id, new FarmTerminatedEvent(false, false, false, false, $force, $this->getUser()->id));
     } catch (LockedException $e) {
         throw new ApiErrorException(409, ErrorMessage::ERR_LOCKED, $e->getMessage() . ", please unlock it first", $e->getCode(), $e);
     }
     $farmAdapter = $this->adapter('farm');
     return $this->result($farmAdapter->toData($farm));
 }
开发者ID:mheydt,项目名称:scalr,代码行数:21,代码来源:Farms.php

示例10: terminate

 /**
  * Marks server as to be terminated.
  *
  * @param   integer|array           $reason      The reason possibly with the format parameters.
  * @param   bool                   $forcefully  optional Method: forcefully (true) | gracefully (false)
  * @param   Scalr_Account_User|int $user        optional The user object or its unique identifier
  */
 public function terminate($reason, $forcefully = null, $user = null)
 {
     if (in_array($this->status, array(SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TERMINATED))) {
         return;
     }
     $forcefully = $forcefully === null ? true : (bool) $forcefully;
     //Ensures handling identifier of the user instead of the object
     if ($user !== null && !$user instanceof \Scalr_Account_User) {
         try {
             $user = Scalr_Account_User::init()->loadById(intval($user));
         } catch (\Exception $e) {
         }
     }
     $fnGetReason = function ($reasonId) {
         $args = func_get_args();
         $args[0] = DBServer::getTerminateReason($reasonId);
         return [call_user_func_array('sprintf', $args), $reasonId];
     };
     list($reason, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason);
     //Set who does terminate the server
     if ($user instanceof \Scalr_Account_User) {
         $this->SetProperties(array(\SERVER_PROPERTIES::TERMINATED_BY_ID => $user->id, \SERVER_PROPERTIES::TERMINATED_BY_EMAIL => $user->getEmail()));
     }
     $this->SetProperties([SERVER_PROPERTIES::REBOOTING => 0]);
     $this->update(['status' => SERVER_STATUS::PENDING_TERMINATE, 'dateShutdownScheduled' => date("Y-m-d H:i:s", $forcefully ? time() : strtotime(Scalr::config('scalr.system.server_terminate_timeout')))]);
     $this->getServerHistory()->markAsTerminated($reason, $reasonId);
     if (isset($this->farmId)) {
         Scalr::FireEvent($this->farmId, new BeforeHostTerminateEvent($this, false));
         // If instance was terminated outside scalr, we need manually fire HostDown
         if ($reasonId == self::TERMINATE_REASON_CRASHED) {
             Scalr::FireEvent($this->farmId, new HostDownEvent($this, false));
         }
     }
 }
开发者ID:mheydt,项目名称:scalr,代码行数:41,代码来源:class.DBServer.php

示例11: ScriptingLogMessage

                    }
                    $Logger->warn(new ScriptingLogMessage($req_FarmID, $event_name, $DBServer->serverId, sprintf(_("Script '%s' execution result (Execution time: %s seconds). %s %s"), $data['script_path'], $data['time_elapsed'], $stderr, $stdout)));
                    break;
                case "rebundleStatus":
                    if ($data['bundletaskid']) {
                        try {
                            $BundleTask = BundleTask::LoadById($data['bundletaskid']);
                            if ($BundleTask->serverId == $DBServer->serverId) {
                                $BundleTask->Log($data['message']);
                            }
                        } catch (Exception $e) {
                        }
                    }
                    break;
                case "logEvent":
                    $message = base64_decode($data["msg"]);
                    $tm = date('YmdH');
                    $hash = md5("{$DBServer->serverId}:{$message}:{$req_FarmID}:{$data['source']}:{$tm}", true);
                    $db->Execute("INSERT DELAYED INTO logentries SET id=?, serverid=?, message=?, `time`=?, severity=?, `source`=?, farmid=? ON DUPLICATE KEY UPDATE cnt = cnt + 1, `time` = ?", array($hash, $DBServer->serverId, $message, time(), $data["severity"], $data["source"], $req_FarmID, time()));
                    break;
            }
        }
    }
    if ($event) {
        Scalr::FireEvent($DBFarm->ID, $event);
    }
    exit;
} catch (Exception $e) {
    header("HTTP/1.0 500 Internal Server Error");
    die($e->getMessage());
}
开发者ID:rickb838,项目名称:scalr,代码行数:31,代码来源:event_handler.php

示例12: execute

 /**
  * @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;
//.........这里部分代码省略.........
开发者ID:rickb838,项目名称:scalr,代码行数:101,代码来源:SchedulerTask.php

示例13: Delete

 /**
  * Delete role from farm
  * @return void
  */
 public function Delete()
 {
     foreach ($this->GetServersByFilter() as $DBServer) {
         /** @var DBServer $DBServer */
         if ($DBServer->status != SERVER_STATUS::TERMINATED) {
             try {
                 $DBServer->terminate(DBServer::TERMINATE_REASON_ROLE_REMOVED);
             } catch (Exception $e) {
             }
             $event = new HostDownEvent($DBServer);
             Scalr::FireEvent($DBServer->farmId, $event);
         }
     }
     //
     $this->DB->Execute("DELETE FROM farm_roles WHERE id=?", array($this->ID));
     // Clear farm role options & scripts
     $this->DB->Execute("DELETE FROM farm_role_options WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM farm_role_service_config_presets WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM farm_role_scaling_metrics WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM farm_role_service_config_presets WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM farm_role_settings WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM farm_role_scripting_targets WHERE `target`=? AND `target_type` = 'farmrole'", array($this->ID));
     $this->DB->Execute("DELETE FROM ec2_ebs WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM elastic_ips WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("DELETE FROM storage_volumes WHERE farm_roleid=?", array($this->ID));
     // Clear apache vhosts and update DNS zones
     $this->DB->Execute("UPDATE apache_vhosts SET farm_roleid='0', farm_id='0' WHERE farm_roleid=?", array($this->ID));
     $this->DB->Execute("UPDATE dns_zones SET farm_roleid='0' WHERE farm_roleid=?", array($this->ID));
     // Clear scheduler tasks
     $this->DB->Execute("DELETE FROM scheduler WHERE target_id = ? AND target_type IN(?,?)", array($this->ID, Scalr_SchedulerTask::TARGET_ROLE, Scalr_SchedulerTask::TARGET_INSTANCE));
 }
开发者ID:rickb838,项目名称:scalr,代码行数:36,代码来源:class.DBFarmRole.php

示例14: worker

 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::worker()
  */
 public function worker($request)
 {
     //Warming up static DI cache
     \Scalr::getContainer()->warmup();
     // Reconfigure observers
     \Scalr::ReconfigureObservers();
     try {
         $dbFarm = DBFarm::LoadByID($request->farmId);
         $curDate = new DateTime();
         $tdValue = $dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE);
         if ($tdValue) {
             $td = new DateTime($tdValue);
             if ($td < $curDate) {
                 //Terminates farm
                 SettingEntity::increase(SettingEntity::LEASE_TERMINATE_FARM);
                 //Ajdusts both account & environment for the audit log
                 \Scalr::getContainer()->auditlogger->setAccountId($dbFarm->ClientID)->setAccountId($dbFarm->EnvID);
                 \Scalr::FireEvent($request->farmId, new FarmTerminatedEvent(0, 1, false, 1, true, null));
                 $this->log('INFO', sprintf('Farm: %s [ID: %d] was terminated by lease manager', $dbFarm->Name, $dbFarm->ID));
             } else {
                 // only inform user
                 $days = $td->diff($curDate)->days;
                 $notifications = json_decode($dbFarm->GetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND), true);
                 $governance = new Scalr_Governance($dbFarm->EnvID);
                 $settings = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE, 'notifications');
                 if (is_array($settings)) {
                     foreach ($settings as $n) {
                         if (!$notifications[$n['key']] && $n['period'] >= $days) {
                             $mailer = \Scalr::getContainer()->mailer;
                             $tdHuman = Scalr_Util_DateTime::convertDateTime($td, $dbFarm->GetSetting(Entity\FarmSetting::TIMEZONE), 'M j, Y');
                             /* @var $user Entity\Account\User */
                             if ($n['to'] == 'owner') {
                                 if ($dbFarm->ownerId) {
                                     $user = Entity\Account\User::findPk($dbFarm->ownerId);
                                 } else {
                                     $user = Entity\Account\User::findOne([['accountId' => $dbFarm->ClientID], ['type' => Entity\Account\User::TYPE_ACCOUNT_OWNER]]);
                                 }
                                 if (\Scalr::config('scalr.auth_mode') == 'ldap') {
                                     $email = $user->getSetting(Entity\Account\User\UserSetting::NAME_LDAP_EMAIL);
                                     if (!$email) {
                                         $email = $user->email;
                                     }
                                 } else {
                                     $email = $user->email;
                                 }
                                 $mailer->addTo($email);
                             } else {
                                 foreach (explode(',', $n['emails']) as $email) {
                                     $mailer->addTo(trim($email));
                                 }
                             }
                             $mailer->sendTemplate(SCALR_TEMPLATES_PATH . '/emails/farm_lease_terminate.eml.php', array('terminateDate' => $tdHuman, 'farm' => $dbFarm->Name, 'envName' => $dbFarm->GetEnvironmentObject()->name, 'envId' => $dbFarm->GetEnvironmentObject()->id, 'showOwnerWarning' => !$dbFarm->ownerId));
                             $notifications[$n['key']] = 1;
                             $dbFarm->SetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND, json_encode($notifications));
                             $this->log('INFO', "Notification was sent by key: %s about farm: %s [ID: %d] by lease manager", $n['key'], $dbFarm->Name, $dbFarm->ID);
                         }
                     }
                 }
             }
         }
     } catch (Exception $e) {
         throw $e;
     }
     return $request;
 }
开发者ID:scalr,项目名称:scalr,代码行数:69,代码来源:LeaseManager.php

示例15: worker


//.........这里部分代码省略.........
                     try {
                         $bundleTask = BundleTask::LoadById($message->bundleTaskId);
                     } catch (Exception $e) {
                     }
                     if ($bundleTask) {
                         if ($bundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PREPARING) {
                             if ($message->status == 'ok') {
                                 $metaData = array('szr_version' => $message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION], 'os' => $message->os, 'software' => $message->software);
                                 $bundleTask->setMetaData($metaData);
                                 $bundleTask->Save();
                                 PlatformFactory::NewPlatform($bundleTask->platform)->CreateServerSnapshot($bundleTask);
                             } else {
                                 $bundleTask->SnapshotCreationFailed("PrepareBundle procedure failed: {$message->lastError}");
                             }
                         }
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_DeployResult) {
                     try {
                         $deploymentTask = Scalr_Model::init(Scalr_Model::DM_DEPLOYMENT_TASK)->loadById($message->deployTaskId);
                     } catch (Exception $e) {
                     }
                     if ($deploymentTask) {
                         if ($message->status == 'error') {
                             $deploymentTask->status = Scalr_Dm_DeploymentTask::STATUS_FAILED;
                             $deploymentTask->lastError = $message->lastError;
                         } else {
                             $deploymentTask->status = Scalr_Dm_DeploymentTask::STATUS_DEPLOYED;
                             $deploymentTask->dtDeployed = date("Y-m-d H:i:s");
                         }
                         $deploymentTask->save();
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_Hello) {
                     $event = $this->onHello($message, $dbserver);
                 } elseif ($message instanceof Scalr_Messaging_Msg_FireEvent) {
                     //Validate event
                     $isEventExist = $this->db->GetOne("\n                            SELECT id FROM event_definitions\n                            WHERE name = ? AND ((env_id = ? AND account_id = ?) OR (env_id IS NULL AND account_id = ?) OR (env_id IS NULL AND account_id IS NULL))\n                            LIMIT 1\n                        ", array($message->eventName, $dbserver->envId, $dbserver->clientId, $dbserver->clientId));
                     if ($isEventExist) {
                         $event = new CustomEvent($dbserver, $message->eventName, (array) $message->params);
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_HostUpdate) {
                     try {
                         $dbFarmRole = $dbserver->GetFarmRoleObject();
                     } catch (Exception $e) {
                     }
                     if ($dbFarmRole instanceof DBFarmRole) {
                         foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                             $behavior->handleMessage($message, $dbserver);
                         }
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_MongoDb) {
                     /********* MONGODB *********/
                     try {
                         $dbFarmRole = $dbserver->GetFarmRoleObject();
                     } catch (Exception $e) {
                     }
                     if ($dbFarmRole instanceof DBFarmRole) {
                         foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                             $behavior->handleMessage($message, $dbserver);
                         }
                     }
                 } elseif ($message instanceof Scalr_Messaging_Msg_DbMsr) {
                     /********* DBMSR *********/
                     try {
                         $dbFarmRole = $dbserver->GetFarmRoleObject();
                     } catch (Exception $e) {
                     }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:67,代码来源:ScalarizrMessaging.php


注:本文中的Scalr::FireEvent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。