Пример #1
0
 /**
  *
  * Enter description here ...
  * @param DBRole $dbRole
  * @return Scalr_Role_Behavior
  */
 public static function getListForRole(DBRole $role)
 {
     $list = array();
     foreach ($role->getBehaviors() as $behavior) {
         $list[] = self::loadByName($behavior);
     }
     return $list;
 }
Пример #2
0
 /**
  * Upload S3cmd config file, AWS private key and certificate to instance aftre instance boot.
  * Also execute hostInit hooks from hooks/hostInit folder
  *
  * @param array $instanceinfo
  * @param string $local_ip
  * @param string $remote_ip
  * @param string $public_key
  */
 public function OnHostInit(HostInitEvent $event)
 {
     if ($event->DBServer->IsSupported("0.5")) {
         $this->Logger->info("Scalarizr instance. Skipping SSH observer...");
         return true;
     }
     if ($event->DBServer->platform != SERVER_PLATFORMS::EC2) {
         return true;
     }
     // Get farm info and client info from database;
     $DBFarm = DBFarm::LoadByID($this->FarmID);
     $DBRole = DBRole::loadById($event->DBServer->roleId);
     // Get Role info
     $ssh_port = $DBRole->getProperty(DBRole::PROPERTY_SSH_PORT) ? $DBRole->getProperty(DBRole::PROPERTY_SSH_PORT) : 22;
     // Generate s3cmd config file
     $s3cfg = CONFIG::$S3CFG_TEMPLATE;
     $s3cfg = str_replace("[access_key]", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY), $s3cfg);
     $s3cfg = str_replace("[secret_key]", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY), $s3cfg);
     $s3cfg = str_replace("\r\n", "\n", $s3cfg);
     // Prepare public key for SSH connection
     $pub_key_file = tempnam("/tmp", "AWSK");
     $res = file_put_contents($pub_key_file, $event->PublicKey);
     $this->Logger->debug("Creating temporary file for public key: {$res}");
     try {
         $key = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByFarmId($event->DBServer->farmId, $event->DBServer->GetFarmRoleObject()->CloudLocation);
         if (!$key) {
             throw new Exception(_("There is no SSH key for server: {$event->DBServer->serverId}"));
         }
     } catch (Exception $e) {
         throw new Exception("Cannot init SshKey object: {$e->getMessage()}");
     }
     // Prepare private key for SSH connection
     $priv_key_file = tempnam("/tmp", "AWSK");
     $res = file_put_contents($priv_key_file, $key->getPrivate());
     $this->Logger->debug("Creating temporary file for private key: {$res}");
     // Connect to SSH
     $SSH2 = new Scalr_Net_Ssh2_Client();
     $SSH2->addPubkey("root", $pub_key_file, $priv_key_file);
     if ($SSH2->connect($event->ExternalIP, $ssh_port)) {
         // Upload keys and s3 config to instance
         $res = $SSH2->sendFile("/etc/aws/keys/pk.pem", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), "w+", false);
         $res2 = $SSH2->sendFile("/etc/aws/keys/cert.pem", $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE), "w+", false);
         $res3 = $SSH2->sendFile("/etc/aws/keys/s3cmd.cfg", $s3cfg, "w+", false);
         // remove temporary files
         @unlink($pub_key_file);
         @unlink($priv_key_file);
     } else {
         // remove temporary files
         @unlink($pub_key_file);
         @unlink($priv_key_file);
         Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($this->FarmID, "Cannot upload ec2 keys to '{$event->DBServer->serverId}' instance. Failed to connect to SSH '{$event->ExternalIP}:{$ssh_port}'"));
         throw new Exception("Cannot upload keys on '{$event->DBServer->serverId}'. Failed to connect to '{$event->ExternalIP}:{$ssh_port}'.");
     }
 }
 public function OnStartForking()
 {
     $db = Core::GetDBInstance();
     $roles = $db->GetAll("SELECT * FROM roles_queue WHERE `action` = 'remove'");
     foreach ($roles as $role) {
         try {
             $dbRole = DBRole::loadById($role['role_id']);
             $dbRole->remove(true);
         } catch (Exception $e) {
             print $e->getMessage() . "\n";
         }
     }
 }
Пример #4
0
 /**
  * @return Role[]
  */
 public function getTestRoles()
 {
     $roles = Role::find([['envId' => $this->getEnvironment()->id]]);
     return array_filter(iterator_to_array($roles), function (Role $role) {
         $dbRole = \DBRole::loadById($role->id);
         $farms = $dbRole->getFarms();
         foreach ($farms as $farmId) {
             $farm = \DBFarm::LoadByID($farmId);
             if ($farm->Status) {
                 return false;
             }
         }
         return true;
     });
 }
Пример #5
0
 public function Run()
 {
     $container = Scalr::getContainer();
     $db = $container->adodb;
     $roles = $db->Execute("SELECT * FROM roles WHERE origin='SHARED'");
     while ($role = $roles->FetchRow()) {
         if (!stristr($role['behaviors'], 'chef')) {
             $dbRole = DBRole::loadById($role['id']);
             $behaviors = $dbRole->getBehaviors();
             $behaviors[] = 'chef';
             $dbRole->setBehaviors($behaviors);
             $dbRole->save();
         }
     }
 }
Пример #6
0
 public function Run()
 {
     global $db;
     $time = microtime(true);
     $images = $db->Execute("SELECT * FROM role_images WHERE architecture IS NULL AND platform = 'ec2' ORDER BY id DESC");
     while ($image = $images->FetchRow()) {
         $role = DBRole::loadById($image['role_id']);
         if ($role->clientId == 0) {
             continue;
         }
         $environemnt = Scalr_Environment::init()->loadById($role->envId);
         try {
             $acrh = $environemnt->aws($image['cloud_location'])->ec2->image->describe($image['image_id'])->get(0)->architecture;
             $db->Execute("UPDATE role_images SET architecture = ? WHERE id = ?", array($acrh, $image['id']));
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "does not exist") && stristr($e->getMessage(), 'The image id')) {
                 //$db->Execute("DELETE FROM role_images WHERE id = ?", array($image['id']));
                 print "Removed {$image['image_id']} because: {$e->getMessage()}\n";
                 continue;
             } elseif (stristr($e->getMessage(), "AWS was not able to validate the provided access credentials")) {
                 continue;
             } elseif (stristr($e->getMessage(), "You are not subscribed to this service")) {
                 continue;
             } elseif (stristr($e->getMessage(), "Invalid id")) {
                 $db->Execute("DELETE FROM role_images WHERE id = ?", array($image['id']));
                 continue;
             }
             var_dump($e->getMessage());
             exit;
         }
     }
     $db->Execute("ALTER TABLE  `roles` DROP  `is_stable` , DROP  `approval_state` , DROP  `szr_version` ;");
     $db->Execute("ALTER TABLE  `roles` DROP  `architecture` ;");
     $db->Execute("ALTER TABLE  `roles` ADD  `os_family` VARCHAR( 30 ) NULL ,\n            ADD  `os_generation` VARCHAR( 10 ) NULL ,\n            ADD  `os_version` VARCHAR( 10 ) NULL\n        ");
     //SSL certs refactoring
     $db->Execute("ALTER TABLE  `apache_vhosts` ADD  `ssl_cert_id` INT( 11 ) NULL");
     $db->Execute("CREATE TABLE IF NOT EXISTS `services_ssl_certs` (\n          `id` int(11) NOT NULL AUTO_INCREMENT,\n          `env_id` int(11) NOT NULL,\n          `name` varchar(40) NOT NULL,\n          `ssl_pkey` text NULL,\n          `ssl_cert` text NULL,\n          `ssl_cabundle` text NULL,\n          PRIMARY KEY (`id`)\n        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;");
     $vhosts = $db->Execute("SELECT * FROM apache_vhosts WHERE is_ssl_enabled = '1'");
     while ($vhost = $vhosts->FetchRow()) {
         $db->Execute("INSERT INTO services_ssl_certs SET\n                env_id = ?,\n                name = ?,\n                ssl_pkey = ?,\n                ssl_cert = ?,\n                ssl_cabundle = ?\n            ", array($vhost['env_id'], $vhost['name'], $vhost['ssl_key'], $vhost['ssl_cert'], $vhost['ca_cert']));
         $certId = $db->Insert_ID();
         $db->Execute("UPDATE apache_vhosts SET ssl_cert_id = ? WHERE id = ?", array($certId, $vhost['id']));
     }
     print "Done.\n";
     $t = round(microtime(true) - $time, 2);
     printf("Upgrade process took %0.2f seconds\n\n\n", $t);
 }
Пример #7
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;
 }
Пример #8
0
 /**
  * Creates clone for the farm
  *
  * @param   string             $name   The name of the farm
  * @param   Scalr_Account_User $user   The user object
  * @param   int                $envId  The identifier of the environment
  * @return  DBFarm             Returns clone
  */
 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->RolesLaunchOrder = $definition->rolesLaunchOrder;
     $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]);
     $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, $definition->settings[DBFarm::SETTING_LEASE_STATUS]);
     $variables = new Scalr_Scripting_GlobalVariables($dbFarm->ClientID, $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) {
             \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
             \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
             \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
         }
         if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) {
             CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
         }
         $dbFarmRolesList[] = $dbFarmRole;
         $usedPlatforms[$role->platform] = 1;
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EC2]) {
         \Scalr\Modules\Platforms\Ec2\Helpers\Ec2Helper::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) {
         \Scalr\Modules\Platforms\Eucalyptus\Helpers\EucalyptusHelper::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) {
         CloudstackHelper::farmSave($dbFarm, $dbFarmRolesList);
     }
     $dbFarm->save();
     return $dbFarm;
 }
Пример #9
0
 /**
  *
  * @return array
  */
 public function GetScriptingVars()
 {
     $dbFarmRole = $this->GetFarmRoleObject();
     $roleId = $dbFarmRole->RoleID;
     $dbRole = DBRole::loadById($roleId);
     $isDbMsr = $dbRole->getDbMsrBehavior();
     if ($isDbMsr) {
         $isMaster = $this->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER);
     } else {
         $isMaster = $this->GetProperty(\SERVER_PROPERTIES::DB_MYSQL_MASTER);
     }
     $retval = array('image_id' => $dbRole->__getNewRoleObject()->getImage($this->platform, $dbFarmRole->CloudLocation)->imageId, 'external_ip' => $this->remoteIp, 'internal_ip' => $this->localIp, 'role_name' => $dbRole->name, 'isdbmaster' => $isMaster, 'instance_index' => $this->index, 'instance_farm_index' => $this->farmIndex, 'server_type' => $this->type, 'server_hostname' => $this->GetProperty(Scalr_Role_Behavior::SERVER_BASE_HOSTNAME), 'server_id' => $this->serverId, 'farm_id' => $this->farmId, 'farm_role_id' => $this->farmRoleId, 'farm_role_alias' => $this->GetFarmRoleObject()->Alias, 'farm_name' => $this->GetFarmObject()->Name, 'farm_hash' => $this->GetFarmObject()->Hash, 'farm_owner_email' => $this->GetFarmObject()->createdByUserEmail, 'farm_team' => $this->GetFarmObject()->teamId ? (new Scalr_Account_Team())->loadById($this->GetFarmObject()->teamId)->name : '', 'behaviors' => implode(",", $dbRole->getBehaviors()), 'env_id' => $this->GetEnvironmentObject()->id, 'env_name' => $this->GetEnvironmentObject()->name, 'cloud_location' => $this->GetCloudLocation(), 'cloud_server_id' => $this->GetCloudServerID());
     if ($this->cloudLocationZone) {
         $retval['cloud_location_zone'] = $this->cloudLocationZone;
     }
     if ($this->platform == SERVER_PLATFORMS::EC2) {
         $retval['instance_id'] = $this->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID);
         $retval['ami_id'] = $this->GetProperty(EC2_SERVER_PROPERTIES::AMIID);
         $retval['region'] = $this->GetProperty(EC2_SERVER_PROPERTIES::REGION);
         $retval['avail_zone'] = $this->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE);
         if ($dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_ELB_ENABLED)) {
             $elbId = $dbFarmRole->GetSetting(Entity\FarmRoleSetting::AWS_ELB_ID);
             $retval['aws_elb_name'] = $elbId;
         }
     }
     if (\Scalr::getContainer()->analytics->enabled) {
         $ccId = $this->GetProperty(\SERVER_PROPERTIES::ENV_CC_ID);
         if ($ccId) {
             $cc = CostCentreEntity::findPk($ccId);
             if ($cc) {
                 /* @var $cc CostCentreEntity */
                 $retval['cost_center_id'] = $ccId;
                 $retval['cost_center_bc'] = $cc->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE);
                 $retval['cost_center_name'] = $cc->name;
             } else {
                 throw new Exception("Cost center {$ccId} not found");
             }
         }
         $projectId = $this->GetProperty(\SERVER_PROPERTIES::FARM_PROJECT_ID);
         if ($projectId) {
             $project = ProjectEntity::findPk($projectId);
             /* @var $project ProjectEntity */
             $retval['project_id'] = $projectId;
             $retval['project_bc'] = $project->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE);
             $retval['project_name'] = $project->name;
         }
     }
     return $retval;
 }
