/** * @return Scalr_Dm_Source */ public function getSource() { if (!$this->source) { $this->source = Scalr_Model::init(Scalr_Model::DM_SOURCE)->loadById($this->sourceId); } return $this->source; }
/** * @return Scalr_Environment */ public function getEnvironmentObject() { if (!$this->environment) { $this->environment = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadById($this->envId); } return $this->environment; }
public static function farmSave(DBFarm $DBFarm, array $roles) { foreach ($roles as $DBFarmRole) { if ($DBFarmRole->Platform != SERVER_PLATFORMS::EUCALYPTUS) { continue; } $location = $DBFarmRole->CloudLocation; $sshKey = Scalr_Model::init(Scalr_Model::SSH_KEY); if (!$sshKey->loadGlobalByFarmId($DBFarm->ID, $location)) { $key_name = "FARM-{$DBFarm->ID}"; $eucaClient = Scalr_Service_Cloud_Eucalyptus::newCloud($DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Eucalyptus::SECRET_KEY, true, $location), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Eucalyptus::ACCESS_KEY, true, $location), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Eucalyptus::EC2_URL, true, $location)); $result = $eucaClient->CreateKeyPair($key_name); if ($result->keyMaterial) { $sshKey->farmId = $DBFarm->ID; $sshKey->clientId = $DBFarm->ClientID; $sshKey->envId = $DBFarm->EnvID; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $location; $sshKey->cloudKeyName = $key_name; $sshKey->platform = SERVER_PLATFORMS::EUCALYPTUS; $sshKey->setPrivate($result->keyMaterial); $sshKey->save(); } } } }
public function getApplication() { if (!$this->application) { $this->application = Scalr_Model::init(Scalr_Model::DM_APPLICATION)->loadById($this->applicationId); } return $this->application; }
public static function farmSave(\DBFarm $DBFarm, array $roles) { foreach ($roles as $DBFarmRole) { if ($DBFarmRole->Platform != \SERVER_PLATFORMS::EC2) { continue; } $location = $DBFarmRole->CloudLocation; $sshKey = \Scalr_Model::init(\Scalr_Model::SSH_KEY); if (!$sshKey->loadGlobalByFarmId($DBFarm->EnvID, $DBFarm->ID, $location, \SERVER_PLATFORMS::EC2)) { $key_name = "FARM-" . $DBFarm->ID . "-" . SCALR_ID; $aws = $DBFarm->GetEnvironmentObject()->aws($location); $result = $aws->ec2->keyPair->create($key_name); if (!empty($result->keyMaterial)) { $sshKey->farmId = $DBFarm->ID; $sshKey->envId = $DBFarm->EnvID; $sshKey->type = \Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $location; $sshKey->cloudKeyName = $key_name; $sshKey->platform = \SERVER_PLATFORMS::EC2; $sshKey->setPrivate($result->keyMaterial); $sshKey->save(); } } } }
public static function onCreateDataBundleResult(Scalr_Messaging_Msg $message, DBServer $dbServer) { $dbFarm = $dbServer->GetFarmObject(); $dbFarmRole = $dbServer->GetFarmRoleObject(); $dbFarmRole->SetSetting(Scalr_Db_Msr::DATA_BUNDLE_LAST_TS, time()); $dbFarmRole->SetSetting(Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, 0); //$dbFarmRole->SetSetting(Scalr_Db_Msr::DATA_BUNDLE_SERVER_ID, ""); $dbSettings = $message->{$message->dbType}; if ($dbSettings->snapshotConfig) { try { $snapshot = Scalr_Model::init(Scalr_Model::STORAGE_SNAPSHOT); $snapshot->loadBy(array('id' => $dbSettings->snapshotConfig->id, 'client_id' => $dbServer->clientId, 'env_id' => $dbServer->envId, 'name' => "Automatical '{$message->dbType}' data bundle", 'type' => $dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_ENGINE), 'platform' => $dbServer->platform, 'description' => "'{$message->dbType}' data bundle created automatically by Scalr", 'service' => $message->dbType)); $snapshot->setConfig($dbSettings->snapshotConfig); $snapshot->save(true); $dbFarmRole->SetSetting(Scalr_Db_Msr::SNAPSHOT_ID, $snapshot->id); if ($message->dbType == self::DB_TYPE_MYSQL) { $dbFarmRole->SetSetting(Scalr_Db_Msr_Mysql::LOG_FILE, $dbSettings->logFile); $dbFarmRole->SetSetting(Scalr_Db_Msr_Mysql::LOG_POS, $dbSettings->logPos); } elseif ($message->dbType == self::DB_TYPE_POSTGRESQL) { $dbFarmRole->SetSetting(Scalr_Db_Msr_Postgresql::XLOG_LOCATION, $dbSettings->currentXlogLocation); } elseif ($message->dbType == self::DB_TYPE_REDIS) { //Nothing todo } } catch (Exception $e) { Logger::getLogger(__CLASS__)->error(new FarmLogMessage($dbServer->farmId, "Cannot save storage snapshot: {$e->getMessage()}")); } } }
public function OnStartForking() { $db = Core::GetDBInstance(null, true); // selects rows where the snapshot's time has come to create new snapshot. $resultset = $db->Execute("SELECT * FROM autosnap_settings \r\n\t\t\t\t\t\tWHERE (UNIX_TIMESTAMP(DATE_ADD(dtlastsnapshot, INTERVAL period HOUR)) < UNIX_TIMESTAMP(NOW())\r\n\t\t\t\t\t\tOR dtlastsnapshot IS NULL)\r\n\t\t\t\t\t\tAND objectid \t!= '0' \r\n\t\t\t\t\t\tAND object_type = ?", array(AUTOSNAPSHOT_TYPE::RDSSnap)); while ($snapshotsSettings = $resultset->FetchRow()) { try { $environment = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadById($snapshotsSettings['env_id']); $AmazonRDSClient = Scalr_Service_Cloud_Aws::newRds($environment->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY), $environment->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY), $snapshotsSettings['region']); // Check instance. If instance wasn't found then delete current recrod from settings table try { $AmazonRDSClient->DescribeDBInstances($snapshotsSettings['objectid']); } catch (Exception $e) { if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid") || stristr($e->getMessage(), "security token included in the request is invalid")) { $db->Execute("DELETE FROM autosnap_settings WHERE id = ?", array($snapshotsSettings['id'])); } $this->Logger->error(sprintf(_("RDS instance %s was not found. Auto-snapshot settings for this \r\n\t\t\t\t\t\t\t\tinstance will be deleted. %s."), $snapshotsSettings['objectid'], $e->getMessage())); throw $e; } // snapshot random unique name $snapshotId = "scalr-auto-" . dechex(microtime(true) * 10000) . rand(0, 9); try { // Create new snapshot $AmazonRDSClient->CreateDBSnapshot($snapshotId, $snapshotsSettings['objectid']); // update last snapshot creation date in settings $db->Execute("UPDATE autosnap_settings SET last_snapshotid=?, dtlastsnapshot=NOW() WHERE id=?", array($snapshotId, $snapshotsSettings['id'])); // create new snapshot record in DB $db->Execute("INSERT INTO rds_snaps_info SET \r\n\t\t\t\t\t\t\tsnapid\t\t= ?,\r\n\t\t\t\t\t\t\tcomment\t\t= ?,\r\n\t\t\t\t\t\t\tdtcreated\t= NOW(),\r\n\t\t\t\t\t\t\tregion\t\t= ?,\r\n\t\t\t\t\t\t\tautosnapshotid = ?", array($snapshotId, _("Auto snapshot"), $snapshotsSettings['region'], $snapshotsSettings['id'])); } catch (Exception $e) { $this->Logger->warn(sprintf(_("Cannot create RDS snapshot: %s."), $e->getMessage())); } // Remove old snapshots if ($snapshotsSettings['rotate'] != 0) { $oldSnapshots = $db->GetAll("SELECT * FROM rds_snaps_info WHERE autosnapshotid = ? ORDER BY id ASC", array($snapshotsSettings['id'])); if (count($oldSnapshots) > $snapshotsSettings['rotate']) { while (count($oldSnapshots) > $snapshotsSettings['rotate']) { // takes the oldest snapshot ... $deletingSnapshot = array_shift($oldSnapshots); try { // and deletes it from amazon and from DB $AmazonRDSClient->DeleteDBSnapshot($deletingSnapshot['snapid']); $db->Execute("DELETE FROM rds_snaps_info WHERE id = ?", array($deletingSnapshot['id'])); } catch (Exception $e) { if (stristr($e->getMessage(), "not found") || stristr($e->getMessage(), "not a valid")) { $db->Execute("DELETE FROM rds_snaps_info WHERE id = ?", array($deletingSnapshot['id'])); } $this->Logger->error(sprintf(_("DBsnapshot %s for RDS instance %s was not found \r\n\t\t\t\t\t\t\t\t\t\t\t\tand cannot be deleted . %s."), $deletingSnapshot['snapid'], $snapshotsSettings['objectid'], $e->getMessage())); } } } } } catch (Exception $e) { $this->Logger->warn(sprintf(_("Cannot create snapshot for RDS Instance %s. %s"), $snapshotsSettings['objectid'], $e->getMessage())); } } }
/** * 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}'."); } }
function setFarmRoleMetrics($metrics) { foreach ($this->farmRoleMetrics as $id => $farmRoleMetric) { if (!$metrics[$farmRoleMetric->metricId]) { $farmRoleMetric->delete(); unset($this->farmRoleMetrics[$farmRoleMetric->metricId]); } } foreach ($metrics as $metric_id => $metric_settings) { if (!$this->farmRoleMetrics[$metric_id]) { $this->farmRoleMetrics[$metric_id] = Scalr_Model::init(Scalr_Model::SCALING_FARM_ROLE_METRIC); $this->farmRoleMetrics[$metric_id]->metricId = $metric_id; $this->farmRoleMetrics[$metric_id]->farmRoleId = $this->dbFarmRole->ID; } $this->farmRoleMetrics[$metric_id]->setSettings($metric_settings); $this->farmRoleMetrics[$metric_id]->save(); } }
function handleWork($deploymentTaskId) { try { $deploymentTask = Scalr_Model::init(Scalr_Model::DM_DEPLOYMENT_TASK)->loadById($deploymentTaskId); try { $dbServer = DBServer::LoadByID($deploymentTask->serverId); } catch (Exception $e) { $deploymentTask->status = Scalr_Dm_DeploymentTask::STATUS_ARCHIVED; return; } switch ($deploymentTask->status) { case Scalr_Dm_DeploymentTask::STATUS_PENDING: $deploymentTask->deploy(); break; case Scalr_Dm_DeploymentTask::STATUS_DEPLOYING: //TODO: break; } } catch (Exception $e) { var_dump($e->getMessage()); } }
function setFarmRoleMetrics($metrics) { foreach ($this->farmRoleMetrics as $id => $farmRoleMetric) { if (!$metrics[$farmRoleMetric->metricId]) { $farmRoleMetric->delete(); unset($this->farmRoleMetrics[$farmRoleMetric->metricId]); } } foreach ($metrics as $metric_id => $metric_settings) { if (!is_array($metric_settings)) { continue; } if (!$this->farmRoleMetrics[$metric_id]) { $this->farmRoleMetrics[$metric_id] = Scalr_Model::init(Scalr_Model::SCALING_FARM_ROLE_METRIC); $this->farmRoleMetrics[$metric_id]->metricId = $metric_id; $this->farmRoleMetrics[$metric_id]->farmRoleId = $this->dbFarmRole->ID; } $this->farmRoleMetrics[$metric_id]->clearSettings(); $this->farmRoleMetrics[$metric_id]->setSettings($metric_settings); $this->farmRoleMetrics[$metric_id]->save(false, array('dtlastpolled', 'last_value', 'last_data')); } }
/** * * @return Scalr_SshKey */ public static function init($className = null) { return parent::init(); }
/** * @param Scalr_Messaging_Msg_Mysql_PromoteToMasterResult $message * @param DBServer $dbserver */ private function onMysql_PromoteToMasterResult($message, DBServer $dbserver) { $dbserver->GetFarmRoleObject()->SetSetting(DBFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER, 0); if ($message->status == Scalr_Messaging_Msg_Mysql_PromoteToMasterResult::STATUS_OK) { $dbFarm = $dbserver->GetFarmObject(); $dbFarmRole = $dbserver->GetFarmRoleObject(); $oldMaster = $dbFarm->GetMySQLInstances(true); if ($dbserver->IsSupported("0.7")) { if ($message->volumeConfig) { try { $storageVolume = Scalr_Storage_Volume::init(); try { $storageVolume->loadById($message->volumeConfig->id); $storageVolume->setConfig($message->volumeConfig); $storageVolume->save(); } catch (Exception $e) { if (strpos($e->getMessage(), 'not found')) { $storageVolume->loadBy(array('id' => $message->volumeConfig->id, 'client_id' => $dbserver->clientId, 'env_id' => $dbserver->envId, 'name' => "MySQL data volume", 'type' => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE), 'platform' => $dbserver->platform, 'size' => $message->volumeConfig->size, 'fstype' => $message->volumeConfig->fstype, 'purpose' => ROLE_BEHAVIORS::MYSQL, 'farm_roleid' => $dbserver->farmRoleId, 'server_index' => $dbserver->index)); $storageVolume->setConfig($message->volumeConfig); $storageVolume->save(true); } else { throw $e; } } } catch (Exception $e) { $this->logger->error(new FarmLogMessage($dbserver->farmId, "Cannot save storage volume: {$e->getMessage()}")); } } if ($message->snapshotConfig) { try { $snapshot = Scalr_Model::init(Scalr_Model::STORAGE_SNAPSHOT); $snapshot->loadBy(array('id' => $message->snapshotConfig->id, 'client_id' => $dbserver->clientId, 'env_id' => $dbserver->envId, 'name' => "Automatical MySQL data bundle", 'type' => $dbFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_DATA_STORAGE_ENGINE), 'platform' => $dbserver->platform, 'description' => "MySQL data bundle created automatically by Scalr", 'ismysql' => true)); $snapshot->setConfig($message->snapshotConfig); $snapshot->save(true); $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_SCALR_SNAPSHOT_ID, $snapshot->id); $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_LOG_FILE, $message->logFile); $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_LOG_POS, $message->logPos); } catch (Exception $e) { $this->logger->error(new FarmLogMessage($dbserver->farmId, "Cannot save storage snapshot: {$e->getMessage()}")); } } } else { // TODO: delete old slave volume if new one was created $dbFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID, $message->volumeId); } return new NewMysqlMasterUpEvent($dbserver, "", $oldMaster[0]); } elseif ($message->status == Scalr_Messaging_Msg_Mysql_PromoteToMasterResult::STATUS_FAILED) { $dbserver->SetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER, 0); $dbserver->SetProperty(Scalr_Db_Msr::REPLICATION_MASTER, 0); // XXX: Need to do smth $this->logger->error(sprintf("Promote to Master failed for server %s. Last error: %s", $dbserver->serverId, $message->lastError)); } }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $RunInstancesType = new RunInstancesType(); $RunInstancesType->ConfigureRootPartition(); if (!$launchOptions) { $launchOptions = new Scalr_Server_LaunchOptions(); $DBRole = DBRole::loadById($DBServer->roleId); // Set Cloudwatch monitoring $RunInstancesType->SetCloudWatchMonitoring($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_ENABLE_CW_MONITORING)); $launchOptions->architecture = $DBRole->architecture; $launchOptions->imageId = $DBRole->getImageId(SERVER_PLATFORMS::EC2, $DBServer->GetFarmRoleObject()->CloudLocation); $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation; $akiId = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::AKIID); if (!$akiId) { $akiId = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_AKI_ID); } if ($akiId) { $RunInstancesType->kernelId = $akiId; } $ariId = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::ARIID); if (!$ariId) { $ariId = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_ARI_ID); } if ($ariId) { $RunInstancesType->ramdiskId = $ariId; } $i_type = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_INSTANCE_TYPE); if (!$i_type) { $DBRole = DBRole::loadById($DBServer->roleId); $i_type = $DBRole->getProperty(EC2_SERVER_PROPERTIES::INSTANCE_TYPE); } $launchOptions->serverType = $i_type; foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } $RunInstancesType->SetUserData(trim($u_data, ";")); $vpcPrivateIp = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_VPC_PRIVATE_IP); $vpcSubnetId = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_VPC_SUBNET_ID); if ($vpcSubnetId) { $RunInstancesType->subnetId = $vpcSubnetId; if ($vpcPrivateIp) { $RunInstancesType->privateIpAddress = $vpcPrivateIp; } } } else { $RunInstancesType->SetUserData(trim($launchOptions->userData)); } $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $launchOptions->architecture); $EC2Client = Scalr_Service_Cloud_Aws::newEc2($launchOptions->cloudLocation, $DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::PRIVATE_KEY), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::CERTIFICATE)); // Set AMI, AKI and ARI ids $RunInstancesType->imageId = $launchOptions->imageId; if (!$RunInstancesType->subnetId) { // Set Security groups foreach ($this->GetServerSecurityGroupsList($DBServer, $EC2Client) as $sgroup) { $RunInstancesType->AddSecurityGroup($sgroup); } } $RunInstancesType->minCount = 1; $RunInstancesType->maxCount = 1; // Set availability zone if (!$launchOptions->availZone) { $avail_zone = $this->GetServerAvailZone($DBServer, $EC2Client, $launchOptions); if ($avail_zone) { $RunInstancesType->SetAvailabilityZone($avail_zone); } } else { $RunInstancesType->SetAvailabilityZone($launchOptions->availZone); } // Set instance type $RunInstancesType->instanceType = $launchOptions->serverType; if (in_array($RunInstancesType->instanceType, array('cc1.4xlarge', 'cg1.4xlarge', 'cc2.8xlarge'))) { $placementGroup = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_CLUSTER_PG); if (!$placementGroup) { $placementGroup = "scalr-role-{$DBServer->farmRoleId}"; if (!$EC2Client->CreatePlacementGroup($placementGroup)) { throw new Exception(sprintf(_("Cannot launch new instance. Unable to create placement group: %s"), $result->faultstring)); } $DBServer->GetFarmRoleObject()->SetSetting(DBFarmRole::SETTING_AWS_CLUSTER_PG, $placementGroup); } $RunInstancesType->SetPlacementGroup($placementGroup); } // Set additional info $RunInstancesType->additionalInfo = ""; ///// if ($DBServer->status == SERVER_STATUS::TEMPORARY) { $keyName = "SCALR-ROLESBUILDER"; $sshKey = Scalr_Model::init(Scalr_Model::SSH_KEY); if (!$sshKey->loadGlobalByName($keyName, $launchOptions->cloudLocation, $DBServer->envId)) { $result = $EC2Client->CreateKeyPair($keyName); if ($result->keyMaterial) { $sshKey->farmId = 0; $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::EC2; $sshKey->setPrivate($result->keyMaterial); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } } } else { $sshKey = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByFarmId($DBServer->farmId, $DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION)); $keyName = $sshKey->cloudKeyName; } ///// $RunInstancesType->keyName = $keyName; try { $result = $EC2Client->RunInstances($RunInstancesType); } catch (Exception $e) { if (stristr($e->getMessage(), "key pair") && stristr($e->getMessage(), "does not exist")) { $result = $EC2Client->CreateKeyPair($keyName); if ($result->keyMaterial) { $sshKey->setPrivate($result->keyMaterial); $sshKey->setPublic($sshKey->generatePublicKey()); $sshKey->save(); } //Your requested instance type (m2.2xlarge) is not supported in your requested Availability Zone (us-east-1a). Please retry your request by not specifying an Availability Zone or choosing us-east-1c, us-east-1b, us-east-1 } else { if (stristr($e->getMessage(), "The requested Availability Zone is no longer supported") || stristr($e->getMessage(), "is not supported in your requested Availability Zone")) { $availZone = $RunInstancesType->placement->availabilityZone; $DBServer->GetEnvironmentObject()->setPlatformConfig(array("aws.{$launchOptions->cloudLocation}.{$availZone}.unavailable" => time()), false); throw $e; } else { throw $e; } } } if ($result->instancesSet) { $DBServer->SetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE, (string) $result->instancesSet->item->placement->availabilityZone); $DBServer->SetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID, (string) $result->instancesSet->item->instanceId); $DBServer->SetProperty(EC2_SERVER_PROPERTIES::INSTANCE_TYPE, $RunInstancesType->instanceType); $DBServer->SetProperty(EC2_SERVER_PROPERTIES::AMIID, $RunInstancesType->imageId); $DBServer->SetProperty(EC2_SERVER_PROPERTIES::REGION, $launchOptions->cloudLocation); try { if ($DBServer->farmId != 0) { $CreateTagsType = new CreateTagsType(array((string) $result->instancesSet->item->instanceId), array("scalr-farm-id" => $DBServer->farmId, "scalr-farm-name" => $DBServer->GetFarmObject()->Name, "scalr-farm-role-id" => $DBServer->farmRoleId, "scalr-role-name" => $DBServer->GetFarmRoleObject()->GetRoleObject()->name, "scalr-server-id" => $DBServer->serverId)); $EC2Client->CreateTags($CreateTagsType); } } catch (Exception $e) { Logger::getLogger('EC2')->warn("Cannot add tags to server: {$e->getMessage()}"); } return $DBServer; } else { throw new Exception(sprintf(_("Cannot launch new instance. %s"), serialize($result))); } }
/** * Update database when 'hostInit' event recieved from instance * * @param HostInitEvent $event * */ public function OnHostInit(HostInitEvent $event) { $event->DBServer->SetProperty("tmp.status", $event->DBServer->status); $event->DBServer->localIp = $event->InternalIP; $event->DBServer->remoteIp = $event->ExternalIP; $event->DBServer->status = SERVER_STATUS::INIT; $event->DBServer->Save(); $event->DBServer->SetProperty("tmp.status.processed", $event->DBServer->status); $this->DB->Execute("DELETE FROM server_operations WHERE server_id=?", array($event->DBServer->serverId)); $event->DBServer->SetProperty(SERVER_PROPERTIES::SZR_IS_INIT_FAILED, false); try { $key = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByFarmId($event->DBServer->farmId, $event->DBServer->GetFarmRoleObject()->CloudLocation, $event->DBServer->platform); if ($key && !$key->getPublic()) { $key->setPublic($event->PublicKey); $key->save(); } } catch (Exception $e) { } }
public function GetServiceConfiguration($behavior) { $preset_id = $this->DB->GetOne("SELECT preset_id FROM farm_role_service_config_presets WHERE farm_roleid=? AND behavior=?", array($this->ID, $behavior)); if ($preset_id) { return Scalr_Model::init(Scalr_Model::SERVICE_CONFIGURATION)->loadById($preset_id); } else { return null; } }
$farmid = (int) $req_farmid; $watchername = $req_watchername; $graph_type = $req_graph_type; $role_name = $req_role_name ? $req_role_name : $req_role; if ($req_version == 2) { if ($role_name != 'FARM' && !stristr($role_name, "INSTANCE_")) { $role_name = "FR_{$role_name}"; } } $farminfo = $db->GetRow("SELECT status, id, env_id FROM farms WHERE id=?", array($farmid)); if ($farminfo["status"] != FARM_STATUS::RUNNING) { $result = array("success" => false, "msg" => _("Statistics not available for terminated farm")); } else { if ($farminfo['clientid'] != 0) { define("SCALR_SERVER_TZ", date("T")); $env = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadById($farminfo['env_id']); $tz = $env->getPlatformConfigValue(ENVIRONMENT_SETTINGS::TIMEZONE); if ($tz) { date_default_timezone_set($tz); } } $graph_info = GetGraphicInfo($graph_type); $image_path = APPPATH . "/cache/stats/{$farmid}/{$role_name}.{$watchername}.{$graph_type}.gif"; $farm_rrddb_dir = CONFIG::$RRD_DB_DIR . "/{$farminfo['id']}"; $rrddbpath = "{$farm_rrddb_dir}/{$role_name}/{$watchername}/db.rrd"; CONFIG::$RRD_GRAPH_STORAGE_TYPE = RRD_STORAGE_TYPE::LOCAL_FS; if (file_exists($rrddbpath)) { try { GenerateGraph($farmid, $role_name, $rrddbpath, $watchername, $graph_type, $image_path); $url = str_replace(array("%fid%", "%rn%", "%wn%"), array($farmid, $role_name, $watchername), CONFIG::$RRD_STATS_URL); $url = "{$url}{$graph_type}.gif";
function handleWork($farmRoleId) { try { $dbFarmRole = DBFarmRole::LoadByID($farmRoleId); $dbFarm = $dbFarmRole->GetFarmObject(); $env = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadById($dbFarm->EnvID); $tz = $env->getPlatformConfigValue(Scalr_Environment::SETTING_TIMEZONE); if (!$tz) { $tz = date_default_timezone_get(); } $farmTz = $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE); if ($farmTz) { $tz = $farmTz; } //skip terminated farms if ($dbFarm->Status != FARM_STATUS::RUNNING) { return; } } catch (Exception $e) { return; } //********* Check Replication status *********/ //TODO: //********* Bundle database data ***********/ $this->performDbMsrAction('BUNDLE', $dbFarmRole, $tz); $backupsNotSupported = in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::UCLOUD)); //********* Backup database data ***********/ if (!$backupsNotSupported) { $this->performDbMsrAction('BACKUP', $dbFarmRole, $tz); } }
public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null) { $DBRole = DBRole::loadById($DBServer->roleId); $eucaClient = $this->getEucaClient($DBServer->GetEnvironmentObject(), $DBServer->GetCloudLocation()); $i_type = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_EUCA_INSTANCE_TYPE); foreach ($DBServer->GetCloudUserData() as $k => $v) { $u_data .= "{$k}={$v};"; } /* $imageId, $instanceType, $keyName = null, $availZone = null, $securityGroup = array(), $userData = "", $minCount = 1, $maxCount = 1, $kernelId = null, $ramdiskId = null, $monitoring = false */ $DBServer->SetProperty(SERVER_PROPERTIES::ARCHITECTURE, $DBRole->architecture); $key_pair_name = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByFarmId($DBServer->farmId, $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::REGION))->cloudKeyName; $result = $eucaClient->runInstances($DBRole->getImageId(SERVER_PLATFORMS::EUCALYPTUS, $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::REGION)), $i_type, $key_pair_name, $this->GetServerAvailZone($DBServer), $this->GetServerSecurityGroupsList($DBServer, $eucaClient), trim($u_data, ";")); if ($result->instancesSet) { $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::AVAIL_ZONE, (string) $result->instancesSet->item[0]->placement->availabilityZone); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_ID, (string) $result->instancesSet->item[0]->instanceId); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::INSTANCE_TYPE, $i_type); $DBServer->SetProperty(EUCA_SERVER_PROPERTIES::EMIID, $DBRole->getImageId(SERVER_PLATFORMS::EUCALYPTUS, $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::REGION))); return $DBServer; } }
/** * * @return Scalr_Scaling_Metric */ function getMetric() { if (!$this->metric) { $this->metric = Scalr_Model::init(Scalr_Model::SCALING_METRIC)->loadById($this->metricId); } return $this->metric; }
/** * Update database when 'hostInit' event recieved from instance * * @param HostInitEvent $event * */ public function OnHostInit(HostInitEvent $event) { $event->DBServer->SetProperty("tmp.status", $event->DBServer->status); $event->DBServer->localIp = $event->InternalIP; $event->DBServer->remoteIp = $event->ExternalIP; $event->DBServer->status = SERVER_STATUS::INIT; $event->DBServer->Save(); $db = Scalr::getDb(); $event->DBServer->SetProperty("tmp.status.debug", "{$db->hasTransactions}:{$db->transCnt}"); $event->DBServer->SetProperty("tmp.status.processed", $event->DBServer->status); $event->DBServer->SetProperty(SERVER_PROPERTIES::SZR_IS_INIT_FAILED, false); try { $key = Scalr_Model::init(Scalr_Model::SSH_KEY)->loadGlobalByFarmId($event->DBServer->envId, $event->DBServer->farmId, $event->DBServer->GetFarmRoleObject()->CloudLocation, $event->DBServer->platform); if ($key && !$key->getPublic()) { $key->setPublic($event->PublicKey); $key->save(); } } catch (Exception $e) { } }
protected function buildStorageSettings() { if ($this->dbFarmRole->GetSetting(Scalr_Db_Msr::VOLUME_ID) && $this->replicationMaster) { try { $volume = Scalr_Storage_Volume::init()->loadById($this->dbFarmRole->GetSetting(Scalr_Db_Msr::VOLUME_ID)); $this->volumeConfig = $volume->getConfig(); } catch (Exception $e) { } } /*** * For Rackspace we ALWAYS need snapsjot_config for mysql * ***/ if ($this->dbFarmRole->GetSetting(Scalr_Db_Msr::SNAPSHOT_ID)) { try { $snapshotConfig = Scalr_Model::init(Scalr_Model::STORAGE_SNAPSHOT)->loadById($this->dbFarmRole->GetSetting(Scalr_Db_Msr::SNAPSHOT_ID)); $this->snapshotConfig = $snapshotConfig->getConfig(); } catch (Exception $e) { $this->logger->error(new FarmLogMessage($this->dbServer->farmId, "Cannot get snaphotConfig for hostInit message: {$e->getMessage()}")); } } //TODO: /** If new role and there is no volume, we need to create a new one **/ if ($this->replicationMaster && !$this->volumeConfig) { $this->volumeConfig = new stdClass(); $this->volumeConfig->type = $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_ENGINE); // For any Block storage APIs if ($this->volumeConfig->type == MYSQL_STORAGE_ENGINE::RAID_EBS) { $this->volumeConfig->type = 'raid'; $this->volumeConfig->vg = $this->databaseType; $this->volumeConfig->level = $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_RAID_LEVEL); $this->volumeConfig->disks = array(); for ($i = 1; $i <= $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_RAID_DISKS_COUNT); $i++) { $dsk = new stdClass(); $dsk->type = 'ebs'; $dsk->size = $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_RAID_DISK_SIZE); $this->volumeConfig->disks[] = $dsk; } $this->volumeConfig->snapPv = new stdClass(); $this->volumeConfig->snapPv->type = 'ebs'; $this->volumeConfig->snapPv->size = 1; } else { if ($this->volumeConfig->type != MYSQL_STORAGE_ENGINE::EPH && $this->volumeConfig->type != MYSQL_STORAGE_ENGINE::RAID_EBS) { $this->volumeConfig->size = $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EBS_SIZE); } else { if ($this->volumeConfig->type == MYSQL_STORAGE_ENGINE::EPH) { if ($this->dbFarmRole->Platform == SERVER_PLATFORMS::RACKSPACE) { $this->volumeConfig->snap_backend = sprintf("cf://scalr-%s-%s/data-bundles/%s/%s", $this->dbFarmRole->GetFarmObject()->EnvID, $this->dbFarmRole->CloudLocation, $this->dbFarmRole->FarmID, $this->databaseType); $this->volumeConfig->vg = $this->databaseType; $this->volumeConfig->disk = new stdClass(); $this->volumeConfig->disk->type = 'loop'; $this->volumeConfig->disk->size = '75%root'; } elseif ($this->dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { $this->volumeConfig->snap_backend = sprintf("s3://scalr-%s-%s/data-bundles/%s/%s", $this->dbFarmRole->GetFarmObject()->EnvID, $this->dbFarmRole->CloudLocation, $this->dbFarmRole->FarmID, $this->databaseType); $this->volumeConfig->vg = $this->databaseType; $this->volumeConfig->disk = $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EPH_DISK); $this->volumeConfig->size = "80%"; } } } } } }
protected function buildStorageSettings() { if ($this->dbFarmRole->GetSetting(Scalr_Db_Msr::VOLUME_ID) && $this->replicationMaster) { try { $volume = Scalr_Storage_Volume::init()->loadById($this->dbFarmRole->GetSetting(Scalr_Db_Msr::VOLUME_ID)); $this->volumeConfig = $volume->getConfig(); } catch (Exception $e) { } } /*** * For Rackspace we ALWAYS need snapsjot_config for mysql * ***/ if ($this->dbFarmRole->GetSetting(Scalr_Db_Msr::SNAPSHOT_ID)) { try { $snapshotConfig = Scalr_Model::init(Scalr_Model::STORAGE_SNAPSHOT)->loadById($this->dbFarmRole->GetSetting(Scalr_Db_Msr::SNAPSHOT_ID)); $this->snapshotConfig = $snapshotConfig->getConfig(); if ($this->snapshotConfig) { if ($this->snapshotConfig->type == MYSQL_STORAGE_ENGINE::EPH) { if ($this->dbFarmRole->Platform == SERVER_PLATFORMS::EC2) { if (!isset($this->snapshotConfig->disk)) { $this->snapshotConfig->disk = new stdClass(); } $this->snapshotConfig->disk->device = $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EPH_DISK); } } } } catch (Exception $e) { $this->logger->error(new FarmLogMessage($this->dbServer->farmId, "Cannot get snaphotConfig for hostInit message: {$e->getMessage()}")); } } if ($this->replicationMaster && $this->volumeConfig) { $this->volumeConfig->recreateIfMissing = (int) $this->dbFarmRole->GetSetting(Scalr_Role_DbMsrBehavior::ROLE_DATA_STORAGE_RECREATE_IF_MISSING); if ($this->volumeConfig->type == MYSQL_STORAGE_ENGINE::EPH) { if ($this->dbFarmRole->Platform == SERVER_PLATFORMS::EC2 && !$this->volumeConfig->disks) { $this->volumeConfig->disk->device = $this->dbFarmRole->GetSetting(Scalr_Db_Msr::DATA_STORAGE_EPH_DISK); } } } else { $this->volumeConfig = $this->getFreshVolumeConfig(); } }
public function DmApplicationDeploy($ApplicationID, $FarmRoleID, $RemotePath) { $this->restrictAccess(Acl::RESOURCE_DEPLOYMENTS_APPLICATIONS); $application = Scalr_Model::init(Scalr_Model::DM_APPLICATION)->loadById($ApplicationID); if ($application->envId != $this->Environment->id) { throw new Exception("Aplication not found in database"); } $dbFarmRole = DBFarmRole::LoadByID($FarmRoleID); if ($dbFarmRole->GetFarmObject()->EnvID != $this->Environment->id) { throw new Exception("Farm Role not found in database"); } $this->user->getPermissions()->validate($dbFarmRole); $servers = $dbFarmRole->GetServersByFilter(array('status' => SERVER_STATUS::RUNNING)); if (count($servers) == 0) { throw new Exception("There is no running servers on selected farm/role"); } $response = $this->CreateInitialResponse(); $response->DeploymentTasksSet = new stdClass(); $response->DeploymentTasksSet->Item = array(); foreach ($servers as $dbServer) { $taskId = Scalr_Dm_DeploymentTask::getId($ApplicationID, $dbServer->serverId, $RemotePath); $deploymentTask = Scalr_Model::init(Scalr_Model::DM_DEPLOYMENT_TASK); if (!$taskId) { try { if (!$dbServer->IsSupported("0.7.38")) { throw new Exception("Scalr agent installed on this server doesn't support deployments. Please update it to the latest version"); } $deploymentTask->create($FarmRoleID, $ApplicationID, $dbServer->serverId, Scalr_Dm_DeploymentTask::TYPE_API, $RemotePath, $this->Environment->id); } catch (Exception $e) { $itm = new stdClass(); $itm->ServerID = $dbServer->serverId; $itm->ErrorMessage = $e->getMessage(); $response->DeploymentTasksSet->Item[] = $itm; continue; } } else { $deploymentTask->loadById($taskId); $deploymentTask->status = Scalr_Dm_DeploymentTask::STATUS_PENDING; $deploymentTask->log("Re-deploying application. Status: pending"); $deploymentTask->save(); } $itm = new stdClass(); $itm->ServerID = $dbServer->serverId; $itm->DeploymentTaskID = $deploymentTask->id; $itm->FarmRoleID = $deploymentTask->farmRoleId; $itm->RemotePath = $deploymentTask->remotePath; $itm->Status = $deploymentTask->status; $response->DeploymentTasksSet->Item[] = $itm; } return $response; }
public function OnEndForking() { $db = Core::GetDBInstance(null, true); // Rotate MySQL master snapshots. $list = $db->GetAll("SELECT farm_roleid FROM farm_role_settings WHERE name=? AND value='1'", array(DBFarmRole::SETTING_MYSQL_EBS_SNAPS_ROTATION_ENABLED)); foreach ($list as $list_item) { try { $DBFarmRole = DBFarmRole::LoadByID($list_item['farm_roleid']); } catch (Exception $e) { continue; } $DBFarm = $DBFarmRole->GetFarmObject(); if ($DBFarm->Status == FARM_STATUS::RUNNING) { $old_snapshots = $db->GetAll("SELECT * FROM storage_snapshots WHERE ismysql='1' AND farm_roleid=? AND `type`='ebs' ORDER BY dtcreated ASC", array($DBFarmRole->ID)); if (count($old_snapshots) > $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_EBS_SNAPS_ROTATE)) { try { $AmazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($DBFarmRole->CloudLocation, $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE)); while (count($old_snapshots) > $DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_EBS_SNAPS_ROTATE)) { $snapinfo = array_shift($old_snapshots); try { $AmazonEC2Client->DeleteSnapshot($snapinfo['id']); $db->Execute("DELETE FROM ebs_snaps_info WHERE snapid=?", array($snapinfo['id'])); $db->Execute("DELETE FROM storage_snapshots WHERE id=?", array($snapinfo['id'])); } catch (Exception $e) { if (stristr($e->getMessage(), "does not exist")) { $db->Execute("DELETE FROM ebs_snaps_info WHERE snapid=?", array($snapinfo['id'])); $db->Execute("DELETE FROM storage_snapshots WHERE id=?", array($snapinfo['id'])); } else { throw $e; } } } } catch (Exception $e) { $this->logger->warn(sprintf(_("Cannot delete old snapshots for volume %s. %s"), $snapshot_settings['volumeid'], $e->getMessage())); } } } } // Auto - snapshoting $snapshots_settings = $db->Execute("SELECT * FROM autosnap_settings \r\n\t\t\t\t\tWHERE (UNIX_TIMESTAMP(DATE_ADD(dtlastsnapshot, INTERVAL period HOUR)) < UNIX_TIMESTAMP(NOW()) OR dtlastsnapshot IS NULL)\r\n\t\t\t\t\tAND objectid != '0' AND object_type = ?", array(AUTOSNAPSHOT_TYPE::EBSSnap)); while ($snapshot_settings = $snapshots_settings->FetchRow()) { try { $environment = Scalr_Model::init(Scalr_Model::ENVIRONMENT)->loadById($snapshot_settings['env_id']); $AmazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($snapshot_settings['region'], $environment->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $environment->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE)); // Check volume try { $AmazonEC2Client->DescribeVolumes($snapshot_settings['objectid']); } catch (Exception $e) { if (stristr($e->getMessage(), "does not exist")) { $db->Execute("DELETE FROM autosnap_settings WHERE id=?", array($snapshot_settings['id'])); } throw $e; } $description = "Auto snapshot created by Scalr"; if (true) { $info = $db->GetRow("SELECT * FROM ec2_ebs WHERE volume_id=?", array($snapshot_settings['objectid'])); $farmName = false; $roleName = false; $serverIndex = false; if ($info) { try { $farmName = DBFarm::LoadByID($info['farm_id'])->Name; $roleName = DBFarmRole::LoadByID($info['farm_roleid'])->GetRoleObject()->name; $serverIndex = $info['server_index']; } catch (Exception $e) { } } if (!$farmName) { try { //$info = Scalr_Storage_Volume::init()->loadById($snapshot_settings['objectid']); } catch (Exception $e) { } } if ($farmName) { $description = sprintf("Auto snapshot created by Scalr: %s -> %s #%s", $farmName, $roleName, $serverIndex); } } // Create new snapshot $result = $AmazonEC2Client->CreateSnapshot($snapshot_settings['objectid'], $description); $snapshot_id = $result->snapshotId; $db->Execute("UPDATE autosnap_settings SET last_snapshotid=?, dtlastsnapshot=NOW() WHERE id=?", array($snapshot_id, $snapshot_settings['id'])); $db->Execute("INSERT INTO ebs_snaps_info SET snapid=?, comment=?, dtcreated=NOW(), region=?, autosnapshotid=?", array($snapshot_id, _("Auto-snapshot"), $snapshot_settings['region'], $snapshot_settings['id'])); // Remove old snapshots if ($snapshot_settings['rotate'] != 0) { $old_snapshots = $db->GetAll("SELECT * FROM ebs_snaps_info WHERE autosnapshotid=? ORDER BY id ASC", array($snapshot_settings['id'])); if (count($old_snapshots) > $snapshot_settings['rotate']) { try { while (count($old_snapshots) > $snapshot_settings['rotate']) { $snapinfo = array_shift($old_snapshots); try { $AmazonEC2Client->DeleteSnapshot($snapinfo['snapid']); $db->Execute("DELETE FROM ebs_snaps_info WHERE id=?", array($snapinfo['id'])); } catch (Exception $e) { if (stristr($e->getMessage(), "does not exist")) { $db->Execute("DELETE FROM ebs_snaps_info WHERE id=?", array($snapinfo['id'])); } throw $e; } } } catch (Exception $e) { $this->logger->error(sprintf(_("Cannot delete old snapshots for volume %s. %s"), $snapshot_settings['objectid'], $e->getMessage())); } } } } catch (Exception $e) { $this->logger->warn(sprintf(_("Cannot create snapshot for volume %s. %s"), $snapshot_settings['objectid'], $e->getMessage())); } } }
/** * * @return Scalr_ServiceConfiguration */ public static function init() { return parent::init(); }
public static function farmSave(DBFarm $DBFarm, array $roles) { $buckets = array(); foreach ($roles as $DBFarmRole) { if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_S3_BUCKET)) { $buckets[$DBFarmRole->CloudLocation] = $DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_S3_BUCKET); } } foreach ($roles as $DBFarmRole) { if ($DBFarmRole->Platform != SERVER_PLATFORMS::EC2) { continue; } $location = $DBFarmRole->CloudLocation; $sshKey = Scalr_Model::init(Scalr_Model::SSH_KEY); if (!$sshKey->loadGlobalByFarmId($DBFarm->ID, $location)) { $key_name = "FARM-{$DBFarm->ID}"; $AmazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($location, $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE)); $result = $AmazonEC2Client->CreateKeyPair($key_name); if ($result->keyMaterial) { $sshKey->farmId = $DBFarm->ID; $sshKey->clientId = $DBFarm->ClientID; $sshKey->envId = $DBFarm->EnvID; $sshKey->type = Scalr_SshKey::TYPE_GLOBAL; $sshKey->cloudLocation = $location; $sshKey->cloudKeyName = $key_name; $sshKey->platform = SERVER_PLATFORMS::EC2; $sshKey->setPrivate($result->keyMaterial); $sshKey->save(); } } try { if (!$DBFarmRole->GetSetting(DBFarmRole::SETTING_AWS_S3_BUCKET)) { if (!$buckets[$location]) { $aws_account_id = $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCOUNT_ID); $bucket_name = "farm-{$DBFarm->Hash}-{$aws_account_id}-{$location}"; // // Create S3 Bucket (For MySQL, BackUs, etc.) // $AmazonS3 = new AmazonS3($DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY)); $buckets = $AmazonS3->ListBuckets(); $create_bucket = true; foreach ($buckets as $bucket) { if ($bucket->Name == $bucket_name) { $create_bucket = false; $buckets[$location] = $bucket_name; break; } } if ($create_bucket) { if ($AmazonS3->CreateBucket($bucket_name, $location)) { $buckets[$location] = $bucket_name; } } } $DBFarmRole->SetSetting(DBFarmRole::SETTING_AWS_S3_BUCKET, $buckets[$location]); } } catch (Exception $e) { throw new Exception("Amazon S3: {$e->getMessage()}"); } } }