示例#1
0
文件: Eip.php 项目: recipe/scalr
 /**
  * Allocate and Assign Elastic IP to instance if role use it.
  *
  * @param HostUpEvent $event
  */
 public function OnHostUp(HostUpEvent $event)
 {
     if ($event->DBServer->replaceServerID) {
         return;
     }
     Modules_Platforms_Ec2_Helpers_Eip::setEipForServer($event->DBServer);
 }
示例#2
0
 public function cloneFarm($name = false)
 {
     $account = Scalr_UI_Request::getInstance()->getUser()->getAccount();
     $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
     $definition = $this->getDefinition();
     if (!$name) {
         if (!stristr($definition->name, "(clone")) {
             $name = $definition->name . ' (clone #1)';
         } else {
             preg_match("/^(.*?)\\(clone \\#([0-9]*)\\)\$/si", $definition->name, $matches);
             $name = trim($matches[1]) . " (clone #" . ($matches[2] + 1) . ")";
         }
     }
     $dbFarm = self::create($name);
     foreach ($definition->roles as $index => $role) {
         $dbFarmRole = $dbFarm->AddRole(DBRole::loadById($role->roleId), $role->platform, $role->cloudLocation, $index + 1);
         $oldRoleSettings = $dbFarmRole->GetAllSettings();
         $dbFarmRole->applyDefinition($role, true);
         Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $dbFarmRole->GetAllSettings());
         /**
          * Platfrom specified updates
          */
         if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
             Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $dbFarmRole->GetAllSettings());
             Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $dbFarmRole->GetAllSettings());
             Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $dbFarmRole->GetAllSettings());
         }
         $dbFarmRolesList[] = $dbFarmRole;
         $usedPlatforms[$role->platform] = 1;
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EC2]) {
         Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) {
         Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) {
         Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList);
     }
     $dbFarm->save();
     return $dbFarm;
 }