Пример #10
0
 public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $environment = $DBServer->GetEnvironmentObject();
     $diskOffering = null;
     $size = null;
     if (!$launchOptions) {
         $farmRole = $DBServer->GetFarmRoleObject();
         $launchOptions = new Scalr_Server_LaunchOptions();
         $dbRole = DBRole::loadById($DBServer->roleId);
         $launchOptions->imageId = $dbRole->getImageId($this->platform, $DBServer->GetFarmRoleObject()->CloudLocation);
         $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_SERVICE_OFFERING_ID);
         $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation;
         /*
          * User Data
          */
         foreach ($DBServer->GetCloudUserData() as $k => $v) {
             $u_data .= "{$k}={$v};";
         }
         $launchOptions->userData = trim($u_data, ";");
         $diskOffering = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_DISK_OFFERING_ID);
         if ($diskOffering === false || $diskOffering === null) {
             $diskOffering = null;
         }
         $sharedIp = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_SHARED_IP_ID);
         $networkType = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_TYPE);
         $networkId = $farmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_ID);
         $roleName = $farmRole->GetRoleObject()->name;
     } else {
         $launchOptions->userData = array();
         $roleName = 'TemporaryScalrServer' . rand(100, 999);
     }
     $launchOptions->architecture = 'x86_64';
     $cs = $this->getCloudStackClient($environment, $launchOptions->cloudLocation);
     if (!$sharedIp) {
         if ($networkId && ($networkType == 'Virtual' || $networkType == 'Isolated' || !$networkType)) {
             $sharedIpId = $this->getConfigVariable(self::SHARED_IP_ID . ".{$launchOptions->cloudLocation}", $environment, false);
             if (!$sharedIpId) {
                 $ipResult = $cs->associateIpAddress($launchOptions->cloudLocation);
                 $ipId = $ipResult->id;
                 if ($ipId) {
                     while (true) {
                         $ipInfo = $cs->listPublicIpAddresses($ipId);
                         $ipInfo = $ipInfo->publicipaddress[0];
                         if (!$ipInfo) {
                             throw new Exception("Cannot allocate IP address: listPublicIpAddresses -> failed");
                         }
                         if ($ipInfo->state == 'Allocated') {
                             $this->setConfigVariable(array(self::SHARED_IP_ID . ".{$launchOptions->cloudLocation}" => $ipId), $environment, false);
                             $this->setConfigVariable(array(self::SHARED_IP . ".{$launchOptions->cloudLocation}" => $ipInfo->ipaddress), $environment, false);
                             $this->setConfigVariable(array(self::SHARED_IP_INFO . ".{$launchOptions->cloudLocation}" => serialize($ipInfo)), $environment, false);
                             $sharedIpId = $ipId;
                             break;
                         } else {
                             if ($ipInfo->state == 'Allocating') {
                                 sleep(1);
                             } else {
                                 throw new Exception("Cannot allocate IP address: ipAddress->state = {$ipInfo->state}");
                             }
                         }
                     }
                 } else {
                     throw new Exception("Cannot allocate IP address: associateIpAddress -> failed");
                 }
             }
         }
     }
     if ($DBServer->status == SERVER_STATUS::TEMPORARY) {
         $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID;
         $farmId = 0;
     } else {
         $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID;
         $farmId = $DBServer->farmId;
     }
     $sshKey = Scalr_SshKey::init();
     try {
         if (!$sshKey->loadGlobalByName($keyName, "", $DBServer->envId, $this->platform)) {
             $result = $cs->createSSHKeyPair($keyName);
             if ($result->keypair->privatekey) {
                 $sshKey->farmId = $farmId;
                 $sshKey->clientId = $DBServer->clientId;
                 $sshKey->envId = $DBServer->envId;
                 $sshKey->type = Scalr_SshKey::TYPE_GLOBAL;
                 $sshKey->cloudLocation = "";
                 //$launchOptions->cloudLocation;
                 $sshKey->cloudKeyName = $keyName;
                 $sshKey->platform = $this->platform;
                 $sshKey->setPrivate($result->keypair->privatekey);
                 $sshKey->setPublic($sshKey->generatePublicKey());
                 $sshKey->save();
             }
         }
     } catch (Exception $e) {
         Logger::getLogger("CloudStack")->error(new FarmLogMessage($DBServer->farmId, "Unable to generate keypair: {$e->getMessage()}"));
     }
     $vResult = $cs->deployVirtualMachine($launchOptions->serverType, $launchOptions->imageId, $launchOptions->cloudLocation, null, $diskOffering, $DBServer->serverId, null, $roleName, null, null, $keyName, "", $networkId, null, null, $size, base64_encode($launchOptions->userData));
     if ($vResult->id) {
         $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID, $vResult->id);
         $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION, $launchOptions->cloudLocation);
         $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::LAUNCH_JOB_ID, $vResult->jobid);
         $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture);
         return $DBServer;
     } else {
         throw new Exception(sprintf("Cannot launch new instance: %s", $vResult->errortext));
     }
 }
Пример #11
0
 /**
  * Launches server
  *
  * @param   \ServerCreateInfo       $ServerCreateInfo optional The server create info
  * @param   \DBServer               $DBServer         optional The DBServer object
  * @param   bool                    $delayed          optional
  * @param   integer|array            $reason           optional
  * @param   \Scalr_Account_User|int $user             optional The Scalr_Account_User object or its unique identifier
  * @return  DBServer|null           Returns the DBServer object on cussess or null otherwise
  */
 public static function LaunchServer(ServerCreateInfo $ServerCreateInfo = null, DBServer $DBServer = null, $delayed = false, $reason = 0, $user = null)
 {
     $db = self::getDb();
     $farm = null;
     //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) {
         }
     }
     if (!$DBServer && $ServerCreateInfo) {
         $ServerCreateInfo->SetProperties(array(SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::ONE_TIME));
         $DBServer = DBServer::Create($ServerCreateInfo, false, true);
     } elseif (!$DBServer && !$ServerCreateInfo) {
         // incorrect arguments
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Cannot create server"));
         return null;
     }
     $propsToSet = array();
     if ($user instanceof \Scalr_Account_User) {
         $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_ID] = $user->id;
         $propsToSet[SERVER_PROPERTIES::LAUNCHED_BY_EMAIL] = $user->getEmail();
     }
     //We should keep role_id and farm_role_id in server properties to use in cost analytics
     if (!empty($DBServer->farmRoleId)) {
         $propsToSet[SERVER_PROPERTIES::FARM_ROLE_ID] = $DBServer->farmRoleId;
         $propsToSet[SERVER_PROPERTIES::ROLE_ID] = $DBServer->farmRoleId ? $DBServer->GetFarmRoleObject()->RoleID : 0;
     }
     try {
         // Ensures the farm object will be fetched as correctly as possible
         $farm = $DBServer->farmId ? $DBServer->GetFarmObject() : null;
         $farmRole = $DBServer->farmRoleId ? $DBServer->GetFarmRoleObject() : null;
         if (!$farmRole instanceof DBFarmRole) {
             $farmRole = null;
         } else {
             if (!$farm instanceof DBFarm) {
                 // Gets farm through FarmRole object in this case
                 $farm = $farmRole->GetFarmObject();
             }
         }
         if ($farm instanceof DBFarm) {
             $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_ID] = $farm->createdByUserId;
             $propsToSet[SERVER_PROPERTIES::FARM_CREATED_BY_EMAIL] = $farm->createdByUserEmail;
             $projectId = $farm->GetSetting(DBFarm::SETTING_PROJECT_ID);
             if (!empty($projectId)) {
                 try {
                     $projectEntity = ProjectEntity::findPk($projectId);
                     if ($projectEntity instanceof ProjectEntity) {
                         /* @var $projectEntity ProjectEntity */
                         $ccId = $projectEntity->ccId;
                     } else {
                         $projectId = null;
                     }
                 } catch (Exception $e) {
                     $projectId = null;
                 }
             }
             $propsToSet[SERVER_PROPERTIES::FARM_PROJECT_ID] = $projectId;
         }
         if ($farmRole instanceof DBFarmRole) {
             $propsToSet[SERVER_PROPERTIES::INFO_INSTANCE_TYPE_NAME] = $farmRole->GetSetting(DBFarmRole::SETTING_INFO_INSTANCE_TYPE_NAME);
         }
         if (!empty($ccId)) {
             $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $ccId;
         } elseif ($DBServer->envId && ($environment = $DBServer->GetEnvironmentObject()) instanceof Scalr_Environment) {
             $propsToSet[SERVER_PROPERTIES::ENV_CC_ID] = $environment->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID);
         }
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("Could not load related object for recently created server %s. It says: %s", $DBServer->serverId, $e->getMessage()));
     }
     if (!empty($propsToSet)) {
         $DBServer->SetProperties($propsToSet);
     }
     $fnGetReason = function ($reasonId) {
         $args = func_get_args();
         $args[0] = DBServer::getLaunchReason($reasonId);
         return [call_user_func_array('sprintf', $args), $reasonId];
     };
     if ($delayed) {
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason);
         $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_REASON => $reasonMsg, SERVER_PROPERTIES::LAUNCH_REASON_ID => $reasonId]);
         $DBServer->Save();
         return $DBServer;
     }
     if ($ServerCreateInfo && $ServerCreateInfo->roleId) {
         $dbRole = DBRole::loadById($ServerCreateInfo->roleId);
         if ($dbRole->generation == 1) {
             $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
             $DBServer->Save();
             $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ERROR => "ami-scripts servers no longer supported", SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]);
             return $DBServer;
         }
     }
     // Limit amount of pending servers
     if ($DBServer->isOpenstack()) {
         $config = \Scalr::getContainer()->config;
         if ($config->defined("scalr.{$DBServer->platform}.pending_servers_limit")) {
             $pendingServersLimit = $config->get("scalr.{$DBServer->platform}.pending_servers_limit");
             $pendingServers = $db->GetOne("SELECT COUNT(*) FROM servers WHERE platform=? AND status=? AND server_id != ?", array($DBServer->platform, SERVER_STATUS::PENDING, $DBServer->serverId));
             if ($pendingServers >= $pendingServersLimit) {
                 Logger::getLogger("SERVER_LAUNCH")->warn("{$pendingServers} servers in PENDING state on {$DBServer->platform}. Limit is: {$pendingServersLimit}. Waiting.");
                 $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
                 $DBServer->Save();
                 $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]);
                 return $DBServer;
             } else {
                 Logger::getLogger("SERVER_LAUNCH")->warn("{$pendingServers} servers in PENDING state on {$DBServer->platform}. Limit is: {$pendingServersLimit}. Launching server.");
             }
         }
     }
     try {
         $account = Scalr_Account::init()->loadById($DBServer->clientId);
         $account->validateLimit(Scalr_Limits::ACCOUNT_SERVERS, 1);
         PlatformFactory::NewPlatform($DBServer->platform)->LaunchServer($DBServer);
         $DBServer->status = SERVER_STATUS::PENDING;
         $DBServer->Save();
         try {
             if ($reason) {
                 list($reasonMsg, $reasonId) = is_array($reason) ? call_user_func_array($fnGetReason, $reason) : $fnGetReason($reason);
             } else {
                 $reasonMsg = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON);
                 $reasonId = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_REASON_ID);
             }
             $DBServer->getServerHistory()->markAsLaunched($reasonMsg, $reasonId);
             $DBServer->updateTimelog('ts_launched');
             if ($DBServer->imageId) {
                 //Update Image last used date
                 $image = Image::findOne([['id' => $DBServer->imageId], ['envId' => $DBServer->envId], ['platform' => $DBServer->platform], ['cloudLocation' => $DBServer->cloudLocation]]);
                 if (!$image) {
                     $image = Image::findOne([['id' => $DBServer->imageId], ['envId' => NULL], ['platform' => $DBServer->platform], ['cloudLocation' => $DBServer->cloudLocation]]);
                 }
                 if ($image) {
                     $image->dtLastUsed = new DateTime();
                     $image->save();
                 }
                 //Update Role last used date
                 if ($DBServer->farmRoleId) {
                     $dbRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
                     $dbRole->dtLastUsed = date("Y-m-d H:i:s");
                     $dbRole->save();
                 }
             }
         } catch (Exception $e) {
             Logger::getLogger('SERVER_HISTORY')->error(sprintf("Cannot update servers history: {$e->getMessage()}"));
         }
     } catch (Exception $e) {
         Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBServer->farmId, sprintf("Cannot launch server on '%s' platform: %s", $DBServer->platform, $e->getMessage()), $DBServer->serverId));
         $existingLaunchError = $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ERROR);
         $DBServer->status = SERVER_STATUS::PENDING_LAUNCH;
         $DBServer->SetProperties([SERVER_PROPERTIES::LAUNCH_ERROR => $e->getMessage(), SERVER_PROPERTIES::LAUNCH_ATTEMPT => $DBServer->GetProperty(SERVER_PROPERTIES::LAUNCH_ATTEMPT) + 1, SERVER_PROPERTIES::LAUNCH_LAST_TRY => (new DateTime())->format('Y-m-d H:i:s')]);
         $DBServer->Save();
         if ($DBServer->farmId && !$existingLaunchError) {
             Scalr::FireEvent($DBServer->farmId, new InstanceLaunchFailedEvent($DBServer, $e->getMessage()));
         }
     }
     if ($DBServer->status == SERVER_STATUS::PENDING) {
         Scalr::FireEvent($DBServer->farmId, new BeforeInstanceLaunchEvent($DBServer));
         $DBServer->SetProperty(SERVER_PROPERTIES::LAUNCH_ERROR, "");
     }
     return $DBServer;
 }
