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(); } } } }
/** * @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(); } } } }
/** * {@inheritdoc} * @see Scalr_Model::delete() */ public function delete($id = null) { if ($this->db->GetOne('SELECT COUNT(*) FROM apache_vhosts WHERE ssl_cert_id = ?', array($this->id)) > 0) { throw new Scalr_Exception_Core(sprintf('Certificate "%s" is used by apache virtual host(s)', $this->name)); } parent::delete(); }
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()}")); } } }
/** * {@inheritdoc} * @see Scalr_Model::save() */ public function save($forceInsert = false) { if (!$this->id) { $forceInsert = true; $this->id = Scalr::GenerateUID(true); } parent::save($forceInsert); }
public function loadGlobalByFarmId($farmId, $cloudLocation, $platform) { $info = $this->db->GetRow("SELECT * FROM ssh_keys WHERE `farm_id`=? AND (`cloud_location`=? OR `cloud_location` = '') AND `type`=? AND `platform` = ? LIMIT 1", array($farmId, $cloudLocation, self::TYPE_GLOBAL, $platform)); if (!$info) { return false; } else { return parent::loadBy($info); } }
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())); } } }
public function save($forceInsert = false) { parent::save(); if ($this->preDeployScript !== false) { $this->db->Execute("UPDATE dm_applications SET pre_deploy_script = ? WHERE id = ?", array($this->preDeployScript, $this->id)); } if ($this->postDeployScript !== false) { $this->db->Execute("UPDATE dm_applications SET post_deploy_script = ? WHERE id = ?", array($this->postDeployScript, $this->id)); } }
public function delete() { parent::delete(); foreach ($this->getGroups() as $group) { $this->db->Execute('DELETE FROM `account_group_permissions` WHERE group_id = ?', array($group['id'])); } $this->db->Execute('DELETE FROM `account_groups` WHERE team_id = ?', array($this->id)); $this->db->Execute('DELETE FROM `account_team_users` WHERE team_id = ?', array($this->id)); $this->db->Execute('DELETE FROM `account_team_envs` WHERE team_id = ?', array($this->id)); }
/** * 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}'."); } }
/** * {@inheritdoc} * @see Scalr_Model::save() */ public function save($forceInsert = false) { parent::save($forceInsert); // Save parts if ($this->isPartsChanged && $this->id) { $this->db->Execute("DELETE FROM services_db_backup_parts WHERE backup_id = ?", array($this->id)); foreach ($this->parts as $n => $part) { $this->db->Execute("INSERT INTO services_db_backup_parts SET\n `backup_id` \t= ?,\n `path`\t\t\t= ?,\n `size`\t\t\t= ?,\n `seq_number`\t= ?\n ", array($this->id, $part['path'], $part['size'], $n + 1)); } } return $this; }
public function save() { parent::save(); $this->db->Execute("DELETE FROM service_config_preset_data WHERE preset_id = ?", array($this->id)); foreach ($this->parameters as $param) { if ($param->getValue() != null) { //Save params $this->db->Execute("INSERT INTO service_config_preset_data SET\n\t\t\t\t\t\t`preset_id`\t= ?,\n\t\t\t\t\t\t`key`\t\t= ?,\n\t\t\t\t\t\t`value`\t\t= ?\n\t\t\t\t\t", array($this->id, $param->getName(), $param->getValue())); } } return true; }
public function loadGlobalByFarmId($envId, $farmId, $cloudLocation, $platform) { $sql = "SELECT * FROM ssh_keys WHERE `env_id` = ? AND (`cloud_location`=? OR `cloud_location` = '') AND `type`=? AND `platform` = ?"; $params = [$envId, $cloudLocation, self::TYPE_GLOBAL, $platform]; if ($farmId == 0 || $farmId == NULL) { $sql .= ' AND `farm_id` IS NULL'; } else { $sql .= 'AND `farm_id` = ?'; $params[] = $farmId; } $sql .= ' LIMIT 1'; $info = $this->db->GetRow($sql, $params); if (!$info) { return false; } else { return parent::loadBy($info); } }
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')); } }
$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";
/** * @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 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; }
/** * {@inheritdoc} * @see Scalr_Model::save() */ public function save($forceInsert = false) { return parent::save($forceInsert); }
/** * {@inheritdoc} * @see Scalr_Model::save() */ public function save($forceInsert = false) { $ret = parent::save($forceInsert); if ($this->id && \Scalr::getContainer()->analytics->enabled) { \Scalr::getContainer()->analytics->tags->syncValue($this->accountId, \Scalr\Stats\CostAnalytics\Entity\TagEntity::TAG_ID_USER, $this->id, $this->fullname ?: $this->email); } return $ret; }
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); } }
/** * {@inheritdoc} * @see Scalr_Model::delete() */ public function delete($id = null) { if ($this->db->GetOne("SELECT COUNT(*) FROM farms WHERE env_id = ?", array($this->id))) { throw new Exception("Cannot remove environment. You need to remove all your farms first."); } if ($this->db->GetOne("SELECT COUNT(*) FROM client_environments WHERE client_id = ?", array($this->clientId)) < 2) { throw new Exception('At least one environment should be in account. You cannot remove the last one.'); } parent::delete(); try { $this->db->Execute("DELETE FROM client_environment_properties WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM apache_vhosts WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM autosnap_settings WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM bundle_tasks WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM dm_applications WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM dm_deployment_tasks WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM dm_sources WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM dns_zones WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM ec2_ebs WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM elastic_ips WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM farms WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM roles WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM servers WHERE env_id=?", array($this->id)); $this->db->Execute("DELETE FROM ssh_keys WHERE env_id=?", array($this->id)); $this->db->Execute('DELETE FROM `account_team_envs` WHERE env_id = ?', array($this->id)); $this->db->Execute('DELETE FROM `global_variables` WHERE env_id = ?', array($this->id)); } catch (Exception $e) { throw new Exception(sprintf(_("Cannot delete record. Error: %s"), $e->getMessage()), $e->getCode()); } }
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(); } }
/** * * @return Scalr_Account */ public static function init() { return parent::init(); }
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; } }
/** * * @return Scalr_Limits */ public static function init($className = null) { return parent::init(); }
public function delete() { parent::delete(); $this->clearPermissions(); $this->db->Execute('DELETE FROM `account_user_groups` WHERE group_id = ?', array($this->id)); }
function loadBy($info) { parent::loadBy($info); $this->settings = unserialize($this->settingsRaw); return $this; }