示例#3
0
文件: Poller.php 项目: recipe/scalr
 function handleWork($farmId)
 {
     $this->cleanup();
     $DBFarm = DBFarm::LoadByID($farmId);
     $account = Scalr_Account::init()->loadById($DBFarm->ClientID);
     $payAsYouGoTime = $account->getSetting(Scalr_Account::SETTING_BILLING_PAY_AS_YOU_GO_DATE);
     $GLOBALS["SUB_TRANSACTIONID"] = abs(crc32(posix_getpid() . $farmId));
     $GLOBALS["LOGGER_FARMID"] = $farmId;
     $this->logger->info("[" . $GLOBALS["SUB_TRANSACTIONID"] . "] Begin polling farm (ID: {$DBFarm->ID}, Name: {$DBFarm->Name}, Status: {$DBFarm->Status})");
     //
     // Collect information from database
     //
     $servers_count = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id = ? AND status != ?", array($DBFarm->ID, SERVER_STATUS::TERMINATED));
     $this->logger->info("[FarmID: {$DBFarm->ID}] Found {$servers_count} farm instances in database");
     if ($DBFarm->Status == FARM_STATUS::TERMINATED && $servers_count == 0) {
         return;
     }
     foreach ($DBFarm->GetServersByFilter(array(), array('status' => SERVER_STATUS::PENDING_LAUNCH)) as $DBServer) {
         try {
             if ($DBServer->status != SERVER_STATUS::PENDING && $DBServer->status != SERVER_STATUS::PENDING_TERMINATE) {
                 $p = PlatformFactory::NewPlatform($DBServer->platform);
                 if (!$p->IsServerExists($DBServer)) {
                     try {
                         $serverInfo = $p->GetServerExtendedInformation($DBServer);
                     } catch (Exception $e) {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: {$DBFarm->ID}] Crash check for server '{$DBServer->serverId}' failed: {$e->getMessage()}"));
                     }
                     if (!$serverInfo) {
                         if ($DBServer->status != SERVER_STATUS::PENDING_TERMINATE && $DBServer->status != SERVER_STATUS::TERMINATED) {
                             if ($DBServer->GetProperty("system.crashed") == 1) {
                                 $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                                 Scalr::FireEvent($DBFarm->ID, new HostCrashEvent($DBServer));
                             } else {
                                 $DBServer->SetProperty(SERVER_PROPERTIES::REBOOTING, 0);
                                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' found in database but not found on {$DBServer->platform}. Crashed.", $DBServer->serverId)));
                                 $DBServer->SetProperty("system.crashed", "1");
                             }
                             continue;
                         }
                     } else {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: {$DBFarm->ID}] False-positive crash check: {$DBServer->serverId}"));
                         if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->fatal(sprintf("[CRASH][FarmID: {$DBFarm->ID}] InstanceID: %s, List: %s", $DBServer->GetCloudServerID(), json_encode($p->instancesListCache)));
                         }
                     }
                 } else {
                     $DBServer->SetProperty("system.crashed", "0");
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "AWS was not able to validate the provided access credentials") || stristr($e->getMessage(), "Unable to sign AWS API request. Please, check your X.509")) {
                 $env = Scalr_Environment::init()->LoadById($DBFarm->EnvID);
                 $env->status = Scalr_Environment::STATUS_INACTIVE;
                 $env->save();
                 $env->setPlatformConfig(array('system.auto-disable-reason' => $e->getMessage()), false);
                 return;
             }
             if (stristr($e->getMessage(), "Could not connect to host")) {
                 continue;
             }
             print "[0][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             continue;
         }
         try {
             $realStatus = $DBServer->GetRealStatus()->getName();
             if ($realStatus == 'stopped') {
                 $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, $realStatus);
                 continue;
             } else {
                 if ($DBServer->GetProperty(SERVER_PROPERTIES::SUB_STATUS) == 'stopped') {
                     $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, "");
                 }
             }
         } catch (Exception $e) {
         }
         try {
             if (!in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE)) && $DBServer->GetRealStatus()->isTerminated()) {
                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' (Platform: %s) not running (Real state: %s, Scalr status: %s).", $DBServer->serverId, $DBServer->platform, $DBServer->GetRealStatus()->getName(), $DBServer->status)));
                 $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                 $DBServer->SetProperty(SERVER_PROPERTIES::REBOOTING, 0);
                 Scalr::FireEvent($DBFarm->ID, new HostDownEvent($DBServer));
                 continue;
             } elseif ($DBServer->status != SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->IsRunning()) {
                 if ($DBServer->status != SERVER_STATUS::TERMINATED && $DBServer->status != SERVER_STATUS::TROUBLESHOOTING) {
                     /*
                     if ($DBServer->platform == SERVER_PLATFORMS::NIMBULA)
                     {
                         if (!$DBServer->GetProperty(NIMBULA_SERVER_PROPERTIES::USER_DATA_INJECTED))
                         {
                             $dbRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
                     
                             $ssh2Client = new Scalr_Net_Ssh2_Client();
                             $ssh2Client->addPassword(
                                 $dbRole->getProperty(DBRole::PROPERTY_NIMBULA_INIT_ROOT_USER),
                                 $dbRole->getProperty(DBRole::PROPERTY_NIMBULA_INIT_ROOT_PASS)
                             );
                     
                             $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                     
                             $port = $dbRole->getProperty(DBRole::PROPERTY_SSH_PORT);
                             if (!$port) $port = 22;
                     
                             try {
                                 $ssh2Client->connect($info['remoteIp'], $port);
                     
                                 foreach ($DBServer->GetCloudUserData() as $k=>$v)
                                     $u_data .= "{$k}={$v};";
                     
                                 $u_data = trim($u_data, ";");
                                 $ssh2Client->sendFile('/etc/scalr/private.d/.user-data', $u_data, "w+", false);
                     
                                 $DBServer->SetProperty(NIMBULA_SERVER_PROPERTIES::USER_DATA_INJECTED, 1);
                             }
                             catch(Exception $e) {
                                 Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBFarm->ID, $e->getMessage()));
                             }
                         }
                     }
                     */
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         if ($DBServer->status == SERVER_STATUS::PENDING && $DBFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
                             if ($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_VPC_INTERNET_ACCESS) != 'outbound-only') {
                                 $ipAddress = Modules_Platforms_Ec2_Helpers_Eip::setEipForServer($DBServer);
                                 if ($ipAddress) {
                                     $DBServer->remoteIp = $ipAddress;
                                     $DBServer->Save();
                                 }
                             }
                         }
                     }
                     if ($DBServer->isOpenstack()) {
                         $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_OPENSTACK_IP_POOL);
                         if (!$DBServer->remoteIp && ($DBServer->status == SERVER_STATUS::PENDING || $DBServer->status == SERVER_STATUS::INIT) && $ipPool) {
                             $osClient = $DBServer->GetEnvironmentObject()->openstack($DBServer->platform, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
                             if ($osClient->hasService('network')) {
                                 $platform = PlatformFactory::NewPlatform($DBServer->platform);
                                 $serverIps = $platform->GetServerIPAddresses($DBServer);
                                 /********* USE Quantum (Neuron) NETWORK *******/
                                 $ips = $osClient->network->floatingIps->list();
                                 //Check free existing IP
                                 $ipAssigned = false;
                                 $ipAddress = false;
                                 $ipId = false;
                                 $ipInfo = false;
                                 foreach ($ips as $ip) {
                                     if ($ip->fixed_ip_address == $serverIps['localIp'] && $ip->port_id) {
                                         $ipAddress = $ip->floating_ip_address;
                                         $ipId = $ip->id;
                                         $ipAssigned = true;
                                         $ipInfo = $ip;
                                         break;
                                     }
                                     /*
                                     if (!$ip->fixed_ip_address && !$ipAddress) {
                                         $ipAddress = $ip->floating_ip_address;
                                         $ipId = $ip->id;
                                         $ipInfo = $ip;
                                     }
                                     */
                                 }
                                 if ($ipInfo) {
                                     Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Found free floating IP: {$ipAddress} for use (" . json_encode($ipInfo) . ")"));
                                 }
                                 if (!$ipAssigned) {
                                     // Get instance port
                                     $ports = $osClient->network->ports->list();
                                     foreach ($ports as $port) {
                                         if ($port->device_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                                             $serverNetworkPort = $port->id;
                                             break;
                                         }
                                     }
                                     if (!$serverNetworkPort) {
                                         Logger::getLogger("Openstack")->error(new FarmLogMessage($DBServer->farmId, "Unable to identify network port of instance"));
                                     } else {
                                         if (!$ipAddress) {
                                             $publicNetworkId = $ipPool;
                                             /*
                                             $networks = $osClient->network->listNetworks();
                                             foreach ($networks as $network) {
                                                 if ($network->{"router:external"} == true) {
                                                     $publicNetworkId = $network->id;
                                                 }
                                             }
                                             
                                             if (!$publicNetworkId) {
                                                 Logger::getLogger("Openstack")->error(new FarmLogMessage($DBServer->farmId,
                                                                                                     "Unable to identify public network to allocate"
                                                                                                 ));
                                             } else {
                                             */
                                             $ip = $osClient->network->floatingIps->create($publicNetworkId, $serverNetworkPort);
                                             $ipAddress = $ip->floating_ip_address;
                                             $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->floating_ip_address, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id));
                                             Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Allocated new IP {$ipAddress} for port: {$serverNetworkPort}"));
                                             //}
                                         } else {
                                             /*
                                             Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId,
                                               "Updating IP {$ipAddress} ({$ipId}) with port: {$serverNetworkPort}"
                                             ));
                                             $osClient->network->floatingIps->update($ipId, $serverNetworkPort);
                                             */
                                         }
                                     }
                                 } else {
                                     Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "IP: {$ipAddress} already assigned"));
                                 }
                             } else {
                                 /********* USE NOVA NETWORK *******/
                                 //Check free existing IP
                                 $ipAssigned = false;
                                 $ipAddress = false;
                                 $ips = $osClient->servers->floatingIps->list($ipPool);
                                 foreach ($ips as $ip) {
                                     //if (!$ip->instance_id) {
                                     //	$ipAddress = $ip->ip;
                                     //}
                                     if ($ip->instance_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                                         $ipAddress = $ip->ip;
                                         $ipAssigned = true;
                                     }
                                 }
                                 //If no free IP allocate new from pool
                                 if (!$ipAddress) {
                                     $ip = $osClient->servers->floatingIps->create($ipPool);
                                     $ipAddress = $ip->ip;
                                     $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->ip, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id));
                                 }
                                 if (!$ipAssigned) {
                                     //Associate floating IP with Instance
                                     $osClient->servers->addFloatingIp($DBServer->GetCloudServerID(), $ipAddress);
                                 }
                             }
                             if ($ipAddress) {
                                 $DBServer->remoteIp = $ipAddress;
                                 $DBServer->Save();
                                 $DBServer->SetProperty(SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, null);
                             }
                         }
                     }
                     if ($DBServer->isCloudstack()) {
                         if ($DBServer->status == SERVER_STATUS::PENDING) {
                             $jobId = $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::LAUNCH_JOB_ID);
                             try {
                                 $platform = PlatformFactory::NewPlatform($DBServer->platform);
                                 $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $DBServer->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $DBServer->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $DBServer->GetEnvironmentObject()), $DBServer->platform);
                                 $res = $cs->queryAsyncJobResult($jobId);
                                 if ($res->jobresult->jobstatus == 1) {
                                     $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::TMP_PASSWORD, $res->jobresult->virtualmachine->password);
                                     $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_NAME, $res->jobresult->virtualmachine->name);
                                 }
                                 //TODO: handle failed job: $res->jobresult->jobstatus == 2
                             } catch (Exception $e) {
                                 if ($DBServer->farmId) {
                                     Logger::getLogger("CloudStack")->error(new FarmLogMessage($DBServer->farmId, $e->getMessage()));
                                 }
                             }
                         }
                     }
                     try {
                         $dtadded = strtotime($DBServer->dateAdded);
                         $DBFarmRole = $DBServer->GetFarmRoleObject();
                         $launch_timeout = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) > 0 ? $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) : 900;
                     } catch (Exception $e) {
                         if (stristr($e->getMessage(), "not found")) {
                             $DBServer->terminate('FARM_ROLE_NOT_FOUND');
                         }
                     }
                     $scripting_event = false;
                     if ($DBServer->status == SERVER_STATUS::PENDING) {
                         $event = "hostInit";
                         $scripting_event = EVENT_TYPE::HOST_INIT;
                     } elseif ($DBServer->status == SERVER_STATUS::INIT) {
                         $event = "hostUp";
                         $scripting_event = EVENT_TYPE::HOST_UP;
                     }
                     if ($scripting_event && $dtadded) {
                         $scripting_timeout = (int) $this->db->GetOne("\n                                SELECT sum(timeout)\n                                FROM farm_role_scripts\n                                WHERE event_name=? AND\n                                farm_roleid=? AND issync='1'\n                            ", array($scripting_event, $DBServer->farmRoleId));
                         if ($scripting_timeout) {
                             $launch_timeout = $launch_timeout + $scripting_timeout;
                         }
                         if ($dtadded + $launch_timeout < time() && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //Add entry to farm log
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' did not send '%s' event in %s seconds after launch (Try increasing timeouts in role settings). Considering it broken. Terminating instance.", $DBServer->serverId, $event, $launch_timeout)));
                             try {
                                 $DBServer->terminate(array('SERVER_DID_NOT_SEND_EVENT', $event, $launch_timeout), false);
                             } catch (Exception $err) {
                                 $this->logger->fatal($err->getMessage());
                             }
                         } elseif ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //DO NOT TERMINATE MONGODB INSTANCES BY TIMEOUT! IT'S NOT SAFE
                             //THINK ABOUT WORKAROUND
                         }
                     }
                     // Is IP address changed?
                     if (!$DBServer->IsRebooting()) {
                         $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                         if ($ipaddresses['remoteIp'] && $DBServer->remoteIp && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp && $DBServer->localIp != $ipaddresses['localIp']) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("RemoteIP: %s (%s), LocalIp: %s (%s) (Poller).", $DBServer->remoteIp, $ipaddresses['remoteIp'], $DBServer->localIp, $ipaddresses['localIp'])));
                             Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                         }
                         //TODO: Check health:
                     }
                 }
             } elseif ($DBServer->status == SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->isRunning()) {
                 // Is IP address changed?
                 if (!$DBServer->IsRebooting()) {
                     $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                     if ($ipaddresses['remoteIp'] && $DBServer->remoteIp && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp && $DBServer->localIp != $ipaddresses['localIp']) {
                         Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                     }
                     if ($payAsYouGoTime) {
                         $initTime = $DBServer->GetProperty(SERVER_PROPERTIES::INITIALIZED_TIME);
                         if ($initTime < $payAsYouGoTime) {
                             $initTime = $payAsYouGoTime;
                         }
                         $runningHours = ceil((time() - $initTime) / 3600);
                         $scuUsed = $runningHours * Scalr_Billing::getSCUByInstanceType($DBServer->GetFlavor());
                         $this->db->Execute("UPDATE servers_history SET scu_used = ?, scu_updated = 0 WHERE server_id = ?", array($scuUsed, $DBServer->serverId));
                     }
                     //Update GCE ServerID
                     if ($DBServer->platform == SERVER_PLATFORMS::GCE) {
                         if ($DBServer->GetProperty(GCE_SERVER_PROPERTIES::SERVER_ID) == $DBServer->serverId) {
                             $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerExtendedInformation($DBServer);
                             $DBServer->SetProperty(GCE_SERVER_PROPERTIES::SERVER_ID, $info['Cloud Server ID']);
                         }
                     }
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $env = Scalr_Environment::init()->loadById($DBServer->envId);
                         $ec2 = $env->aws($DBServer->GetCloudLocation())->ec2;
                         //TODO:
                         $isEnabled = $ec2->instance->describeAttribute($DBServer->GetCloudServerID(), InstanceAttributeType::disableApiTermination());
                         $DBServer->SetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED, $isEnabled);
                     }
                 } else {
                     //TODO: Check reboot timeout
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "not found")) {
                 print $e->getTraceAsString() . "\n";
             } else {
                 print "[1][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             }
         }
     }
 }