Пример #12
0
 public function getReplacementRoles($includeSelf = false)
 {
     $dbRole = $this->GetRoleObject();
     $roles_sql = '
         SELECT r.id
         FROM roles r
         INNER JOIN role_images ri ON r.id = ri.role_id
         LEFT JOIN roles_queue q ON r.id = q.role_id
         WHERE generation = \'2\' AND env_id IN(0, ?)
         AND q.id IS NULL
         AND ri.platform = ?' . (in_array($this->Platform, array(SERVER_PLATFORMS::GCE, SERVER_PLATFORMS::ECS)) ? '' : 'AND ri.cloud_location = ?') . 'AND r.os_family = ?' . ($includeSelf ? '' : 'AND r.id != ?') . 'GROUP BY r.id
     ';
     $args = array($this->GetFarmObject()->EnvID, $this->Platform);
     if (!in_array($this->Platform, array(SERVER_PLATFORMS::GCE, SERVER_PLATFORMS::ECS))) {
         $args[] = $this->CloudLocation;
     }
     $args[] = $dbRole->osFamily;
     if ($includeSelf) {
         $args[] = $dbRole->id;
     }
     $behaviors = $dbRole->getBehaviors();
     sort($behaviors);
     $result = array();
     foreach ($this->DB->GetCol($roles_sql, $args) as $roleId) {
         $role = DBRole::loadById($roleId);
         $behaviors2 = $role->getBehaviors();
         sort($behaviors2);
         if ($behaviors == $behaviors2) {
             $imageInfo = $role->getImageDetails($this->Platform, $this->CloudLocation);
             $result[] = array('id' => $role->id, 'debug' => array($imageInfo), 'name' => $role->name, 'os_name' => $role->os, 'os_family' => $role->osFamily, 'os_generation' => $role->osGeneration, 'os_version' => $role->osVersion, 'shared' => $role->envId == 0, 'behaviors' => $role->getBehaviors(), 'image_id' => $imageInfo['image_id'], 'arch' => !$imageInfo['architecture'] ? stristr($role->name, '64-') ? 'x86_64' : 'i386' : $imageInfo['architecture']);
         } else {
             //var_dump($behaviors2);
         }
     }
     return $result;
 }
 /**
  * List farm roles and hosts list for each role
  * Allowed args: role=(String Role Name) | behaviour=(app|www|mysql|base|memcached)
  * @return DOMDocument
  */
 protected function ListRoles()
 {
     $ResponseDOMDocument = $this->CreateResponse();
     $RolesDOMNode = $ResponseDOMDocument->createElement('roles');
     $ResponseDOMDocument->documentElement->appendChild($RolesDOMNode);
     $sql_query = "SELECT id FROM farm_roles WHERE farmid=?";
     $sql_query_args = array($this->DBServer->farmId);
     // Filter by behaviour
     if ($this->GetArg("behaviour")) {
         $sql_query .= " AND role_id IN (SELECT role_id FROM role_behaviors WHERE behavior=?)";
         array_push($sql_query_args, $this->GetArg("behaviour"));
     }
     // Filter by role
     if ($this->GetArg("role")) {
         $sql_query .= " AND role_id IN (SELECT id FROM roles WHERE name=?)";
         array_push($sql_query_args, $this->GetArg("role"));
     }
     if ($this->GetArg("role-id")) {
         $sql_query .= " AND role_id = ?";
         array_push($sql_query_args, $this->GetArg("role-id"));
     }
     if ($this->GetArg("farm-role-id")) {
         $sql_query .= " AND id = ?";
         array_push($sql_query_args, $this->GetArg("farm-role-id"));
     }
     $farm_roles = $this->DB->GetAll($sql_query, $sql_query_args);
     foreach ($farm_roles as $farm_role) {
         $DBFarmRole = DBFarmRole::LoadByID($farm_role['id']);
         $roleId = $DBFarmRole->NewRoleID ? $DBFarmRole->NewRoleID : $DBFarmRole->RoleID;
         // Create role node
         $RoleDOMNode = $ResponseDOMDocument->createElement('role');
         $RoleDOMNode->setAttribute('behaviour', implode(",", $DBFarmRole->GetRoleObject()->getBehaviors()));
         $RoleDOMNode->setAttribute('name', DBRole::loadById($roleId)->name);
         $RoleDOMNode->setAttribute('alias', $DBFarmRole->Alias);
         $RoleDOMNode->setAttribute('id', $DBFarmRole->ID);
         $RoleDOMNode->setAttribute('role-id', $roleId);
         $HostsDomNode = $ResponseDOMDocument->createElement('hosts');
         $RoleDOMNode->appendChild($HostsDomNode);
         // List instances (hosts)
         $serversSql = "SELECT server_id FROM servers WHERE farm_roleid=?";
         $serversArgs = array($farm_role['id'], SERVER_STATUS::RUNNING);
         if ($this->GetArg("showInitServers")) {
             $serversSql .= " AND status IN (?,?)";
             $serversArgs[] = SERVER_STATUS::INIT;
         } else {
             $serversSql .= " AND status=?";
         }
         $servers = $this->DB->GetAll($serversSql, $serversArgs);
         // Add hosts to response
         if (count($servers) > 0) {
             foreach ($servers as $server) {
                 $DBServer = DBServer::LoadByID($server['server_id']);
                 $HostDOMNode = $ResponseDOMDocument->createElement("host");
                 $HostDOMNode->setAttribute('internal-ip', $DBServer->localIp);
                 $HostDOMNode->setAttribute('external-ip', $DBServer->remoteIp);
                 $HostDOMNode->setAttribute('index', $DBServer->index);
                 $HostDOMNode->setAttribute('status', $DBServer->status);
                 $HostDOMNode->setAttribute('cloud-location', $DBServer->GetCloudLocation());
                 $HostDOMNode->setAttribute('cloud-location-zone', $DBServer->cloudLocationZone);
                 $HostDOMNode->setAttribute('hostname', $DBServer->GetProperty(Scalr_Role_Behavior::SERVER_BASE_HOSTNAME));
                 if ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                     $HostDOMNode->setAttribute('replica-set-index', (int) $DBServer->GetProperty(Scalr_Role_Behavior_MongoDB::SERVER_REPLICA_SET_INDEX));
                     $HostDOMNode->setAttribute('shard-index', (int) $DBServer->GetProperty(Scalr_Role_Behavior_MongoDB::SERVER_SHARD_INDEX));
                 }
                 if ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL)) {
                     $HostDOMNode->setAttribute('replication-master', (int) $DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER));
                 }
                 if ($DBFarmRole->GetRoleObject()->getDbMsrBehavior()) {
                     $HostDOMNode->setAttribute('replication-master', (int) $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER));
                 }
                 $HostsDomNode->appendChild($HostDOMNode);
             }
         }
         // Add role node to roles node
         $RolesDOMNode->appendChild($RoleDOMNode);
     }
     return $ResponseDOMDocument;
 }
Пример #14
0
 /**
  * Clones FarmRoles with settings from this Farm to a new Farm
  *
  * @param   DBFarm  $newFarm    A Farm into which Roles be cloned
  *
  * @throws  Exception
  */
 public function cloneFarmRoles(DBFarm $newFarm)
 {
     foreach ($this->getDefinition()->roles as $idx => $role) {
         $dbFarmRole = $newFarm->AddRole(DBRole::loadById($role->roleId), $role->platform, $role->cloudLocation, $role->launchIndex, $role->alias);
         $oldRoleSettings = $dbFarmRole->GetAllSettings();
         $dbFarmRole->applyDefinition($role, true);
         $newSettings = $dbFarmRole->GetAllSettings();
         // Platform specified updates
         if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
             \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
             \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
             \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
         }
         if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) {
             CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $newSettings);
         }
     }
 }
 public function OnHostUp(HostUpEvent $event)
 {
     $servers = DBFarm::LoadByID($this->FarmID)->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING)));
     $event->msgExpected = count($servers);
     foreach ((array) $servers as $DBServer) {
         try {
             $msg = new Scalr_Messaging_Msg_HostUp();
             $msg->setServerMetaData($event->DBServer);
             if ($event->DBServer->GetFarmRoleObject()->NewRoleID) {
                 $msg->roleName = DBRole::loadById($event->DBServer->GetFarmRoleObject()->NewRoleID)->name;
             } else {
                 $msg->roleName = $event->DBServer->GetFarmRoleObject()->GetRoleObject()->name;
             }
             $msg = Scalr_Scripting_Manager::extendMessage($msg, $event, $event->DBServer, $DBServer);
             if ($event->DBServer->farmRoleId != 0) {
                 foreach (Scalr_Role_Behavior::getListForFarmRole($event->DBServer->GetFarmRoleObject()) as $behavior) {
                     $msg = $behavior->extendMessage($msg, $event->DBServer);
                 }
             }
             $msg = $DBServer->SendMessage($msg, false, true);
             if ($msg) {
                 $event->msgCreated++;
             } else {
                 throw new Exception("Empty MSG: {$DBServer->serverId} ({$event->DBServer->serverId})");
             }
         } catch (Exception $e) {
             Logger::getLogger(__CLASS__)->fatal("MessagingEventObserver::OnHostUp failed: {$e->getMessage()}");
         }
     }
     if ($event->DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) == 1 && $event->DBServer->IsSupported("0.7")) {
         $this->sendNewMasterUpMessage($event->DBServer, "", $event);
     }
     if ($event->DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER) == 1) {
         $this->sendNewDbMsrMasterUpMessage($event->DBServer, $event);
     }
 }
Пример #16
0
 public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $RDSClient = $this->getRdsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION));
     $DBRole = DBRole::loadById($DBServer->roleId);
     $server_id = "scalr-{$DBServer->serverId}";
     $avail_zone = $DBServer->GetProperty(RDS_SERVER_PROPERTIES::AVAIL_ZONE) ? $DBServer->GetProperty(RDS_SERVER_PROPERTIES::AVAIL_ZONE) : $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION) . "a";
     try {
         if ($DBRole->getImageId(SERVER_PLATFORMS::RDS, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION)) == 'ScalrEmpty') {
             $RDSClient->CreateDBInstance($server_id, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::STORAGE), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::INSTANCE_CLASS), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::INSTANCE_ENGINE), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::MASTER_USER), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::MASTER_PASS), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::PORT), null, null, null, $avail_zone, null, null, null);
         } else {
             $RDSClient->RestoreDBInstanceFromDBSnapshot($DBRole->getImageId(SERVER_PLATFORMS::RDS, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION)), $server_id, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::INSTANCE_CLASS), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::PORT), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::AVAIL_ZONE));
         }
         $DBServer->SetProperty(RDS_SERVER_PROPERTIES::INSTANCE_ID, $server_id);
         $DBServer->SetProperty(RDS_SERVER_PROPERTIES::SNAPSHOT_ID, $DBRole->getImageId(SERVER_PLATFORMS::RDS, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION)));
         return $DBServer;
     } catch (Exception $e) {
         throw new Exception(sprintf(_("Cannot launch new instance. %s"), $e->getMessage()));
     }
 }
Пример #17
0
 /**
 launchOptions: imageId
 */
 public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null)
 {
     if (!$launchOptions) {
         $launchOptions = new Scalr_Server_LaunchOptions();
         $DBRole = DBRole::loadById($DBServer->roleId);
         $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::OPENSTACK, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
         $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_OPENSTACK_FLAVOR_ID);
         $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation;
         foreach ($DBServer->GetCloudUserData() as $k => $v) {
             $u_data .= "{$k}={$v};";
         }
         $launchOptions->userData = trim($u_data, ";");
         $launchOptions->architecture = 'x86_64';
     }
     $osClient = $this->getOsClient($DBServer->GetEnvironmentObject(), $launchOptions->cloudLocation);
     $result = $osClient->serverCreate($DBServer->serverId, $launchOptions->imageId, $launchOptions->serverType, base64_encode($launchOptions->userData), array('path' => '/etc/scalr/private.d/.user-data', 'contents' => base64_encode($launchOptions->userData)));
     if ($result->server) {
         //TODO:
         $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID, $result->server->id);
         $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::IMAGE_ID, $result->server->image->id);
         $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::FLAVOR_ID, $result->server->flavor->id);
         $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS, $result->server->adminPass);
         $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::NAME, $DBServer->serverId);
         $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::HOST_ID, $result->server->hostId);
         $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture);
         $DBServer->SetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION, $launchOptions->cloudLocation);
         return $DBServer;
     } else {
         throw new Exception(sprintf(_("Cannot launch new instance. %s"), $result->faultstring));
     }
 }
Пример #18
0
 /**
 launchOptions: imageId
 */
 public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null)
 {
     if (!$launchOptions) {
         $launchOptions = new Scalr_Server_LaunchOptions();
         $DBRole = DBRole::loadById($DBServer->roleId);
         $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::RACKSPACE, $DBServer->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER));
         $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_RS_FLAVOR_ID);
         $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation;
         foreach ($DBServer->GetCloudUserData() as $k => $v) {
             $u_data .= "{$k}={$v};";
         }
         $launchOptions->userData = trim($u_data, ";");
         $launchOptions->architecture = 'x86_64';
     }
     $rsClient = $this->getRsClient($DBServer->GetEnvironmentObject(), $launchOptions->cloudLocation);
     //Cannot launch new instance. Request to Rackspace failed (Code: 413): {"overLimit":{"message":"Too many requests...","code":413,"retryAfter":"2012-03-12T09:44:56.343-05:00"}} (19641119, 4)
     try {
         $result = $rsClient->createServer($DBServer->serverId, $launchOptions->imageId, $launchOptions->serverType, array(), array('path' => '/etc/scalr/private.d/.user-data', 'contents' => base64_encode($launchOptions->userData)));
     } catch (Exception $e) {
         throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), $e->getMessage(), $launchOptions->imageId, $launchOptions->serverType));
     }
     if ($result->server) {
         $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::SERVER_ID, $result->server->id);
         $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::IMAGE_ID, $result->server->imageId);
         $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::FLAVOR_ID, $result->server->flavorId);
         $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::ADMIN_PASS, $result->server->adminPass);
         $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::NAME, $DBServer->serverId);
         $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::HOST_ID, $result->server->hostId);
         $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture);
         $DBServer->SetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER, $launchOptions->cloudLocation);
         return $DBServer;
     } else {
         throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), serialize($result), $launchOptions->imageId, $launchOptions->serverType));
     }
 }