示例#4
0
 public function xBuildAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int')));
     $Validator = new Validator();
     $cloudFoundryStack = array();
     $nginxFound = 0;
     foreach ($this->getParam('roles') as $role) {
         $dbRole = DBRole::loadById($role['role_id']);
         if (!$dbRole->getImageId($role['platform'], $role['cloud_location'])) {
             throw new Exception(sprintf(_("Role '%s' is not available in %s on %s"), $dbRole->name, $role['platform'], $role['cloud_location']));
         }
         // Validate deployments
         $appId = $role[Scalr_Role_Behavior::ROLE_DM_APPLICATION_ID];
         if ($appId) {
             $application = Scalr_Dm_Application::init()->loadById($appId);
             $this->user->getPermissions()->validate($application);
             if (!$role[Scalr_Role_Behavior::ROLE_DM_REMOTE_PATH]) {
                 throw new Exception(sprintf("Remote path reuired for deployment on role '%s'", $dbRole->name));
             }
         }
         //-- CloudFoundryStuff
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER)) {
             $cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER] = true;
         }
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_DEA)) {
             $cloudFoundryStack[ROLE_BEHAVIORS::CF_DEA] = true;
         }
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_HEALTH_MANAGER)) {
             $cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER] = true;
         }
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_ROUTER)) {
             $cloudFoundryStack[ROLE_BEHAVIORS::CF_ROUTER] = true;
         }
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::CF_SERVICE)) {
             $cloudFoundryStack[ROLE_BEHAVIORS::CF_SERVICE] = true;
         }
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::NGINX)) {
             $nginxFound++;
         }
         //-- End CloudFoundry stuff
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
             $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES];
             $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] = (int) $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO];
             if ($role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] < 1 || $role['settings'][Scalr_Role_Behavior_RabbitMQ::ROLE_NODES_RATIO] > 100) {
                 throw new Exception(sprintf("Nodes ratio for RabbitMq role '%s' should be between 1 and 100", $dbRole->name));
             }
         }
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
             if ($role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_ENGINE] == 'ebs') {
                 if ($role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_EBS_SIZE] < 10 || $role['settings'][Scalr_Role_Behavior_MongoDB::ROLE_DATA_STORAGE_EBS_SIZE] > 1000) {
                     throw new Exception(sprintf("EBS size for mongoDB role should be between 10 and 1000 GB", $dbRole->name));
                 }
             }
         }
         /* Validate scaling */
         $minCount = (int) $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES];
         if (!$minCount && $minCount != 0) {
             $minCount = 1;
         }
         if ($minCount < 0 || $minCount > 400) {
             throw new Exception(sprintf(_("Min instances for '%s' must be a number between 1 and 400"), $dbRole->name));
         }
         $maxCount = (int) $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES];
         if (!$maxCount) {
             $maxCount = 1;
         }
         if ($maxCount < 1 || $maxCount > 400) {
             throw new Exception(sprintf(_("Max instances for '%s' must be a number between 1 and 400"), $dbRole->name));
         }
         if ($maxCount < $minCount) {
             throw new Exception(sprintf(_("Max instances should be greater or equal than Min instances for role '%s'"), $dbRole->name));
         }
         if (isset($role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL]) && $role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL] > 0) {
             $polling_interval = (int) $role['settings'][DBFarmRole::SETTING_SCALING_POLLING_INTERVAL];
         } else {
             $polling_interval = 2;
         }
         if ($polling_interval < 1 || $polling_interval > 50) {
             throw new Exception(sprintf(_("Polling interval for role '%s' must be a number between 1 and 50"), $dbRole->name));
         }
         /** Validate platform specified settings **/
         switch ($role['platform']) {
             case SERVER_PLATFORMS::EC2:
                 Modules_Platforms_Ec2_Helpers_Ebs::farmValidateRoleSettings($role['settings'], $dbRole->name);
                 Modules_Platforms_Ec2_Helpers_Eip::farmValidateRoleSettings($role['settings'], $dbRole->name);
                 Modules_Platforms_Ec2_Helpers_Elb::farmValidateRoleSettings($role['settings'], $dbRole->name);
                 if ($dbRole->hasBehavior(ROLE_BEHAVIORS::MYSQL)) {
                     if ($role['settings'][DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE] == MYSQL_STORAGE_ENGINE::EBS) {
                         if ($dbRole->generation != 2) {
                             if ($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == "" || $role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == "x-scalr-diff" || stristr($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE], 'x-scalr-custom')) {
                                 throw new Exception(sprintf(_("Requirement for EBS MySQL data storage is specific 'Placement' parameter for role '%s'"), $dbRole->name));
                             }
                         }
                     }
                 }
                 if ($dbRole->getDbMsrBehavior()) {
                     if ($role['settings'][Scalr_Db_Msr::DATA_STORAGE_ENGINE] == MYSQL_STORAGE_ENGINE::EPH) {
                         if (!$role['settings'][Scalr_Db_Msr::DATA_STORAGE_EPH_DISK]) {
                             throw new Exception(sprintf(_("Ephemeral disk settings is required for role '%s'"), $dbRole->name));
                         }
                     }
                 }
                 if ($role['settings'][DBFarmRole::SETTING_AWS_AVAIL_ZONE] == 'x-scalr-custom=') {
                     throw new Exception(sprintf(_("Availability zone for role \"%s\" should be selected"), $dbRole->name));
                 }
                 break;
             case SERVER_PLATFORMS::RDS:
                 Modules_Platforms_Rds_Helpers_Rds::farmValidateRoleSettings($role['settings'], $dbRole->name);
                 break;
             case SERVER_PLATFORMS::EUCALYPTUS:
                 Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmValidateRoleSettings($role['settings'], $dbRole->name);
                 break;
             case SERVER_PLATFORMS::CLOUDSTACK:
                 Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmValidateRoleSettings($role['settings'], $dbRole->name);
                 break;
             case SERVER_PLATFORMS::RACKSPACE:
                 Modules_Platforms_Rackspace_Helpers_Rackspace::farmValidateRoleSettings($role['settings'], $dbRole->name);
                 break;
         }
         Scalr_Helpers_Dns::farmValidateRoleSettings($role['settings'], $dbRole->name);
     }
     //Validate ClouFoundry stuff
     if (!empty($cloudFoundryStack)) {
         if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER]) {
             throw new Exception("CF CloudContoller role required for CloudFoundry stack. Please add All-in-one CF or separate CCHM role to farm");
         }
         if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER]) {
             throw new Exception("CF HealthManager role required for CloudFoundry stack. Please add All-in-one CF or separate CCHM role to farm");
         }
         if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_ROUTER]) {
             throw new Exception("CF Router role required for CloudFoundry stack. Please add All-in-one CF or separate CF Router role to farm");
         }
         if (!$cloudFoundryStack[ROLE_BEHAVIORS::CF_DEA]) {
             throw new Exception("CF DEA role required for CloudFoundry stack. Please add All-in-one CF or separate CF DEA role to farm");
         }
         if (!$nginxFound) {
             throw new Exception("Nginx load balancer role required for CloudFoundry stack. Please add it to the farm");
         }
         if ($cloudFoundryStack[ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER] > 1) {
             throw new Exception("CloudFoundry stack can work only with ONE CF CloudController role. Please leave only one CloudController role in farm");
         }
         if ($cloudFoundryStack[ROLE_BEHAVIORS::CF_HEALTH_MANAGER] > 1) {
             throw new Exception("CloudFoundry stack can work only with ONE CF HealthManager role. Please leave only one HealthManager role in farm");
         }
         if ($nginxFound > 1) {
             throw new Exception("CloudFoundry stack can work only with ONE nginx role. Please leave only one nginx role in farm");
         }
     }
     $client = Client::Load($this->user->getAccountId());
     if ($this->getParam('farmId')) {
         $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
         $this->user->getPermissions()->validate($dbFarm);
     } else {
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
         $dbFarm = new DBFarm();
         $dbFarm->Status = FARM_STATUS::TERMINATED;
     }
     if ($this->getParam('farm')) {
         $farm = $this->getParam('farm');
         $dbFarm->Name = strip_tags($farm['name']);
         $dbFarm->RolesLaunchOrder = $farm['roles_launch_order'];
         $dbFarm->Comments = trim(strip_tags($farm['description']));
     }
     if (!$Validator->IsNotEmpty($dbFarm->Name)) {
         throw new Exception(_("Farm name required"));
     }
     $dbFarm->save();
     if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) {
         $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     }
     $usedPlatforms = array();
     $dbFarmRolesList = array();
     $newFarmRolesList = array();
     foreach ($this->getParam('roles') as $role) {
         if ($role['farm_role_id']) {
             $update = true;
             $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']);
             $dbRole = DBRole::loadById($dbFarmRole->RoleID);
             $role['role_id'] = $dbFarmRole->RoleID;
         } else {
             $update = false;
             $dbRole = DBRole::loadById($role['role_id']);
             $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']);
         }
         if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
             $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES];
         }
         if ($dbFarmRole->NewRoleID) {
             continue;
         }
         if ($update) {
             $dbFarmRole->LaunchIndex = (int) $role['launch_index'];
             $dbFarmRole->Save();
         }
         $usedPlatforms[$role['platform']] = 1;
         $oldRoleSettings = $dbFarmRole->GetAllSettings();
         foreach ($role['scaling_settings'] as $k => $v) {
             $dbFarmRole->SetSetting($k, $v);
         }
         foreach ($role['settings'] as $k => $v) {
             $dbFarmRole->SetSetting($k, $v);
         }
         /****** Scaling settings ******/
         $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
         $scalingManager->setFarmRoleMetrics($role['scaling']);
         //TODO: optimize this code...
         $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID));
         // 5 = Time based scaling -> move to constants
         if ($role['scaling'][5]) {
             foreach ($role['scaling'][5] as $scal_period) {
                 $chunks = explode(":", $scal_period['id']);
                 $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n\t\t\t\t\t\tfarm_roleid\t\t= ?,\n\t\t\t\t\t\tstart_time\t\t= ?,\n\t\t\t\t\t\tend_time\t\t= ?,\n\t\t\t\t\t\tdays_of_week\t= ?,\n\t\t\t\t\t\tinstances_count\t= ?\n\t\t\t\t\t", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3]));
             }
         }
         /*****************/
         /* Update role params */
         $dbFarmRole->SetParameters($role['params']);
         /* End of role params management */
         /* Add script options to databse */
         $dbFarmRole->SetScripts($role['scripting']);
         /* End of scripting section */
         /* Add services configuration */
         $dbFarmRole->SetServiceConfigPresets($role['config_presets']);
         /* End of scripting section */
         Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
         foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
             $behavior->onFarmSave($dbFarm, $dbFarmRole);
         }
         /**
          * Platfrom specified updates
          */
         if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
             Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
         }
         $dbFarmRolesList[] = $dbFarmRole;
         $newFarmRolesList[] = $dbFarmRole->ID;
     }
     if (!$this->getParam('roleUpdate')) {
         foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
             if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) {
                 $dbFarmRole->Delete();
             }
         }
     }
     if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) {
         Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EC2]) {
         Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) {
         Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList);
     }
     $dbFarm->save();
     if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) {
         $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time());
     }
     $this->response->success('Farm successfully saved');
     $this->response->data(array('farmId' => $dbFarm->ID));
 }