Пример #19
0
 /**
  * 
  * @return DBRole
  */
 public function GetRoleObject()
 {
     if (!$this->dbRole) {
         $this->dbRole = DBRole::loadById($this->RoleID);
     }
     return $this->dbRole;
 }
 public function StartThread($bundle_task_info)
 {
     $db = Core::GetDBInstance();
     // Reconfigure observers;
     Scalr::ReconfigureObservers();
     $BundleTask = BundleTask::LoadById($bundle_task_info['id']);
     try {
         $DBServer = DBServer::LoadByID($BundleTask->serverId);
     } catch (ServerNotFoundException $e) {
         if (!$BundleTask->snapshotId) {
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::FAILED;
             $BundleTask->setDate('finished');
             $BundleTask->failureReason = sprintf(_("Server '%s' was terminated during snapshot creation process"), $BundleTask->serverId);
             $BundleTask->Save();
             return;
         }
     } catch (Exception $e) {
         //$this->Logger->error($e->getMessage());
     }
     switch ($BundleTask->status) {
         case SERVER_SNAPSHOT_CREATION_STATUS::STARING_SERVER:
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV:
         case SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE:
             if (!PlatformFactory::NewPlatform($DBServer->platform)->IsServerExists($DBServer)) {
                 $DBServer->status = SERVER_STATUS::TERMINATED;
                 $DBServer->save();
                 $BundleTask->SnapshotCreationFailed("Server was terminated and no longer available in cloud.");
                 exit;
             }
             // IF server is in pensing state
             $status = PlatformFactory::NewPlatform($DBServer->platform)->GetServerRealStatus($DBServer);
             $BundleTask->Log(sprintf(_("Server status: %s"), $status->getName()));
             if ($status->isPending()) {
                 $BundleTask->Log(sprintf(_("Waiting for running state."), $status->getName()));
                 exit;
             } elseif ($status->isTerminated()) {
                 $DBServer->status = SERVER_STATUS::TERMINATED;
                 $DBServer->save();
                 $BundleTask->SnapshotCreationFailed("Server was terminated and no longer available in cloud.");
                 exit;
             }
             break;
     }
     switch ($BundleTask->status) {
         case SERVER_SNAPSHOT_CREATION_STATUS::STARING_SERVER:
             $ips = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
             $DBServer->remoteIp = $ips['remoteIp'];
             $DBServer->localIp = $ips['locateIp'];
             $DBServer->save();
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV;
             $BundleTask->save();
             $BundleTask->Log(sprintf(_("Bundle task status: %s"), $BundleTask->status));
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV:
             $BundleTask->Log(sprintf(_("Initializing SSH2 session to the server")));
             try {
                 $ssh2Client = $DBServer->GetSsh2Client();
                 $ssh2Client->connect($DBServer->remoteIp, 22);
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scalr unable to establish SSH connection with server on %:%. Error: %s"), $DBServer->remoteIp, 22, $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             //Prepare script
             $BundleTask->Log(sprintf(_("Uploading builder scripts...")));
             $behaviors = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR);
             try {
                 $options = array('server-id' => $DBServer->serverId, 'role-name' => $BundleTask->roleName, 'crypto-key' => $DBServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 'platform' => $DBServer->platform, 'behaviour' => trim(str_replace("base", "", $behaviors)), 'queryenv-url' => CONFIG::$HTTP_PROTO . "://" . CONFIG::$EVENTHANDLER_URL . "/query-env", 'messaging-p2p.producer-url' => CONFIG::$HTTP_PROTO . "://" . CONFIG::$EVENTHANDLER_URL . "/messaging");
                 $command = 'scalarizr --import -y';
                 foreach ($options as $k => $v) {
                     $command .= sprintf(' -o %s=%s', $k, $v);
                 }
                 if ($DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE) == 'percona') {
                     $recipes = 'mysql=percona';
                 } else {
                     $recipes = '';
                 }
                 $scalarizrBranch = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH);
                 $scriptContents = @file_get_contents(APPPATH . "/templates/services/role_builder/chef_import.tpl");
                 $scriptContents = str_replace(array("%PLATFORM%", "%BEHAVIOURS%", "%SZR_IMPORT_STRING%", "%DEV%", "%SCALARIZR_BRANCH%", "%RECIPES%", "%BUILD_ONLY%", "%CHEF_SERVER_URL%", "%CHEF_VALIDATOR_NAME%", "%CHEF_VALIDATOR_KEY%", "%CHEF_ENVIRONMENT%", "%CHEF_ROLE%", "%CHEF_NODE_NAME%", "\r\n"), array($DBServer->platform, trim(str_replace("base", "", str_replace(",", " ", $behaviors))), $command, $scalarizrBranch ? '1' : '0', $scalarizrBranch, $recipes, '0', '', '', '', '', '', '', "\n"), $scriptContents);
                 if (!$ssh2Client->sendFile('/tmp/scalr-builder.sh', $scriptContents, "w+", false)) {
                     throw new Exception("Cannot upload script");
                 }
                 $BundleTask->Log(sprintf(_("Uploading chef recipes...")));
                 if (!$ssh2Client->sendFile('/tmp/recipes.tar.gz', APPPATH . '/www/storage/chef/recipes.tar.gz')) {
                     throw new Exception("Cannot upload chef recipes");
                 }
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scripts upload failed: %s"), $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             $BundleTask->Log("Launching role builder routines on server");
             $ssh2Client->exec("chmod 0777 /tmp/scalr-builder.sh");
             $ssh2Client->exec("setsid /tmp/scalr-builder.sh > /var/log/role-builder-output.log 2>&1 &");
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE;
             $BundleTask->save();
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE:
             try {
                 $ssh2Client = $DBServer->GetSsh2Client();
                 $ssh2Client->connect($DBServer->remoteIp, 22);
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scalr unable to establish SSH connection with server on %:%. Error: %s"), $DBServer->remoteIp, 22, $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             $log = $ssh2Client->getFile('/var/log/role-builder-output.log');
             $log_lines = explode("\r\n", $log);
             $last_msg = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_LAST_LOG_MESSAGE);
             while ($msg = trim(array_shift($log_lines))) {
                 if (substr($msg, -1, 1) != ']') {
                     continue;
                 }
                 if ($last_msg) {
                     if ($msg != $last_msg) {
                         continue;
                     } elseif ($msg == $last_msg) {
                         $last_msg = null;
                         continue;
                     }
                 }
                 if (stristr($msg, '[ Failed ]')) {
                     $stepLog = $ssh2Client->getFile('/var/log/role-builder-step.log');
                     $BundleTask->Log(sprintf("role-builder-step.log: %s", $stepLog));
                     $BundleTask->SnapshotCreationFailed($msg);
                     /** Terminate server **/
                     PlatformFactory::NewPlatform($DBServer->platform)->TerminateServer($DBServer);
                     $DBServer->status = SERVER_STATUS::PENDING_TERMINATE;
                     $DBServer->save();
                     $BundleTask->Log(sprintf("Temporary server '%s' (%s) has been terminated", $DBServer->serverId, $DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID)));
                 } else {
                     $BundleTask->Log($msg);
                     $DBServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_LAST_LOG_MESSAGE, $msg);
                 }
             }
             //Read /var/log/role-builder-output.log
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PENDING:
             try {
                 $platformModule = PlatformFactory::NewPlatform($BundleTask->platform);
                 $platformModule->CreateServerSnapshot($BundleTask);
             } catch (Exception $e) {
                 Logger::getLogger(LOG_CATEGORY::BUNDLE)->error($e->getMessage());
                 $BundleTask->SnapshotCreationFailed($e->getMessage());
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING:
             $addedTime = strtotime($BundleTask->dateAdded);
             if ($addedTime + 3600 < time()) {
                 $BundleTask->SnapshotCreationFailed("Server didn't send PrepareBundleResult message in time.");
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS:
             PlatformFactory::NewPlatform($BundleTask->platform)->CheckServerSnapshotStatus($BundleTask);
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS:
             $r_farm_roles = array();
             $BundleTask->Log(sprintf("Bundle task replacement type: %s", $BundleTask->replaceType));
             try {
                 $DBFarm = DBFarm::LoadByID($BundleTask->farmId);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "not found in database")) {
                     $BundleTask->SnapshotCreationFailed("Farm was removed before task was finished");
                 }
                 return;
             }
             if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_FARM) {
                 try {
                     $r_farm_roles[] = $DBFarm->GetFarmRoleByRoleID($BundleTask->prototypeRoleId);
                 } catch (Exception $e) {
                 }
             } elseif ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                 $farm_roles = $db->GetAll("SELECT id FROM farm_roles WHERE role_id=? AND new_role_id=? AND farmid IN (SELECT id FROM farms WHERE env_id=?)", array($BundleTask->prototypeRoleId, $BundleTask->roleId, $BundleTask->envId));
                 foreach ($farm_roles as $farm_role) {
                     try {
                         $r_farm_roles[] = DBFarmRole::LoadByID($farm_role['id']);
                     } catch (Exception $e) {
                     }
                 }
             }
             $update_farm_dns_zones = array();
             $completed_roles = 0;
             foreach ($r_farm_roles as $DBFarmRole) {
                 if ($DBFarmRole->CloudLocation != $BundleTask->cloudLocation) {
                     $BundleTask->Log(sprintf("Role '%s' (ID: %s), farm '%s' (ID: %s) using the same role but in abother cloud location. Skiping it.", $DBFarmRole->GetRoleObject()->name, $DBFarmRole->ID, $DBFarmRole->GetFarmObject()->Name, $DBFarmRole->FarmID));
                     $completed_roles++;
                 } else {
                     $servers = $db->GetAll("SELECT server_id FROM servers WHERE farm_roleid = ? AND role_id=? AND status NOT IN (?,?)", array($DBFarmRole->ID, $DBFarmRole->RoleID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE));
                     $BundleTask->Log(sprintf("Found %s servers that need to be replaced with new ones. Role '%s' (ID: %s), farm '%s' (ID: %s)", count($servers), $DBFarmRole->GetRoleObject()->name, $DBFarmRole->ID, $DBFarmRole->GetFarmObject()->Name, $DBFarmRole->FarmID));
                     if (count($servers) == 0) {
                         $DBFarmRole->RoleID = $DBFarmRole->NewRoleID;
                         $DBFarmRole->NewRoleID = null;
                         $DBFarmRole->Save();
                         $update_farm_dns_zones[$DBFarmRole->FarmID] = 1;
                         $completed_roles++;
                     } else {
                         $metaData = $BundleTask->getSnapshotDetails();
                         foreach ($servers as $server) {
                             try {
                                 $DBServer = DBServer::LoadByID($server['server_id']);
                             } catch (Exception $e) {
                                 //TODO:
                                 continue;
                             }
                             if ($DBServer->serverId == $BundleTask->serverId || $metaData['noServersReplace']) {
                                 $DBServer->roleId = $BundleTask->roleId;
                                 $DBServer->Save();
                                 if ($metaData['noServersReplace']) {
                                     $BundleTask->Log(sprintf("'Do not replace servers' option was checked. Server '%s' won't be replaced to new image.", $DBServer->serverId));
                                 } else {
                                     $BundleTask->Log(sprintf("Server '%s', on which snapshot has been taken, already has all modifications. No need to replace it.", $DBServer->serverId));
                                 }
                                 if ($DBServer->GetFarmObject()->Status == FARM_STATUS::SYNCHRONIZING) {
                                     PlatformFactory::NewPlatform($DBServer->platform)->TerminateServer($DBServer);
                                     $db->Execute("UPDATE servers_history SET\r\n\t\t\t\t\t\t\t\t\t\t\t\tdtterminated\t= NOW(),\r\n\t\t\t\t\t\t\t\t\t\t\t\tterminate_reason\t= ?\r\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE server_id = ?\r\n\t\t\t\t\t\t\t\t\t\t\t", array(sprintf("Farm was in 'Synchronizing' state. Server terminated when bundling was completed. Bundle task #%s", $BundleTask->id), $DBServer->serverId));
                                 }
                             } else {
                                 if (!$db->GetOne("SELECT server_id FROM servers WHERE replace_server_id=? AND status NOT IN (?,?)", array($DBServer->serverId, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) {
                                     $ServerCreateInfo = new ServerCreateInfo($DBFarmRole->Platform, $DBFarmRole, $DBServer->index, $DBFarmRole->NewRoleID);
                                     $nDBServer = Scalr::LaunchServer($ServerCreateInfo);
                                     $nDBServer->replaceServerID = $DBServer->serverId;
                                     $nDBServer->Save();
                                     $BundleTask->Log(sprintf(_("Started new server %s to replace server %s"), $nDBServer->serverId, $DBServer->serverId));
                                 }
                             }
                             // if serverid != bundletask->serverID
                         }
                         // foreach server
                     }
                     // count($servers)
                 }
             }
             if ($completed_roles == count($r_farm_roles)) {
                 $BundleTask->Log(sprintf(_("No servers with old role. Replacement complete. Bundle task complete."), SERVER_REPLACEMENT_TYPE::NO_REPLACE, SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS));
                 $BundleTask->setDate('finished');
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                 $BundleTask->Save();
             }
             try {
                 if (count($update_farm_dns_zones) != 0) {
                     foreach ($update_farm_dns_zones as $farm_id => $v) {
                         $dnsZones = DBDNSZone::loadByFarmId($farm_id);
                         foreach ($dnsZones as $dnsZone) {
                             if ($dnsZone->status != DNS_ZONE_STATUS::INACTIVE && $dnsZone->status != DNS_ZONE_STATUS::PENDING_DELETE) {
                                 $dnsZone->updateSystemRecords();
                                 $dnsZone->save();
                             }
                         }
                     }
                 }
             } catch (Exception $e) {
                 $this->Logger->fatal("DNS ZONE: {$e->getMessage()}");
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::CREATING_ROLE:
             try {
                 if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                     $saveOldRole = false;
                     try {
                         $dbRole = DBRole::loadById($DBServer->roleId);
                         if ($dbRole->name == $BundleTask->roleName && $dbRole->envId == $BundleTask->envId) {
                             $saveOldRole = true;
                         }
                     } catch (Exception $e) {
                         //NO OLD ROLE
                     }
                     if ($dbRole && $saveOldRole) {
                         if ($DBServer) {
                             $new_role_name = BundleTask::GenerateRoleName($DBServer->GetFarmRoleObject(), $DBServer);
                         } else {
                             $new_role_name = $BundleTask->roleName . "-" . rand(1000, 9999);
                         }
                         $dbRole->name = $new_role_name;
                         $BundleTask->Log(sprintf(_("Old role '%s' (ID: %s) renamed to '%s'"), $BundleTask->roleName, $dbRole->id, $new_role_name));
                         $dbRole->save();
                     } else {
                         //TODO:
                         //$this->Logger->error("dbRole->replace->fail({$BundleTask->roleName}, {$BundleTask->envId})");
                     }
                 }
                 try {
                     $DBRole = DBRole::createFromBundleTask($BundleTask);
                 } catch (Exception $e) {
                     $BundleTask->SnapshotCreationFailed("Role creation failed due to internal error ({$e->getMessage()}). Please try again.");
                     return;
                 }
                 if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::NO_REPLACE) {
                     $BundleTask->setDate('finished');
                     $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                     $BundleTask->Log(sprintf(_("Replacement type: %s. Bundle task status: %s"), SERVER_REPLACEMENT_TYPE::NO_REPLACE, SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS));
                     try {
                         $DBServer = DBServer::LoadByID($BundleTask->serverId);
                         if ($DBServer->status == SERVER_STATUS::IMPORTING) {
                             if ($DBServer->farmId) {
                                 // Create DBFarmRole object
                                 // TODO: create DBFarm role
                             }
                             //$DBServer->Delete();
                         }
                     } catch (Exception $e) {
                     }
                 } else {
                     try {
                         $BundleTask->Log(sprintf(_("Replacement type: %s. Bundle task status: %s"), $BundleTask->replaceType, SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS));
                         if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_FARM) {
                             $DBFarm = DBFarm::LoadByID($BundleTask->farmId);
                             $DBFarmRole = $DBFarm->GetFarmRoleByRoleID($BundleTask->prototypeRoleId);
                             $DBFarmRole->NewRoleID = $BundleTask->roleId;
                             $DBFarmRole->Save();
                         } else {
                             $farm_roles = $db->GetAll("SELECT id FROM farm_roles WHERE role_id=? AND farmid IN (SELECT id FROM farms WHERE env_id=?)", array($BundleTask->prototypeRoleId, $BundleTask->envId));
                             foreach ($farm_roles as $farm_role) {
                                 $DBFarmRole = DBFarmRole::LoadByID($farm_role['id']);
                                 $DBFarmRole->NewRoleID = $BundleTask->roleId;
                                 $DBFarmRole->Save();
                             }
                         }
                         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS;
                     } catch (Exception $e) {
                         $this->Logger->error($e->getMessage());
                         $BundleTask->Log(sprintf(_("Server replacement failed: %s"), $e->getMessage()));
                         $BundleTask->setDate('finished');
                         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                     }
                 }
                 $BundleTask->Save();
             } catch (Exception $e) {
                 $this->Logger->error($e->getMessage());
             }
             break;
     }
 }
Пример #21
0
 public function ServerImageCreate($ServerID, $RoleName)
 {
     $this->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE);
     $DBServer = DBServer::LoadByID($ServerID);
     // Validate client and server
     if ($DBServer->envId != $this->Environment->id) {
         throw new Exception(sprintf("Server ID #%s not found", $ServerID));
     }
     $this->user->getPermissions()->validate($DBServer);
     //Check for already running bundle on selected instance
     $chk = $this->DB->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($ServerID));
     if ($chk) {
         throw new Exception(sprintf(_("Server '%s' is already synchonizing."), $ServerID));
     }
     //Check is role already synchronizing...
     $chk = $this->DB->GetOne("SELECT server_id FROM bundle_tasks WHERE prototype_role_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($DBServer->GetFarmRoleObject()->RoleID));
     if ($chk && $chk != $DBServer->serverId) {
         try {
             $bDBServer = DBServer::LoadByID($chk);
             if ($bDBServer->farmId == $DBServer->farmId) {
                 throw new Exception(sprintf(_("Role '%s' is already synchonizing."), $DBServer->GetFarmRoleObject()->GetRoleObject()->name));
             }
         } catch (Exception $e) {
         }
     }
     try {
         $DBRole = DBRole::loadByFilter(array("name" => $RoleName, "env_id" => $DBServer->envId));
     } catch (Exception $e) {
     }
     if (!$DBRole) {
         $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo($DBServer, $RoleName, SERVER_REPLACEMENT_TYPE::NO_REPLACE, BundleTask::BUNDLETASK_OBJECT_ROLE, 'Bundled via API');
         $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
         $BundleTask->createdById = $this->user->id;
         $BundleTask->createdByEmail = $this->user->getEmail();
         $BundleTask->save();
         $response = $this->CreateInitialResponse();
         $response->BundleTaskID = $BundleTask->id;
         return $response;
     } else {
         throw new Exception(_("Specified role name is already used by another role"));
     }
 }
Пример #22
0
 public function GlobalVariablesList($ServerID = null, $FarmID = null, $FarmRoleID = null, $RoleID = null)
 {
     if (empty($FarmID) && empty($FarmRoleID) && empty($RoleID) && empty($ServerID)) {
         $this->restrictAccess(Acl::RESOURCE_ENVADMINISTRATION_GLOBAL_VARIABLES);
     }
     $response = $this->CreateInitialResponse();
     $response->VariableSet = new stdClass();
     $response->VariableSet->Item = array();
     if ($ServerID) {
         $DBServer = DBServer::LoadByID($ServerID);
         if ($DBServer->envId != $this->Environment->id) {
             throw new Exception(sprintf("Server ID #%s not found", $ServerID));
         }
         $this->user->getPermissions()->validate($DBServer);
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
         $vars = $globalVariables->listVariables($DBServer->roleId, $DBServer->farmId, $DBServer->farmRoleId, $ServerID);
     } elseif ($FarmID) {
         $DBFarm = DBFarm::LoadByID($FarmID);
         if ($DBFarm->EnvID != $this->Environment->id) {
             throw new Exception(sprintf("Farm ID #%s not found", $FarmID));
         }
         $this->user->getPermissions()->validate($DBFarm);
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $vars = $globalVariables->listVariables(null, $DBFarm->ID, null);
     } elseif ($RoleID) {
         $DBRole = DBRole::LoadByID($RoleID);
         if ($DBRole->envId != $this->Environment->id) {
             throw new Exception(sprintf("Role ID #%s not found", $RoleID));
         }
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_ROLE);
         $vars = $globalVariables->listVariables($RoleID, null, null);
     } elseif ($FarmRoleID) {
         $DBFarmRole = DBFarmRole::LoadByID($FarmRoleID);
         if ($DBFarmRole->GetFarmObject()->EnvID != $this->Environment->id) {
             throw new Exception(sprintf("FarmRole ID #%s not found", $FarmRoleID));
         }
         $this->user->getPermissions()->validate($DBFarmRole);
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
         $vars = $globalVariables->listVariables($DBFarmRole->RoleID, $DBFarmRole->FarmID, $DBFarmRole->ID);
     } else {
         $globalVariables = new Scalr_Scripting_GlobalVariables($this->Environment->clientId, $this->Environment->id, Scalr_Scripting_GlobalVariables::SCOPE_ENVIRONMENT);
         $vars = $globalVariables->listVariables();
     }
     foreach ($vars as $v) {
         $itm = new stdClass();
         $itm->{"Name"} = $v['name'];
         $itm->{"Value"} = $v['value'];
         $itm->{"Private"} = $v['private'];
         $response->VariableSet->Item[] = $itm;
     }
     return $response;
 }
Пример #23
0
 /**
  * Deletes this script
  *
  * @throws Scalr_Exception_Core
  * @throws Exception
  * @throws ModelException
  */
 public function delete()
 {
     // Check script usage
     $usage = [];
     $farmRolesCount = $this->db()->GetOne("SELECT COUNT(DISTINCT farm_roleid) FROM farm_role_scripts WHERE scriptid=?", array($this->id));
     if ($farmRolesCount > 0) {
         $message = [];
         foreach ($this->db()->GetCol("SELECT DISTINCT farm_roleid FROM farm_role_scripts WHERE scriptid = ? LIMIT 3", array($this->id)) as $id) {
             $dbFarmRole = \DBFarmRole::LoadByID($id);
             $message[] = $dbFarmRole->GetFarmObject()->Name . ' (' . $dbFarmRole->Alias . ')';
         }
         $usage[] = sprintf("%d farm roles: %s%s", $farmRolesCount, join(', ', $message), $farmRolesCount > 3 ? ' and others' : '');
     }
     $rolesCount = $this->db()->GetOne("SELECT COUNT(DISTINCT role_id) FROM role_scripts WHERE script_id=?", array($this->id));
     if ($rolesCount > 0) {
         $message = [];
         foreach ($this->db()->GetCol("SELECT DISTINCT role_id FROM role_scripts WHERE script_id = ? LIMIT 3", array($this->id)) as $id) {
             $dbRole = \DBRole::LoadByID($id);
             $message[] = $dbRole->name;
         }
         $usage[] = sprintf("%d roles: %s%s", $rolesCount, join(', ', $message), $rolesCount > 3 ? ' and others' : '');
     }
     $accountCount = $this->db()->GetOne("SELECT COUNT(*) FROM account_scripts WHERE script_id=?", array($this->id));
     if ($accountCount > 0) {
         $usage[] = sprintf("%d orchestration rule(s) on account level", $accountCount);
     }
     $taskCount = $this->db()->GetOne("SELECT COUNT(*) FROM scheduler WHERE script_id = ?", array($this->id));
     if ($taskCount > 0) {
         $usage[] = sprintf("%d scheduler task(s)", $taskCount);
     }
     if (count($usage)) {
         throw new Scalr_Exception_Core(sprintf('Script "%s" being used by %s, and can\'t be deleted', $this->name, join(', ', $usage)));
     }
     Tag::deleteTags(Tag::RESOURCE_SCRIPT, $this->id);
     parent::delete();
 }