示例#5
0
文件: Builder.php 项目: recipe/scalr
 public function xBuildAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int')));
     $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE);
     if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) {
         if ($this->errors['error_count'] != 0) {
             $this->response->failure();
             $this->response->data(array('errors' => $this->errors));
             return;
         }
     }
     $farm = $this->getParam('farm');
     $client = Client::Load($this->user->getAccountId());
     if ($this->getParam('farmId')) {
         $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
         $this->user->getPermissions()->validate($dbFarm);
         $dbFarm->isLocked();
         if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) {
             $userName = '******';
             $changed = explode(' ', $this->getParam('changed'));
             $changedTime = intval($changed[1]);
             try {
                 $user = new Scalr_Account_User();
                 $user->loadById($dbFarm->changedByUserId);
                 $userName = $user->getEmail();
             } catch (Exception $e) {
             }
             $this->response->failure();
             $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime))));
             return;
         }
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
     } else {
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
         $dbFarm = new DBFarm();
         $dbFarm->Status = FARM_STATUS::TERMINATED;
         $dbFarm->createdByUserId = $this->user->getId();
         $dbFarm->createdByUserEmail = $this->user->getEmail();
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
     }
     if ($this->getParam('farm')) {
         $dbFarm->Name = strip_tags($farm['name']);
         $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder'];
         $dbFarm->Comments = trim(strip_tags($farm['description']));
     }
     if (empty($dbFarm->Name)) {
         throw new Exception(_("Farm name required"));
     }
     $dbFarm->save();
     $governance = new Scalr_Governance($this->getEnvironmentId());
     if ($governance->isEnabled(Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
     }
     if (isset($farm['variables'])) {
         $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $variables->setValues($farm['variables'], 0, $dbFarm->ID, 0, '', false);
     }
     if (!$farm['timezone']) {
         $farm['timezone'] = date_default_timezone_get();
     }
     $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']);
     if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) {
         $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     }
     $virtualFarmRoles = array();
     $roles = $this->getParam('roles');
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if (strpos($role['farm_role_id'], "virtual_") !== false) {
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']);
                 $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID;
             }
         }
     }
     $usedPlatforms = array();
     $dbFarmRolesList = array();
     $newFarmRolesList = array();
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if ($role['farm_role_id']) {
                 if ($virtualFarmRoles[$role['farm_role_id']]) {
                     $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']];
                 }
                 $update = true;
                 $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']);
                 $dbRole = DBRole::loadById($dbFarmRole->RoleID);
                 $role['role_id'] = $dbFarmRole->RoleID;
                 if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) {
                     $dbFarmRole->CloudLocation = $role['cloud_location'];
                 }
             } else {
                 $update = false;
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']);
             }
             if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                 $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES];
             }
             if ($dbFarmRole->NewRoleID) {
                 continue;
             }
             if ($update) {
                 $dbFarmRole->LaunchIndex = (int) $role['launch_index'];
                 $dbFarmRole->Alias = $role['alias'];
                 $dbFarmRole->Save();
             }
             $usedPlatforms[$role['platform']] = 1;
             $oldRoleSettings = $dbFarmRole->GetAllSettings();
             // Update virtual farm_role_id with actual value
             $scripts = (array) $role['scripting'];
             if (count($virtualFarmRoles) > 0) {
                 array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
                 array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
             }
             //Audit log start
             //!TODO Enable Audit log for Farm Builder
             //             $auditLog = $this->getEnvironment()->auditLog;
             //             $docRoleSettingsBefore = new FarmRoleSettingsDocument($oldRoleSettings);
             //             $docRoleSettingsBefore['farmroleid'] = $dbFarmRole->ID;
             //             $docRoleSettings = new FarmRoleSettingsDocument(array_merge((array)$role['scaling_settings'], (array)$role['settings']));
             //             $docRoleSettings['farmroleid'] = $dbFarmRole->ID;
             $dbFarmRole->ClearSettings("chef.");
             if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) {
                 foreach ($role['scaling_settings'] as $k => $v) {
                     $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG);
                 }
             }
             foreach ($role['settings'] as $k => $v) {
                 $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG);
             }
             //             $auditLog->log('Farm has been saved', array(AuditLogTags::TAG_UPDATE), $docRoleSettings, $docRoleSettingsBefore);
             //             unset($docRoleSettings);
             //             unset($docRoleSettingsBefore);
             //Audit log finish
             /****** Scaling settings ******/
             $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
             $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array());
             //TODO: optimize this code...
             $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID));
             // 5 = Time based scaling -> move to constants
             if ($role['scaling'][5]) {
                 foreach ($role['scaling'][5] as $scal_period) {
                     $chunks = explode(":", $scal_period['id']);
                     $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n                            farm_roleid\t\t= ?,\n                            start_time\t\t= ?,\n                            end_time\t\t= ?,\n                            days_of_week\t= ?,\n                            instances_count\t= ?\n                        ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3]));
                 }
             }
             /*****************/
             /* Update role params */
             $dbFarmRole->SetParameters((array) $role['params']);
             /* End of role params management */
             /* Add script options to databse */
             $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']);
             /* End of scripting section */
             /* Add services configuration */
             $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']);
             /* End of scripting section */
             /* Add storage configuration */
             //try {
             $dbFarmRole->getStorage()->setConfigs((array) $role['storages']['configs']);
             //} catch (FarmRoleStorageException $e) {
             //    $errors[] = array('farm_role_id' => 1, 'tab' => 'storage', 'error' => $e->getMessage());
             //}
             $farmRoleVariables->setValues($role['variables'], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false);
             Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                 $behavior->onFarmSave($dbFarm, $dbFarmRole);
             }
             /**
              * Platfrom specified updates
              */
             if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
                 Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
             if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) {
                 Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
             $dbFarmRolesList[] = $dbFarmRole;
             $newFarmRolesList[] = $dbFarmRole->ID;
         }
     }
     if (!$this->getParam('roleUpdate')) {
         foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
             if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) {
                 $dbFarmRole->Delete();
             }
         }
     }
     if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) {
         Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EC2]) {
         Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) {
         Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList);
     }
     $dbFarm->save();
     if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) {
         $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time());
     }
     $this->response->success('Farm successfully saved');
     $this->response->data(array('farmId' => $dbFarm->ID));
 }
示例#6
0
 public function cloneFarm($name = false, Scalr_Account_User $user, $envId)
 {
     $account = $user->getAccount();
     $account->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
     $definition = $this->getDefinition();
     if (!$name) {
         $template = "";
         if (!stristr($definition->name, "clone")) {
             $template = $definition->name . ' (clone #%s)';
             $i = 1;
         } else {
             preg_match("/^(.*?)\\(clone \\#([0-9]*)\\)\$/si", $definition->name, $matches);
             $template = trim($matches[1]) . " (clone #%s)";
             $i = $matches[2] + 1;
         }
         while (true) {
             $name = sprintf($template, $i);
             if (!$this->DB->GetOne("SELECT id FROM farms WHERE name = ? AND env_id = ? LIMIT 1", array($name, $this->EnvID))) {
                 break;
             } else {
                 $i++;
             }
         }
     }
     $dbFarm = self::create($name, $user, $envId);
     $dbFarm->createdByUserId = $user->id;
     $dbFarm->createdByUserEmail = $user->getEmail();
     $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $definition->settings[DBFarm::SETTING_TIMEZONE]);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $definition->settings[DBFarm::SETTING_EC2_VPC_ID]);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $definition->settings[DBFarm::SETTING_EC2_VPC_REGION]);
     $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $definition->settings[DBFarm::SETTING_SZR_UPD_REPOSITORY]);
     $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $definition->settings[DBFarm::SETTING_SZR_UPD_SCHEDULE]);
     $variables = new Scalr_Scripting_GlobalVariables($envId, Scalr_Scripting_GlobalVariables::SCOPE_FARM);
     $variables->setValues($definition->globalVariables, 0, $dbFarm->ID, 0);
     foreach ($definition->roles as $index => $role) {
         $dbFarmRole = $dbFarm->AddRole(DBRole::loadById($role->roleId), $role->platform, $role->cloudLocation, $index + 1, $role->alias);
         $oldRoleSettings = $dbFarmRole->GetAllSettings();
         $dbFarmRole->applyDefinition($role, true);
         $newSettings = $dbFarmRole->GetAllSettings();
         Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
         /**
          * Platfrom specified updates
          */
         if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
             Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
             Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
             Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
         }
         if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) {
             Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
         }
         $dbFarmRolesList[] = $dbFarmRole;
         $usedPlatforms[$role->platform] = 1;
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EC2]) {
         Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) {
         Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) {
         Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList);
     }
     $dbFarm->save();
     return $dbFarm;
 }