Пример #24
0
734fa0c7-cbec-4ebc-a8b1-ffed833be097 - psql-ubuntu1204-shared-10102013
156f8821-ea33-4d59-b36e-2dbae17eed62 - redis-ubuntu1204-shared-10102013
4ce9d4ce-1798-462e-8ee9-22dc21c19375 - mysql-ubuntu1204-shared-10102013
37751ad0-8507-4f58-966a-328ef0a7c7f0 - apache-ubuntu1204-shared-10102013
b54b4117-fd27-4576-9947-a1b03b1209ce - base-ubuntu1204-shared-10102013
*/
$roles = array(array('name' => 'base-ubuntu1204', 'os' => 'Ubuntu 12.04', 'osFamily' => 'ubuntu', 'catId' => 1, 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('base', 'chef'), 'description' => 'Base role', 'images' => array(array('image_id' => 'b54b4117-fd27-4576-9947-a1b03b1209ce', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'mysql5-ubuntu1204', 'os' => 'Ubuntu 12.04', 'catId' => 2, 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('mysql2', 'chef'), 'description' => 'MySQL 5', 'images' => array(array('image_id' => '4ce9d4ce-1798-462e-8ee9-22dc21c19375', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'percona5-ubuntu1204', 'catId' => 2, 'os' => 'Ubuntu 12.04', 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('percona', 'chef'), 'description' => 'Percona 5', 'images' => array(array('image_id' => '68ad6daa-05c1-4286-b2dd-5deca7c1a6c8', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'postgresql-ubuntu1204', 'catId' => 2, 'os' => 'Ubuntu 12.04', 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('postgresql', 'chef'), 'description' => 'PostgreSQL', 'images' => array(array('image_id' => '734fa0c7-cbec-4ebc-a8b1-ffed833be097', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'redis-ubuntu1204', 'catId' => 2, 'os' => 'Ubuntu 12.04', 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('redis', 'chef'), 'description' => 'Redis', 'images' => array(array('image_id' => '156f8821-ea33-4d59-b36e-2dbae17eed62', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'mongodb-ubuntu1204', 'os' => 'Ubuntu 12.04', 'catId' => 2, 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('mongodb', 'chef'), 'description' => 'MongoDB', 'images' => array(array('image_id' => '933cc1b0-9130-4979-a873-1c4cc6adc4eb', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'apache-ubuntu1204', 'os' => 'Ubuntu 12.04', 'catId' => 3, 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('app', 'chef'), 'description' => 'Apache', 'images' => array(array('image_id' => '37751ad0-8507-4f58-966a-328ef0a7c7f0', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'tomcat-ubuntu1204', 'os' => 'Ubuntu 12.04', 'catId' => 3, 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('tomcat', 'chef'), 'description' => 'Tomcat', 'images' => array(array('image_id' => '366554c9-6961-4238-b7f5-b012909e55a8', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'nginx-ubuntu1204', 'os' => 'Ubuntu 12.04', 'osFamily' => 'ubuntu', 'catId' => 4, 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('www', 'chef'), 'description' => 'Nginx', 'images' => array(array('image_id' => 'e35edb3b-f995-4915-bd37-2008e29c1db7', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'haproxy-ubuntu1204', 'os' => 'Ubuntu 12.04', 'osFamily' => 'ubuntu', 'catId' => 4, 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('haproxy', 'chef'), 'description' => 'HAProxy', 'images' => array(array('image_id' => 'b10299b5-464a-4871-b354-6c5d12e00ce1', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'rabbitmq-ubuntu1204', 'os' => 'Ubuntu 12.04', 'catId' => 5, 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('rabbitmq', 'chef'), 'description' => 'RabbitMQ', 'images' => array(array('image_id' => '128fd870-c897-455f-88a6-77f0c4ee538f', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'memcached-ubuntu1204', 'os' => 'Ubuntu 12.04', 'catId' => 6, 'osFamily' => 'ubuntu', 'osGeneration' => '12.04', 'osVersion' => '12.04', 'behaviors' => array('memcached', 'chef'), 'description' => 'Memcached', 'images' => array(array('image_id' => '95c27eb7-4973-4b14-a9b4-3508b02b3392', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'base-centos6', 'os' => 'CentOS 6.4', 'osFamily' => 'centos', 'osGeneration' => '6', 'catId' => 1, 'osVersion' => '6.4', 'behaviors' => array('base', 'chef'), 'description' => 'Base role', 'images' => array(array('image_id' => '9b723be4-c34d-4e00-9c89-aea36f4ba9f5', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'mysql5-centos6', 'os' => 'CentOS 6.4', 'catId' => 2, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('mysql2', 'chef'), 'description' => 'MySQL 5', 'images' => array(array('image_id' => '085c37a7-8355-41a8-b6c2-52cb3345be10', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'percona5-centos6', 'os' => 'CentOS 6.4', 'osFamily' => 'centos', 'catId' => 2, 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('percona', 'chef'), 'description' => 'Percona 5', 'images' => array(array('image_id' => 'e5b5ddc1-baae-4fc1-b0b2-edfa248ce291', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'postgresql-centos6', 'os' => 'CentOS 6.4', 'osFamily' => 'centos', 'catId' => 2, 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('postgresql', 'chef'), 'description' => 'PostgreSQL', 'images' => array(array('image_id' => '9144dff0-5440-4029-8ca1-86192cdc0be1', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'redis-centos6', 'os' => 'CentOS 6.4', 'catId' => 2, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('redis', 'chef'), 'description' => 'Redis', 'images' => array(array('image_id' => '2892d4f4-4cc4-4468-94ac-fb8c5651fe8c', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'mongodb-centos6', 'os' => 'CentOS 6.4', 'catId' => 2, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('mongodb', 'chef'), 'description' => 'MongoDB', 'images' => array(array('image_id' => '1ed9ea0a-0363-4714-af1b-0a0ddde9451d', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'apache-centos6', 'os' => 'CentOS 6.4', 'catId' => 3, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('app', 'chef'), 'description' => 'Apache', 'images' => array(array('image_id' => '13d16a4a-3972-40a6-a058-2d6176a70cae', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'tomcat-centos6', 'os' => 'CentOS 6.4', 'catId' => 3, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('tomcat', 'chef'), 'description' => 'Tomcat', 'images' => array(array('image_id' => '5fb15d6e-333e-4367-93bb-0cd27e00a0dd', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'nginx-centos6', 'os' => 'CentOS 6.4', 'catId' => 4, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('www', 'chef'), 'description' => 'Nginx', 'images' => array(array('image_id' => '2d40a20c-e749-408c-b936-feb6ac7fdb50', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'haproxy-centos6', 'os' => 'CentOS 6.4', 'catId' => 4, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('haproxy', 'chef'), 'description' => 'HAProxy', 'images' => array(array('image_id' => 'e4ac6980-4eab-43f0-a298-b6a1e462e12d', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'rabbitmq-centos6', 'os' => 'CentOS 6.4', 'catId' => 5, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('rabbitmq', 'chef'), 'description' => 'RabbitMQ', 'images' => array(array('image_id' => '449780ec-68d9-498f-b6aa-74e54aa376b7', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))), array('name' => 'memcached-centos6', 'os' => 'CentOS 6.4', 'catId' => 6, 'osFamily' => 'centos', 'osGeneration' => '6', 'osVersion' => '6.4', 'behaviors' => array('memcached', 'chef'), 'description' => 'Memcached', 'images' => array(array('image_id' => '0ce1388d-9bbc-45b1-b3f9-150414d09b29', 'platform' => 'openstack', 'location' => 'ItalyMilano1', 'szr_version' => '0.19.10', 'architecture' => 'x86_64'))));
foreach ($roles as $info) {
    if (!$info['name']) {
        continue;
    }
    $dbInfoId = $db->GetOne("SELECT id FROM roles WHERE name = ? AND origin = ? LIMIT 1", array($info['name'], 'SHARED'));
    if ($dbInfoId) {
        $dbRole = DBRole::loadById($dbInfoId);
    } else {
        $dbRole = new DBRole(0);
        $dbRole->generation = 2;
        $dbRole->origin = ROLE_TYPE::SHARED;
        $dbRole->envId = 0;
        $dbRole->clientId = 0;
        $dbRole->catId = $info['catId'];
        $dbRole->name = $info['name'];
        $dbRole->os = $info['os'];
        $dbRole->osFamily = $info['osFamily'];
        $dbRole->osGeneration = $info['osGeneration'];
        $dbRole->osVersion = $info['osVersion'];
        foreach ($info['behaviors'] as $behavior) {
            foreach (Scalr_Role_Behavior::loadByName($behavior)->getSecurityRules() as $rr) {
                $rules[] = array('rule' => $rr);
            }
        }
Пример #25
0
 /**
  * @param  string    $platform
  * @param  string    $cloudLocation
  * @param  int    $roleId
  * @throws Exception
  */
 public function xGetRootDeviceInfoAction($platform, $cloudLocation, $roleId)
 {
     if (!in_array($platform, $this->getEnvironment()->getEnabledPlatforms())) {
         throw new Exception(sprintf('Platform "%s" is not enabled', $platform));
     }
     $role = DBRole::loadById($roleId)->__getNewRoleObject();
     $image = $role->getImage($platform, $cloudLocation)->getImage();
     $data = ['readOnly' => true, 'mountPoint' => $role->getOs()->family == 'windows' ? 'C:\\ (ROOT)' : '/ (ROOT)'];
     $settings = [];
     switch ($platform) {
         case SERVER_PLATFORMS::CLOUDSTACK:
             $data['type'] = 'csvol';
             $data['readOnly'] = true;
             break;
         case SERVER_PLATFORMS::GCE:
             // Get default size
             $p = PlatformFactory::NewPlatform(SERVER_PLATFORMS::GCE);
             $gceClient = $p->getClient($this->environment);
             /* @var $gceClient Google_Service_Compute */
             $ind = strpos($image->id, '/global/');
             if ($ind !== FALSE) {
                 $projectId = substr($image->id, 0, $ind);
                 $id = str_replace("{$projectId}/global/images/", '', $image->id);
             } else {
                 $ind = strpos($image->id, '/images/');
                 if ($ind !== false) {
                     $projectId = substr($image->id, 0, $ind);
                 } else {
                     $projectId = $this->environment->keychain(SERVER_PLATFORMS::GCE)->properties[Entity\CloudCredentialsProperty::GCE_PROJECT_ID];
                 }
                 $id = str_replace("{$projectId}/images/", '', $image->id);
             }
             try {
                 $imageInfo = $gceClient->images->get($projectId, $id);
                 $settings = [FarmRoleStorageConfig::SETTING_GCE_PD_TYPE => 'pd-standard', FarmRoleStorageConfig::SETTING_GCE_PD_SIZE => $imageInfo->diskSizeGb];
             } catch (Exception $e) {
                 // gce client returns error as json-encoded message
                 if ($e->getMessage() && ($json = json_decode($e->getMessage())) && is_object($json) && !empty($json->error)) {
                     throw new Exception($json->error->message);
                 } else {
                     throw $e;
                 }
             }
             $data['type'] = 'gce_persistent';
             $data['readOnly'] = false;
             break;
         case SERVER_PLATFORMS::EC2:
             if ($image->isEc2EbsImage()) {
                 $data['type'] = 'ebs';
                 $aws = $this->getEnvironment()->aws($cloudLocation);
                 $cloudImageInfo = $aws->ec2->image->describe($image->id)[0];
                 if ($cloudImageInfo->blockDeviceMapping) {
                     foreach ($cloudImageInfo->blockDeviceMapping as $blockDeviceMapping) {
                         if (stristr($blockDeviceMapping->deviceName, $cloudImageInfo->rootDeviceName)) {
                             $data['readOnly'] = false;
                             $settings[FarmRoleStorageConfig::SETTING_EBS_TYPE] = $blockDeviceMapping->ebs->volumeType;
                             $settings[FarmRoleStorageConfig::SETTING_EBS_SIZE] = $blockDeviceMapping->ebs->volumeSize;
                             $settings[FarmRoleStorageConfig::SETTING_EBS_SNAPSHOT] = $blockDeviceMapping->ebs->snapshotId;
                             $settings[FarmRoleStorageConfig::SETTING_EBS_IOPS] = $blockDeviceMapping->ebs->iops;
                             $settings[FarmRoleStorageConfig::SETTING_EBS_DEVICE_NAME] = $blockDeviceMapping->deviceName;
                         }
                     }
                 }
             } else {
                 $data['type'] = 'instance-store';
                 $settings['size'] = '10';
             }
             break;
     }
     $data['settings'] = $settings;
     $this->response->data(array('data' => $data));
 }
Пример #26
0
 public function xReplaceRoleAction()
 {
     if (!$this->request->getParam('roleId')) {
         throw new Exception("Please select role");
     }
     $dbFarmRole = DBFarmRole::LoadByID($this->getParam(self::CALL_PARAM_NAME));
     $this->user->getPermissions()->validate($dbFarmRole);
     $this->request->restrictFarmAccess($this->dbFarm, Acl::PERM_FARMS_MANAGE);
     $newRole = DBRole::loadById($this->request->getParam('roleId'));
     $this->checkPermissions($newRole->__getNewRoleObject());
     if (!empty($envs = $newRole->__getNewRoleObject()->getAllowedEnvironments())) {
         if (!in_array($this->getEnvironmentId(), $envs)) {
             throw new Exception("You don't have access to this role");
         }
     }
     //TODO: Add validation of cloud/location/os_family and behavior
     $oldName = $dbFarmRole->GetRoleObject()->name;
     $dbFarmRole->RoleID = $newRole->id;
     $dbFarmRole->Save();
     \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($dbFarmRole->FarmID, sprintf("Role '%s' was upgraded to role '%s'", $oldName, $newRole->name)));
     $image = $newRole->__getNewRoleObject()->getImage($dbFarmRole->Platform, $dbFarmRole->CloudLocation)->getImage();
     $this->response->success("Role successfully replaced.");
     $this->response->data(array('role' => array('role_id' => $newRole->id, 'name' => $newRole->name, 'os' => $newRole->getOs()->name, 'osId' => $newRole->getOs()->id, 'generation' => $newRole->generation, 'image' => ['id' => $image->id, 'type' => $image->type, 'architecture' => $image->architecture], 'behaviors' => join(",", $newRole->getBehaviors()))));
 }
Пример #27
0
 public function xReplaceRoleAction()
 {
     if (!$this->request->getParam('roleId')) {
         throw new Exception("Please select role");
     }
     $dbFarmRole = DBFarmRole::LoadByID($this->getParam(self::CALL_PARAM_NAME));
     $this->user->getPermissions()->validate($dbFarmRole);
     $newRole = DBRole::loadById($this->request->getParam('roleId'));
     if ($newRole->envId != 0) {
         $this->user->getPermissions()->validate($newRole);
     }
     //TODO: Add validation of cloud/location/os_family and behavior
     $oldName = $dbFarmRole->GetRoleObject()->name;
     $dbFarmRole->RoleID = $newRole->id;
     $dbFarmRole->Save();
     Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($dbFarmRole->FarmID, sprintf("Role '%s' was upgraded to role '%s'", $oldName, $newRole->name)));
     $image = $newRole->__getNewRoleObject()->getImage($dbFarmRole->Platform, $dbFarmRole->CloudLocation)->getImage();
     $this->response->success("Role successfully replaced.");
     $this->response->data(array('role' => array('role_id' => $newRole->id, 'name' => $newRole->name, 'os' => $newRole->getOs()->name, 'osId' => $newRole->getOs()->id, 'generation' => $newRole->generation, 'image' => ['id' => $image->id, 'type' => $image->type, 'architecture' => $image->architecture])));
 }
Пример #28
0
 public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $runInstanceRequest = new RunInstancesRequestData(isset($launchOptions->imageId) ? $launchOptions->imageId : null, 1, 1);
     $environment = $DBServer->GetEnvironmentObject();
     $placementData = null;
     $noSecurityGroups = false;
     if (!$launchOptions) {
         $launchOptions = new Scalr_Server_LaunchOptions();
         $DBRole = DBRole::loadById($DBServer->roleId);
         $dbFarmRole = $DBServer->GetFarmRoleObject();
         /*
         $runInstanceRequest->setMonitoring(
             $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_ENABLE_CW_MONITORING)
         );
         */
         $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::EUCALYPTUS, $dbFarmRole->CloudLocation);
         // Need OS Family to get block device mapping for OEL roles
         $imageInfo = $DBRole->getImageDetails(SERVER_PLATFORMS::EUCALYPTUS, $dbFarmRole->CloudLocation);
         $launchOptions->osFamily = $imageInfo['os_family'];
         $launchOptions->cloudLocation = $dbFarmRole->CloudLocation;
         $akiId = $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::EKIID);
         if (!$akiId) {
             $akiId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_EKI_ID);
         }
         if ($akiId) {
             $runInstanceRequest->kernelId = $akiId;
         }
         $ariId = $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::ERIID);
         if (!$ariId) {
             $ariId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_ERI_ID);
         }
         if ($ariId) {
             $runInstanceRequest->ramdiskId = $ariId;
         }
         $launchOptions->serverType = $dbFarmRole->GetSetting(DBFarmRole::SETTING_EUCA_INSTANCE_TYPE);
         /*
         if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_EBS_OPTIMIZED) == 1) {
             $runInstanceRequest->ebsOptimized = true;
         } else {
             $runInstanceRequest->ebsOptimized = false;
         }
         */
         foreach ($DBServer->GetCloudUserData() as $k => $v) {
             $u_data .= "{$k}={$v};";
         }
         $runInstanceRequest->userData = base64_encode(trim($u_data, ";"));
         /*
         $vpcId = $dbFarmRole->GetFarmObject()->GetSetting(DBFarm::SETTING_EC2_VPC_ID);
         if ($vpcId) {
             if ($DBRole->hasBehavior(ROLE_BEHAVIORS::VPC_ROUTER)) {
                 $networkInterface = new InstanceNetworkInterfaceSetRequestData();
                 $networkInterface->networkInterfaceId = $dbFarmRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_NID);
                 $networkInterface->deviceIndex = 0;
                 $networkInterface->deleteOnTermination = false;
         
                 $runInstanceRequest->setNetworkInterface($networkInterface);
                 $noSecurityGroups = true;
             } else {
         
                 $vpcSubnetId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_SUBNET_ID);
                 $vpcInternetAccess = $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_INTERNET_ACCESS);
                 if (!$vpcSubnetId) {
                     $aws = $environment->aws($launchOptions->cloudLocation);
         
                     $subnet = $this->AllocateNewSubnet(
                         $aws->ec2,
                         $vpcId,
                         $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_AVAIL_ZONE),
                         24
                     );
         
                     try {
                         $subnet->createTags(array(
                             array('key' => "scalr-id", 'value' => SCALR_ID),
                             array('key' => "scalr-sn-type", 'value' => $vpcInternetAccess),
                             array('key' => "Name", 'value' => 'Scalr System Subnet')
                         ));
                     } catch (Exception $e) {}
         
                     try {
         
                         $routeTableId = $dbFarmRole->GetSetting(DBFarmRole::SETTING_AWS_VPC_ROUTING_TABLE_ID);
         
                         Logger::getLogger('VPC')->warn(new FarmLogMessage($DBServer->farmId, "Internet access: {$vpcInternetAccess}"));
         
                         if (!$routeTableId) {
                             if ($vpcInternetAccess == Scalr_Role_Behavior_Router::INTERNET_ACCESS_OUTBOUND) {
                                 $routerRole = $DBServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER);
                                 if (!$routerRole) {
                                     if (\Scalr::config('scalr.instances_connection_policy') != 'local')
                                         throw new Exception("Outbound access require VPC router role in farm");
                                 }
         
                                 $networkInterfaceId = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_NID);
         
                                 Logger::getLogger('EC2')->warn(new FarmLogMessage($DBServer->farmId, "Requesting outbound routing table. NID: {$networkInterfaceId}"));
         
                                 $routeTableId = $this->getRoutingTable($vpcInternetAccess, $aws, $networkInterfaceId, $vpcId);
         
                                 Logger::getLogger('EC2')->warn(new FarmLogMessage($DBServer->farmId, "Routing table ID: {$routeTableId}"));
         
                             } elseif ($vpcInternetAccess == Scalr_Role_Behavior_Router::INTERNET_ACCESS_FULL) {
                                 $routeTableId = $this->getRoutingTable($vpcInternetAccess, $aws, null, $vpcId);
                             }
                         }
         
                         $aws->ec2->routeTable->associate($routeTableId, $subnet->subnetId);
         
                     } catch (Exception $e) {
         
                         Logger::getLogger('EC2')->warn(new FarmLogMessage($DBServer->farmId, "Removing allocated subnet, due to routing table issues"));
         
                         $aws->ec2->subnet->delete($subnet->subnetId);
                         throw $e;
                     }
         
                     $vpcSubnetId = $subnet->subnetId;
                     $dbFarmRole->SetSetting(DBFarmRole::SETTING_AWS_VPC_SUBNET_ID, $vpcSubnetId, DBFarmRole::TYPE_LCL);
                 }
         
                 if ($vpcSubnetId) {
                     $runInstanceRequest->subnetId = $vpcSubnetId;
                 } else
                     throw new Exception("Unable to define subnetId for role in VPC");
             }
         }
         */
         $vpcId = false;
     } else {
         $runInstanceRequest->userData = base64_encode(trim($launchOptions->userData));
     }
     $governance = new Scalr_Governance($DBServer->envId);
     $euca = $environment->eucalyptus($launchOptions->cloudLocation);
     // Set AMI, AKI and ARI ids
     $runInstanceRequest->imageId = $launchOptions->imageId;
     $runInstanceRequest->instanceInitiatedShutdownBehavior = 'terminate';
     if (!$noSecurityGroups) {
         foreach ($this->GetServerSecurityGroupsList($DBServer, $euca->ec2, $vpcId, $governance) as $sgroup) {
             $runInstanceRequest->appendSecurityGroupId($sgroup);
         }
         if (!$runInstanceRequest->subnetId) {
             // Set availability zone
             if (!$launchOptions->availZone) {
                 $avail_zone = $this->GetServerAvailZone($DBServer, $euca->ec2, $launchOptions);
                 if ($avail_zone) {
                     $placementData = new PlacementResponseData($avail_zone);
                 }
             } else {
                 $placementData = new PlacementResponseData($launchOptions->availZone);
             }
         }
     }
     $runInstanceRequest->minCount = 1;
     $runInstanceRequest->maxCount = 1;
     // Set instance type
     $runInstanceRequest->instanceType = $launchOptions->serverType;
     if ($placementData !== null) {
         $runInstanceRequest->setPlacement($placementData);
     }
     $sshKey = Scalr_SshKey::init();
     if ($DBServer->status == SERVER_STATUS::TEMPORARY) {
         $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID;
         $farmId = 0;
     } else {
         $keyName = $governance->getValue(Scalr_Governance::AWS_KEYPAIR);
         if ($keyName) {
             $skipKeyValidation = true;
         } else {
             $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID;
             $farmId = $DBServer->farmId;
             $oldKeyName = "FARM-{$DBServer->farmId}";
             if ($sshKey->loadGlobalByName($oldKeyName, $launchOptions->cloudLocation, $DBServer->envId, SERVER_PLATFORMS::EUCALYPTUS)) {
                 $keyName = $oldKeyName;
                 $skipKeyValidation = true;
             }
         }
     }
     if (!$skipKeyValidation && !$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId, SERVER_PLATFORMS::EUCALYPTUS)) {
         $result = $euca->ec2->keyPair->create($keyName);
         if ($result->keyMaterial) {
             $sshKey->farmId = $farmId;
             $sshKey->clientId = $DBServer->clientId;
             $sshKey->envId = $DBServer->envId;
             $sshKey->type = Scalr_SshKey::TYPE_GLOBAL;
             $sshKey->cloudLocation = $launchOptions->cloudLocation;
             $sshKey->cloudKeyName = $keyName;
             $sshKey->platform = SERVER_PLATFORMS::EUCALYPTUS;
             $sshKey->setPrivate($result->keyMaterial);
             $sshKey->setPublic($sshKey->generatePublicKey());
             $sshKey->save();
         }
     }
     $runInstanceRequest->keyName = $keyName;
     try {
         $result = $euca->ec2->instance->run($runInstanceRequest);
     } catch (Exception $e) {
         if (stristr($e->getMessage(), "The key pair") && stristr($e->getMessage(), "does not exist")) {
             $sshKey->delete();
             throw $e;
         }
         if (stristr($e->getMessage(), "The requested Availability Zone is no longer supported") || stristr($e->getMessage(), "is not supported in your requested Availability Zone") || stristr($e->getMessage(), "is currently constrained and we are no longer accepting new customer requests")) {
             $availZone = $runInstanceRequest->getPlacement() ? $runInstanceRequest->getPlacement()->availabilityZone : null;
             if ($availZone) {
                 $DBServer->GetEnvironmentObject()->setPlatformConfig(array("eucalyptus.{$launchOptions->cloudLocation}.{$availZone}.unavailable" => time()));
             }
             throw $e;
         } else {
             throw $e;
         }
     }
     if ($result->instancesSet->get(0)->instanceId) {
         $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::AVAIL_ZONE, $result->instancesSet->get(0)->placement->availabilityZone);
         $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_ID, $result->instancesSet->get(0)->instanceId);
         $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_TYPE, $runInstanceRequest->instanceType);
         $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::EMIID, $runInstanceRequest->imageId);
         $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::REGION, $launchOptions->cloudLocation);
         $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::ARCHITECTURE, $result->instancesSet->get(0)->architecture);
         $DBServer->osType = $result->instancesSet->get(0)->platform ? $result->instancesSet->get(0)->platform : 'linux';
         return $DBServer;
     } else {
         throw new Exception(sprintf(_("Cannot launch new instance. %s"), serialize($result)));
     }
 }
 public function OnHostDown(HostDownEvent $event)
 {
     if ($event->DBServer->IsRebooting() == 1) {
         $event->exit = 'reboot';
         return;
     }
     if (!$this->FarmID) {
         $event->exit = 'no-farm';
         return;
     }
     $dbFarm = DBFarm::LoadByID($this->FarmID);
     $servers = $dbFarm->GetServersByFilter(array('status' => array(SERVER_STATUS::RUNNING)));
     try {
         $DBFarmRole = $event->DBServer->GetFarmRoleObject();
         $is_synchronize = $DBFarmRole->NewRoleID ? true : false;
     } catch (Exception $e) {
         $is_synchronize = false;
     }
     try {
         $DBRole = DBRole::loadById($event->DBServer->roleId);
     } catch (Exception $e) {
     }
     //HUGE BUG HERE!
     $first_in_role_handled = false;
     $first_in_role_server = null;
     $event->msgExpected = count($servers);
     foreach ($servers as $DBServer) {
         if (!$DBServer instanceof DBServer) {
             continue;
         }
         $isfirstinrole = '0';
         $eventServerIsMaster = $event->DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) || $event->DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER);
         if ($eventServerIsMaster && !$first_in_role_handled) {
             if (!$is_synchronize && $DBServer->farmRoleId == $event->DBServer->farmRoleId) {
                 if (DBRole::loadById($DBServer->roleId)->hasBehavior(ROLE_BEHAVIORS::MYSQL) || DBRole::loadById($DBServer->roleId)->getDbMsrBehavior()) {
                     $first_in_role_handled = true;
                     $first_in_role_server = $DBServer;
                     $isfirstinrole = '1';
                 }
             }
         }
         $msg = new Scalr_Messaging_Msg_HostDown();
         //TODO:
         $msg->behaviour = $DBRole ? $DBRole->getBehaviors() : '*Unknown*';
         $msg->roleName = $DBRole ? $DBRole->name : '*Unknown*';
         $msg->localIp = $event->DBServer->localIp;
         $msg->remoteIp = $event->DBServer->remoteIp;
         $msg->isFirstInRole = $isfirstinrole;
         $msg->serverIndex = $event->DBServer->index;
         $msg->farmRoleId = $event->DBServer->farmRoleId;
         $msg->serverId = $event->DBServer->serverId;
         $msg->cloudLocation = $event->DBServer->GetCloudLocation();
         // If FarmRole was removed from farm, no configuration left
         if ($DBFarmRole) {
             $msg = Scalr_Scripting_Manager::extendMessage($msg, $event, $event->DBServer, $DBServer);
             if ($event->DBServer->farmRoleId != 0) {
                 foreach (Scalr_Role_Behavior::getListForRole(DBRole::loadById($event->DBServer->roleId)) as $behavior) {
                     $msg = $behavior->extendMessage($msg, $event->DBServer);
                 }
             }
         }
         $msg = $DBServer->SendMessage($msg, false, true);
         if ($msg->dbMessageId) {
             $event->msgCreated++;
         }
         $loopServerIsMaster = $DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) || $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER);
         if ($loopServerIsMaster && $DBServer->status == SERVER_STATUS::RUNNING) {
             $doNotPromoteSlave2Master = true;
         }
     }
     if (!$DBFarmRole) {
         return;
     }
     if ($DBFarmRole->GetRoleObject()->getDbMsrBehavior() && !$doNotPromoteSlave2Master && !$DBFarmRole->GetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER)) {
         $this->sendPromoteToMasterMessage($event);
     }
     //LEGACY MYSQL CODE:
     if ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MYSQL)) {
         // If EC2 master down
         if ($event->DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) && $DBFarmRole) {
             $master = $dbFarm->GetMySQLInstances(true);
             if ($master[0]) {
                 return;
             }
             $msg = new Scalr_Messaging_Msg_Mysql_PromoteToMaster($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_ROOT_PASSWORD), $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_REPL_PASSWORD), $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_STAT_PASSWORD));
             if ($event->DBServer->IsSupported("0.7")) {
                 if (in_array($event->DBServer->platform, array(SERVER_PLATFORMS::EC2, SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::UCLOUD))) {
                     try {
                         $volume = Scalr_Storage_Volume::init()->loadById($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_SCALR_VOLUME_ID));
                         $msg->volumeConfig = $volume->getConfig();
                     } catch (Exception $e) {
                         $this->Logger->error(new FarmLogMessage($event->DBServer->farmId, "Cannot create volumeConfig for PromoteToMaster message: {$e->getMessage()}"));
                     }
                 }
             } elseif ($event->DBServer->platform == SERVER_PLATFORMS::EC2) {
                 $msg->volumeId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID);
             }
             // Send Mysql_PromoteToMaster to the first server in the same avail zone as old master (if exists)
             // Otherwise send to first in role
             $platform = $event->DBServer->platform;
             if ($platform == SERVER_PLATFORMS::EC2) {
                 $availZone = $event->DBServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE);
             }
             foreach ($servers as $DBServer) {
                 if ($DBServer->serverId == $event->DBServer->serverId) {
                     continue;
                 }
                 if ($platform == SERVER_PLATFORMS::EC2 && $DBServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE) == $availZone || $platform != SERVER_PLATFORMS::EC2) {
                     if (DBRole::loadById($DBServer->roleId)->hasBehavior(ROLE_BEHAVIORS::MYSQL)) {
                         $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER, 1);
                         $DBServer->SetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER, 1);
                         $DBServer->SendMessage($msg, false, true);
                         return;
                     }
                 }
             }
             if ($first_in_role_server) {
                 $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER, 1);
                 $first_in_role_server->SetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER, 1);
                 $first_in_role_server->SendMessage($msg, false, true);
             }
         }
     }
 }
Пример #30
0
 public function getFarmWidgetRoles($farmId, $options)
 {
     $dbFarm = DBFarm::LoadById($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $dataFarmRoles = array();
     $behaviors = array();
     foreach ($options as $key => $value) {
         $matches = explode('_', $value);
         if ($matches[0] == 'behavior' && $matches[1]) {
             $behaviors[] = $matches[1];
         }
     }
     foreach ($this->db->GetAll("SELECT id, platform, role_id, alias AS name FROM farm_roles WHERE farmid = ?", array($dbFarm->ID)) as $farmRole) {
         try {
             $dbRole = DBRole::loadById($farmRole['role_id']);
             if (!empty($behaviors)) {
                 $bFilter = false;
                 foreach ($behaviors as $behavior) {
                     if ($dbRole->hasBehavior($behavior)) {
                         $bFilter = true;
                         break;
                     }
                 }
                 if (!$bFilter) {
                     continue;
                 }
             }
         } catch (Exception $e) {
             $farmRole['name'] = '*removed*';
         }
         array_push($dataFarmRoles, $farmRole);
     }
     if (count($dataFarmRoles) && in_array('addAll', $options)) {
         array_unshift($dataFarmRoles, array('id' => '0', 'name' => 'On all roles'));
     }
     if (in_array('addEmpty', $options)) {
         array_unshift($dataFarmRoles, array('id' => '', 'name' => ''));
     }
     if (!empty($dataFarmRoles)) {
         return $dataFarmRoles;
     } else {
         return null;
     }
 }