コード例 #1
0
ファイル: IdcfPlatformModule.php プロジェクト: scalr/scalr
 public function PutAccessData(\DBServer $DBServer, \Scalr_Messaging_Msg $message)
 {
     $put = false;
     $put |= $message instanceof \Scalr_Messaging_Msg_Rebundle;
     $put |= $message instanceof \Scalr_Messaging_Msg_BeforeHostUp;
     $put |= $message instanceof \Scalr_Messaging_Msg_HostInitResponse;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_PromoteToMaster;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_NewMasterUp;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_CreateDataBundle;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_CreateBackup;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_PromoteToMaster;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_CreateDataBundle;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_CreateBackup;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_NewMasterUp;
     if ($put) {
         $ccProps = $DBServer->GetEnvironmentObject()->keychain($DBServer->platform)->properties;
         $accessData = new \stdClass();
         $accessData->apiKey = $ccProps[CloudCredentialsProperty::CLOUDSTACK_API_KEY];
         $accessData->secretKey = $ccProps[CloudCredentialsProperty::CLOUDSTACK_SECRET_KEY];
         $apiUrl = $ccProps[CloudCredentialsProperty::CLOUDSTACK_API_URL];
         if ($apiUrl == 'https://apis.i.noahcloud.jp/portal/client/api') {
             $accessData->apiUrl = "https://api.noahcloud.jp/portal/client/api";
         } else {
             $accessData->apiUrl = $apiUrl;
         }
         $message->platformAccessData = $accessData;
     }
 }
コード例 #2
0
ファイル: FarmRoleStorage.php プロジェクト: rickb838/scalr
 public function setVolumes(\DBServer $server, $volumes)
 {
     $vlms = array();
     foreach ($volumes as $volume) {
         $vlms[$volume->scalrStorageId] = $volume;
     }
     foreach ($this->getConfigs() as $config) {
         if ($vlms[$config->id]) {
             $volume = new FarmRoleStorageDevice();
             if (!$volume->loadById($volume->id)) {
                 $volume->farmRoleId = $this->farmRole->ID;
                 $volume->storageConfigId = $config->id;
                 $volume->serverIndex = $server->index;
                 $volume->storageId = $vlms[$config->id]->id;
                 $volume->cloudLocation = $server->GetCloudLocation();
                 $volume->envId = $server->envId;
             }
             switch ($config->type) {
                 case FarmRoleStorageConfig::TYPE_RAID_EBS:
                     $volume->placement = $vlms[$config->id]->disks[0]->availZone;
                     break;
                 case FarmRoleStorageConfig::TYPE_EBS:
                     $volume->placement = $vlms[$config->id]->availZone;
                     break;
             }
             $volume->config = $vlms[$config->id];
             $volume->status = FarmRoleStorageDevice::STATUS_ACTIVE;
             $volume->save();
             unset($vlms[$config->id]);
         }
     }
     //TODO: Handle zombies
 }
コード例 #3
0
ファイル: RackspaceNgUs.php プロジェクト: recipe/scalr
 public function GetServerIPAddresses(DBServer $DBServer)
 {
     $client = $this->getOsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
     $result = $client->servers->getServerDetails($DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID));
     if ($result->accessIPv4) {
         $remoteIp = $result->accessIPv4;
     }
     if (!$remoteIp) {
         if (is_array($result->addresses->public)) {
             foreach ($result->addresses->public as $addr) {
                 if ($addr->version == 4) {
                     $remoteIp = $addr->addr;
                     break;
                 }
             }
         }
     }
     if (is_array($result->addresses->private)) {
         foreach ($result->addresses->private as $addr) {
             if ($addr->version == 4) {
                 $localIp = $addr->addr;
                 break;
             }
         }
     }
     if (!$localIp) {
         $localIp = $remoteIp;
     }
     return array('localIp' => $localIp, 'remoteIp' => $remoteIp);
 }
コード例 #4
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\Platforms\Openstack\OpenstackPlatformModule::GetServerIPAddresses()
  */
 public function GetServerIPAddresses(\DBServer $DBServer)
 {
     $config = \Scalr::getContainer()->config;
     $client = $this->getOsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
     $result = $client->servers->getServerDetails($DBServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::SERVER_ID));
     $publicNetworkName = 'public';
     $privateNetworkName = 'private';
     if (is_array($result->addresses->{$publicNetworkName})) {
         foreach ($result->addresses->{$publicNetworkName} as $addr) {
             if ($addr->version == 4) {
                 $remoteIp = $addr->addr;
                 break;
             }
         }
     }
     if (!$remoteIp && $result->accessIPv4) {
         $remoteIp = $result->accessIPv4;
     }
     if (is_array($result->addresses->{$privateNetworkName})) {
         foreach ($result->addresses->{$privateNetworkName} as $addr) {
             if ($addr->version == 4) {
                 $localIp = $addr->addr;
                 break;
             }
         }
     }
     if (!$localIp) {
         $localIp = $remoteIp;
     }
     return array('localIp' => $localIp, 'remoteIp' => $remoteIp);
 }
コード例 #5
0
 public function PutAccessData(\DBServer $DBServer, \Scalr_Messaging_Msg $message)
 {
     $put = false;
     $put |= $message instanceof \Scalr_Messaging_Msg_Rebundle;
     $put |= $message instanceof \Scalr_Messaging_Msg_BeforeHostUp;
     $put |= $message instanceof \Scalr_Messaging_Msg_HostInitResponse;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_PromoteToMaster;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_NewMasterUp;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_CreateDataBundle;
     $put |= $message instanceof \Scalr_Messaging_Msg_Mysql_CreateBackup;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_PromoteToMaster;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_CreateDataBundle;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_CreateBackup;
     $put |= $message instanceof \Scalr_Messaging_Msg_DbMsr_NewMasterUp;
     if ($put) {
         $environment = $DBServer->GetEnvironmentObject();
         $accessData = new \stdClass();
         $accessData->apiKey = $this->getConfigVariable(self::API_KEY, $environment);
         $accessData->secretKey = $this->getConfigVariable(self::SECRET_KEY, $environment);
         $apiUrl = $this->getConfigVariable(self::API_URL, $environment);
         if ($apiUrl == 'https://apis.i.noahcloud.jp/portal/client/api') {
             $accessData->apiUrl = "https://api.noahcloud.jp/portal/client/api";
         } else {
             $accessData->apiUrl = $apiUrl;
         }
         $message->platformAccessData = $accessData;
     }
 }
コード例 #6
0
ファイル: Info.php プロジェクト: rakesh-mohanta/scalr
 public function __construct(DBFarmRole $dbFarmRole, DBServer $dbServer, $type)
 {
     $this->dbFarmRole = $dbFarmRole;
     $this->dbServer = $dbServer;
     $this->logger = Logger::getLogger(__CLASS__);
     $this->replicationMaster = (int) $dbServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER);
     $this->buildStorageSettings();
 }
コード例 #7
0
 public function ResumeServer(\DBServer $DBServer)
 {
     if ($this->getResumeStrategy() == \Scalr_Role_Behavior::RESUME_STRATEGY_INIT) {
         $DBServer->status = \SERVER_STATUS::PENDING;
     }
     $DBServer->SetProperty(\SERVER_PROPERTIES::RESUMING, 1);
     $DBServer->dateAdded = date("Y-m-d H:i:s");
     $DBServer->Save();
 }
コード例 #8
0
ファイル: uCloud.php プロジェクト: recipe/scalr
 public function TerminateServer(DBServer $DBServer)
 {
     $cs = $this->getCloudStackClient($DBServer->GetEnvironmentObject(), $this->GetServerCloudLocation($DBServer));
     if (!$DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::IS_STOPPED_BEFORE_TERMINATE)) {
         $cs->stopVirtualMachine($DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID), true);
         $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::IS_STOPPED_BEFORE_TERMINATE, 1);
     }
     return parent::TerminateServer($DBServer);
 }
コード例 #9
0
ファイル: RabbitMQ.php プロジェクト: recipe/scalr
 public function getConfiguration(DBServer $dbServer)
 {
     $config = new stdClass();
     $config->cookie = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_COOKIE_NAME);
     $config->volumeConfig = $this->getVolumeConfig($dbServer->GetFarmRoleObject(), $dbServer);
     $config->nodeType = $this->getNodeType($dbServer->GetFarmRoleObject(), $dbServer);
     $config->password = $dbServer->GetFarmRoleObject()->GetSetting(self::ROLE_PASSWORD);
     $dbServer->SetProperty(self::SERVER_NODE_TYPE, $config->nodeType);
     return $config;
 }
コード例 #10
0
 public function __construct(DBServer $DBServer, $reasonId = 0, $reasonMsg = "")
 {
     parent::__construct();
     $this->DBServer = $DBServer;
     try {
         $history = $this->DBServer->getServerHistory();
         $this->launchReasonId = $history->launchReasonId;
         $this->launchReason = $history->launchReason;
     } catch (Exception $e) {
     }
 }
コード例 #11
0
ファイル: class.HostDownEvent.php プロジェクト: mheydt/scalr
 public function __construct(DBServer $DBServer)
 {
     parent::__construct();
     $this->DBServer = $DBServer;
     try {
         $history = $this->DBServer->getServerHistory();
         $this->terminationReasonId = $history->terminateReasonId;
         $this->terminationReason = $history->terminateReason;
     } catch (Exception $e) {
     }
 }
コード例 #12
0
 public static function removeIpFromServer(\DBServer $dbServer)
 {
     try {
         if ($dbServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::FLOATING_IP)) {
             if ($dbServer->farmRoleId) {
                 if ($dbServer->GetFarmRoleObject()->GetSetting(\DBFarmRole::SETTING_OPENSTACK_KEEP_FIP_ON_SUSPEND)) {
                     if (in_array($dbServer->status, array(\SERVER_STATUS::PENDING_SUSPEND, \SERVER_STATUS::SUSPENDED)) || $dbServer->GetRealStatus()->isSuspended()) {
                         return false;
                     }
                 }
             }
             $environment = $dbServer->GetEnvironmentObject();
             $osClient = $environment->openstack($dbServer->platform, $dbServer->GetCloudLocation());
             $ipId = $dbServer->GetProperty(\OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID);
             if ($osClient->hasService('network')) {
                 $osClient->network->floatingIps->delete($ipId);
             } else {
                 $osClient->servers->deleteFloatingIp($ipId);
             }
             $dbServer->SetProperties(array(\OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => null, \OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => null));
         }
     } catch (\Exception $e) {
         \Logger::getLogger("OpenStackObserver")->fatal("OpenStackObserver observer failed: " . $e->getMessage());
     }
 }
コード例 #13
0
 public function __construct(DBServer $DBServer, $suspend = false)
 {
     parent::__construct();
     $this->DBServer = $DBServer;
     $this->suspend = $suspend;
     if (!$this->suspend) {
         try {
             $history = $this->DBServer->getServerHistory();
             $this->terminationReasonId = $history->terminateReasonId;
             $this->terminationReason = $history->terminateReason;
         } catch (Exception $e) {
         }
     }
 }
コード例 #14
0
ファイル: AzureHelper.php プロジェクト: scalr/scalr
 public static function setupScalrAgent(\DBServer $dbServer)
 {
     $baseurl = \Scalr::config('scalr.endpoint.scheme') . "://" . \Scalr::config('scalr.endpoint.host');
     $env = $dbServer->GetEnvironmentObject();
     $azure = $env->azure();
     $branch = $dbServer->getScalarizrRepository()['repository'];
     $develRepos = \Scalr::getContainer()->config->get('scalr.scalarizr_update.devel_repos');
     $scmBranch = $dbServer->GetFarmRoleObject()->GetSetting('user-data.scm_branch');
     if ($scmBranch != '' && $develRepos) {
         $branch = $dbServer->GetFarmRoleObject()->GetSetting('base.devel_repository');
         $scmBranch = "{$scmBranch}/";
     } else {
         $scmBranch = '';
     }
     if ($dbServer->osType == 'linux') {
         $extensionProperties = new ResourceExtensionProperties('Microsoft.OSTCExtensions', 'CustomScriptForLinux', '1.2');
         $extensionProperties->setSettings(['commandToExecute' => "bash -c 'curl -k -L \"{$baseurl}/public/linux/{$branch}/azure/{$scmBranch}install_scalarizr.sh\" | bash && service scalr-upd-client start'"]);
     } else {
         $extensionProperties = new ResourceExtensionProperties('Microsoft.Compute', 'CustomScriptExtension', '1.4');
         $extensionProperties->setSettings(["commandToExecute" => "powershell -NoProfile -ExecutionPolicy Bypass -Command \"iex ((new-object net.webclient).DownloadString('{$baseurl}/public/windows/{$branch}/{$scmBranch}install_scalarizr.ps1')); start-service ScalrUpdClient\""]);
     }
     $createExtension = new CreateResourceExtension('scalarizr', $dbServer->cloudLocation, $extensionProperties);
     try {
         $response = $azure->compute->resourceExtension->create($env->keychain(SERVER_PLATFORMS::AZURE)->properties[Entity\CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID], $dbServer->GetProperty(\AZURE_SERVER_PROPERTIES::RESOURCE_GROUP), $dbServer->GetProperty(\AZURE_SERVER_PROPERTIES::SERVER_NAME), $createExtension);
         \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->info(new \FarmLogMessage($dbServer, sprintf(_("Created azure resource extension to install and launch scalr agent"))));
         $dbServer->SetProperty(\AZURE_SERVER_PROPERTIES::SZR_EXTENSION_DEPLOYED, 1);
     } catch (\Exception $e) {
         \Scalr::getContainer()->logger(\LOG_CATEGORY::FARM)->fatal(new \FarmLogMessage($dbServer, sprintf(_("Unable to create azure resource extension to install and launch scalr agent: %s"), $e->getMessage())));
     }
 }
コード例 #15
0
 public function __construct(DBServer $DBServer)
 {
     parent::__construct();
     $this->DBServer = $DBServer;
     $r_server = \Scalr::getDb()->GetRow("SELECT server_id FROM servers WHERE replace_server_id=? LIMIT 1", array($DBServer->serverId));
     if ($r_server) {
         $this->replacementDBServer = DBServer::LoadByID($r_server['server_id']);
     }
     try {
         $history = $this->DBServer->getServerHistory();
         $this->terminationReasonId = $history->terminateReasonId;
         $this->terminationReason = $history->terminateReason;
     } catch (Exception $e) {
     }
 }
コード例 #16
0
ファイル: Bundletasks.php プロジェクト: rickb838/scalr
 public function xListTasksAction()
 {
     $this->request->defineParams(array('bundleTaskId' => array('type' => 'int'), 'sort' => array('type' => 'json', 'default' => array('property' => 'id', 'direction' => 'DESC'))));
     $sql = "SELECT * FROM bundle_tasks WHERE env_id = ?";
     $args = array($this->getEnvironmentId());
     if ($this->getParam('id') > 0) {
         $sql .= " AND id = ?";
         $args[] = $this->getParam('bundleTaskId');
     }
     $response = $this->buildResponseFromSql2($sql, array('id', 'server_id', 'rolename', 'status', 'os_family', 'dtadded', 'dtstarted', 'created_by_email'), array(), $args);
     foreach ($response["data"] as &$row) {
         $row['server_exists'] = DBServer::IsExists($row['server_id']);
         $row['dtadded'] = Scalr_Util_DateTime::convertTz($row['dtadded']);
         if (!$row['bundle_type']) {
             $row['bundle_type'] = "*";
         }
         if ($row['dtfinished'] && $row['dtstarted']) {
             $row['duration'] = Scalr_Util_DateTime::getDateTimeDiff($row['dtfinished'], $row['dtstarted']);
         }
         if ($row['dtfinished']) {
             $row['dtfinished'] = Scalr_Util_DateTime::convertTz($row['dtfinished']);
         }
         if ($row['dtstarted']) {
             $row['dtstarted'] = Scalr_Util_DateTime::convertTz($row['dtstarted']);
         }
     }
     $this->response->data($response);
 }
コード例 #17
0
ファイル: Volumes.php プロジェクト: recipe/scalr
 public function xListVolumesAction()
 {
     $this->request->defineParams(array('sort' => array('type' => 'json', 'default' => array('property' => 'volumeId', 'direction' => 'ASC')), 'volumeId'));
     $platformName = $this->getParam('platform');
     if (!$platformName) {
         throw new Exception("Cloud should be specified");
     }
     $client = $this->environment->openstack($platformName, $this->getParam('cloudLocation'));
     $volumes = $client->volume->listVolumes(true);
     $vols = array();
     foreach ($volumes as $pk => $pv) {
         if ($this->getParam('volumeId') && $this->getParam('volumeId') != $pv->id) {
             continue;
         }
         $item = array('volumeId' => $pv->id, 'size' => $pv->size, 'status' => $pv->status, 'attachmentStatus' => isset($pv->attachments[0]) ? 'attached' : 'available', 'device' => isset($pv->attachments[0]) ? $pv->attachments[0]->device : "", 'instanceId' => isset($pv->attachments[0]) ? $pv->attachments[0]->server_id : "", 'type' => $pv->volume_type, 'availability_zone' => $pv->availability_zone);
         if ($item['instanceId']) {
             try {
                 $dbServer = DBServer::LoadByPropertyValue(OPENSTACK_SERVER_PROPERTIES::SERVER_ID, $item['instanceId']);
                 $item['farmId'] = $dbServer->farmId;
                 $item['farmRoleId'] = $dbServer->farmRoleId;
                 $item['serverIndex'] = $dbServer->index;
                 $item['serverId'] = $dbServer->serverId;
                 $item['farmName'] = $dbServer->GetFarmObject()->Name;
                 $item['mountStatus'] = false;
                 $item['roleName'] = $dbServer->GetFarmRoleObject()->GetRoleObject()->name;
             } catch (Exception $e) {
             }
         }
         $vols[] = $item;
     }
     $response = $this->buildResponseFromData($vols, array('serverId', 'volumeId', 'farmId', 'farmRoleId'));
     $this->response->data($response);
 }
コード例 #18
0
ファイル: Snapshots.php プロジェクト: rickb838/scalr
 public function xCreateAction()
 {
     $this->request->defineParams(array('volumeId', 'cloudLocation'));
     $aws = $this->getEnvironment()->aws($this->getParam('cloudLocation'));
     $snapshot = $aws->ec2->snapshot->create($this->getParam('volumeId'));
     if (isset($snapshot->snapshotId)) {
         /* @var $volume \Scalr\Service\Aws\Ec2\DataType\VolumeData */
         $volume = $aws->ec2->volume->describe($snapshot->volumeId)->get(0);
         if (count($volume->attachmentSet) && !empty($volume->attachmentSet[0]->instanceId)) {
             $instanceId = $volume->attachmentSet[0]->instanceId;
             try {
                 $dBServer = DBServer::LoadByPropertyValue(EC2_SERVER_PROPERTIES::INSTANCE_ID, $instanceId);
                 $dBFarm = $dBServer->GetFarmObject();
             } catch (Exception $e) {
             }
             if (isset($dBServer) && isset($dBFarm)) {
                 $comment = sprintf(_("Created on farm '%s', server '%s' (Instance ID: %s)"), $dBFarm->Name, $dBServer->serverId, $instanceId);
             }
         } else {
             $comment = '';
         }
         $this->db->Execute("\n                INSERT INTO ebs_snaps_info\n                SET snapid = ?,\n                    comment = ?,\n                    dtcreated = NOW(),\n                    region = ?\n            ", array($snapshot->snapshotId, $comment, $this->getParam('cloudLocation')));
         $this->response->data(array('data' => array('snapshotId' => $snapshot->snapshotId)));
     } else {
         throw new Exception("Unable to create snapshot. Please try again later.");
     }
 }
コード例 #19
0
ファイル: Bundletasks.php プロジェクト: recipe/scalr
 public function xListTasksAction()
 {
     $this->request->defineParams(array('bundleTaskId' => array('type' => 'int'), 'sort' => array('type' => 'string', 'default' => 'id'), 'dir' => array('type' => 'string', 'default' => 'DESC')));
     $sql = "SELECT * FROM bundle_tasks WHERE env_id = '" . $this->getEnvironmentId() . "'";
     if ($this->getParam('id') > 0) {
         $sql .= " AND id = " . $this->db->qstr($this->getParam('bundleTaskId'));
     }
     $response = $this->buildResponseFromSql($sql, array("server_id", "rolename", "failure_reason", "snapshot_id", "id"));
     foreach ($response["data"] as &$row) {
         $row['server_exists'] = DBServer::IsExists($row['server_id']);
         $row['dtadded'] = Scalr_Util_DateTime::convertTz($row['dtadded']);
         if (!$row['bundle_type']) {
             $row['bundle_type'] = "*";
         }
         if ($row['dtfinished'] && $row['dtstarted']) {
             $row['duration'] = Scalr_Util_DateTime::getDateTimeDiff($row['dtfinished'], $row['dtstarted']);
         }
         if ($row['dtfinished']) {
             $row['dtfinished'] = Scalr_Util_DateTime::convertTz($row['dtfinished']);
         }
         if ($row['dtstarted']) {
             $row['dtstarted'] = Scalr_Util_DateTime::convertTz($row['dtstarted']);
         }
     }
     $this->response->data($response);
 }
コード例 #20
0
ファイル: Tasks.php プロジェクト: mheydt/scalr
 public function xListTasksAction()
 {
     $this->request->defineParams(array('sort' => array('type' => 'json', 'default' => array('property' => 'dtadded', 'direction' => 'DESC'))));
     $sql = "\n            SELECT\n                dt.id, dma.name AS application_name, servers.index AS server_index, farms.name AS farm_name, roles.name AS role_name,\n                dt.status AS status, dt.dtadded AS dtadded\n            FROM dm_deployment_tasks dt\n            LEFT JOIN dm_applications dma ON dt.dm_application_id = dma.id\n            LEFT JOIN servers ON servers.id = dt.server_id\n            LEFT JOIN farms ON servers.farm_id = farms.id\n            LEFT JOIN roles ON servers.farm_roleid = roles.id\n            WHERE dt.`status` != ? AND dt.env_id = ?\n        ";
     $args = array(Scalr_Dm_DeploymentTask::STATUS_ARCHIVED, $this->getEnvironmentId());
     list($sql, $args) = $this->request->prepareFarmSqlQuery($sql, $args, 'farms');
     $response = $this->buildResponseFromSql2($sql, array('id', 'application_name', 'farm_name', 'role_name', 'server_index', 'status', 'dtadded', 'dtdeployed'), array(), $args);
     foreach ($response["data"] as $k => $row) {
         $data = false;
         try {
             $deploymentTask = Scalr_Dm_DeploymentTask::init()->loadById($row['id']);
             $application = $deploymentTask->getApplication();
             try {
                 $dbServer = DBServer::LoadByID($deploymentTask->serverId);
                 $serverIndex = $dbServer->index;
             } catch (Exception $e) {
             }
             $data = array('id' => $deploymentTask->id, 'application_name' => $application->name, 'application_id' => $deploymentTask->applicationId, 'server_id' => $deploymentTask->serverId, 'server_index' => $serverIndex, 'remote_path' => $deploymentTask->remotePath, 'status' => $deploymentTask->status, 'dtadded' => $deploymentTask->dtAdded ? Scalr_Util_DateTime::convertTz($deploymentTask->dtAdded) : "", 'dtdeployed' => $deploymentTask->dtDeployed ? Scalr_Util_DateTime::convertTz($deploymentTask->dtDeployed) : "Never");
             try {
                 $dbFarmRole = DBFarmRole::LoadByID($deploymentTask->farmRoleId);
                 $data['farm_roleid'] = $dbFarmRole->ID;
                 $data['role_name'] = $dbFarmRole->GetRoleObject()->name;
                 $data['farm_id'] = $dbFarmRole->FarmID;
                 $data['farm_name'] = $dbFarmRole->GetFarmObject()->Name;
             } catch (Exception $e) {
             }
         } catch (Exception $e) {
         }
         $response["data"][$k] = $data;
     }
     $this->response->data($response);
 }
コード例 #21
0
ファイル: Logs.php プロジェクト: recipe/scalr
 public function getScriptingLogAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_LOGS_SCRIPTING_LOGS);
     $this->request->defineParams(array('executionId' => array('type' => 'string')));
     $info = $this->db->GetRow("SELECT * FROM scripting_log WHERE execution_id = ? LIMIT 1", array($this->getParam('executionId')));
     if (!$info) {
         throw new Exception('Script execution log not found');
     }
     try {
         $dbServer = DBServer::LoadByID($info['server_id']);
         if (!in_array($dbServer->status, array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING))) {
             throw new Exception();
         }
     } catch (Exception $e) {
         throw new Exception('Server was terminated and logs no longer available');
     }
     //Note! We should not check not-owned-farms permission here. It's approved by Igor.
     if ($dbServer->envId != $this->environment->id) {
         throw new \Scalr_Exception_InsufficientPermissions();
     }
     $client = Scalr_Net_Scalarizr_Client::getClient($dbServer, Scalr_Net_Scalarizr_Client::NAMESPACE_SYSTEM, $dbServer->getPort(DBServer::PORT_API));
     $logs = $client->getScriptLogs($this->getParam('executionId'));
     $msg = sprintf("STDERR: %s \n\n STDOUT: %s", base64_decode($logs->stderr), base64_decode($logs->stdout));
     $msg = nl2br(htmlspecialchars($msg));
     $this->response->data(array('message' => $msg));
 }
コード例 #22
0
ファイル: Volumes.php プロジェクト: rakesh-mohanta/scalr
 public function xListVolumesAction()
 {
     $this->request->defineParams(array('sort' => array('type' => 'json', 'default' => array('property' => 'volumeId', 'direction' => 'ASC')), 'volumeId'));
     $csClient = Scalr_Service_Cloud_Cloudstack::newCloudstack($this->environment->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_URL), $this->environment->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_KEY), $this->environment->getPlatformConfigValue(Modules_Platforms_Cloudstack::SECRET_KEY));
     $volumes = $csClient->listVolumes($this->getParam('cloudLocation'));
     $vols = array();
     foreach ($volumes as $pk => $pv) {
         if ($this->getParam('volumeId') && $this->getParam('volumeId') != $pv->id) {
             continue;
         }
         $item = array('volumeId' => $pv->id, 'size' => round($pv->size / 1024 / 1024 / 1024, 2), 'status' => $pv->state, 'attachmentStatus' => $pv->virtualmachineid ? 'attached' : 'available', 'device' => $pv->deviceid, 'instanceId' => $pv->virtualmachineid, 'type' => $pv->type . " ({$pv->storagetype})", 'storage' => $pv->storage);
         $item['autoSnaps'] = $this->db->GetOne("SELECT id FROM autosnap_settings WHERE objectid=? AND object_type=?", array($pv->id, AUTOSNAPSHOT_TYPE::CSVOL)) ? true : false;
         if ($item['instanceId']) {
             try {
                 $dbServer = DBServer::LoadByPropertyValue(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID, $item['instanceId']);
                 $item['farmId'] = $dbServer->farmId;
                 $item['farmRoleId'] = $dbServer->farmRoleId;
                 $item['serverIndex'] = $dbServer->index;
                 $item['serverId'] = $dbServer->serverId;
                 $item['farmName'] = $dbServer->GetFarmObject()->Name;
                 $item['mountStatus'] = false;
                 $item['roleName'] = $dbServer->GetFarmRoleObject()->GetRoleObject()->name;
             } catch (Exception $e) {
             }
         }
         $vols[] = $item;
     }
     $response = $this->buildResponseFromData($vols, array('serverId', 'volumeId', 'farmId', 'farmRoleId', 'storage'));
     $this->response->data($response);
 }
コード例 #23
0
 public function ServerGetExtendedInformation($ServerID)
 {
     $DBServer = DBServer::LoadByID($ServerID);
     if ($DBServer->envId != $this->Environment->id) {
         throw new Exception(sprintf("Server ID #%s not found", $ServerID));
     }
     $response = $this->CreateInitialResponse();
     $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerExtendedInformation($DBServer);
     $response->ServerInfo = new stdClass();
     $scalrProps = array('ServerID' => $DBServer->serverId, 'Platform' => $DBServer->platform, 'RemoteIP' => $DBServer->remoteIp ? $DBServer->remoteIp : '', 'LocalIP' => $DBServer->localIp ? $DBServer->localIp : '', 'Status' => $DBServer->status, 'Index' => $DBServer->index, 'AddedAt' => $DBServer->dateAdded);
     foreach ($scalrProps as $k => $v) {
         $response->ServerInfo->{$k} = $v;
     }
     $response->PlatformProperties = new stdClass();
     if (is_array($info) && count($info)) {
         foreach ($info as $name => $value) {
             $name = str_replace(".", "_", $name);
             $name = preg_replace("/[^A-Za-z0-9_-]+/", "", $name);
             if ($name == 'MonitoringCloudWatch') {
                 continue;
             }
             $response->PlatformProperties->{$name} = $value;
         }
     }
     $response->ScalrProperties = new stdClass();
     if (count($DBServer->GetAllProperties())) {
         $it = array();
         foreach ($DBServer->GetAllProperties() as $name => $value) {
             $name = preg_replace("/[^A-Za-z0-9-]+/", "", $name);
             $response->ScalrProperties->{$name} = $value;
         }
     }
     return $response;
 }
コード例 #24
0
 private function sendNewDbMsrMasterUpMessage(DBServer $newMasterServer)
 {
     $dbFarmRole = $newMasterServer->GetFarmRoleObject();
     $servers = $dbFarmRole->GetServersByFilter(array('status' => array(SERVER_STATUS::INIT, SERVER_STATUS::RUNNING)));
     $dbType = $newMasterServer->GetFarmRoleObject()->GetRoleObject()->getDbMsrBehavior();
     $props = Scalr_Db_Msr_Info::init($dbFarmRole, $newMasterServer, $dbType)->getMessageProperties();
     foreach ($servers as $dbServer) {
         $msg = new Scalr_Messaging_Msg_DbMsr_NewMasterUp($dbFarmRole->GetRoleObject()->getBehaviors(), $dbFarmRole->GetRoleObject()->name, $newMasterServer->localIp, $newMasterServer->remoteIp, $dbType);
         $msg->{$dbType} = new stdClass();
         $msg->{$dbType}->snapshotConfig = $props->snapshotConfig;
         foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
             $msg = $behavior->extendMessage($msg, $dbServer);
         }
         $dbServer->SendMessage($msg);
     }
 }
コード例 #25
0
 public static function doJob($job)
 {
     $db = Core::GetDBInstance(null, true);
     $messageSerializer = new Scalr_Messaging_XmlSerializer();
     $message = $db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($job->workload()));
     try {
         if ($message['handle_attempts'] >= 3) {
             $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
         } else {
             try {
                 $DBServer = DBServer::LoadByID($message['server_id']);
             } catch (Exception $e) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
                 return;
             }
             if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) {
                 // Only 0.2-68 or greater version support this feature.
                 if ($DBServer->IsSupported("0.2-68")) {
                     $msg = $messageSerializer->unserialize($message['message']);
                     $DBServer->SendMessage($msg);
                 } else {
                     $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::UNSUPPORTED, $message['id']));
                 }
             } elseif (in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) {
                 $db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
             }
         }
     } catch (Exception $e) {
         //var_dump($e->getMessage());
     }
 }
コード例 #26
0
ファイル: Update20141029152128.php プロジェクト: mheydt/scalr
 protected function run4()
 {
     $this->console->notice('Fill image_id in servers table');
     // ec2
     $this->db->Execute("\n            UPDATE servers s JOIN server_properties sp ON s.server_id = sp.server_id\n            SET s.image_id = sp.value\n            WHERE sp.name = ? AND s.platform = ?\n        ", [\EC2_SERVER_PROPERTIES::AMIID, \SERVER_PLATFORMS::EC2]);
     // rackspace
     $this->db->Execute("\n            UPDATE servers s JOIN server_properties sp ON s.server_id = sp.server_id\n            SET s.image_id = sp.value\n            WHERE sp.name = ? AND s.platform = ?\n        ", [\RACKSPACE_SERVER_PROPERTIES::IMAGE_ID, \SERVER_PLATFORMS::RACKSPACE]);
     //cloudstack
     foreach (PlatformFactory::getCloudstackBasedPlatforms() as $platform) {
         foreach ($this->db->GetCol('SELECT server_id FROM servers WHERE platform = ?', [$platform]) as $serverId) {
             try {
                 $dbServer = \DBServer::LoadByID($serverId);
                 $env = (new \Scalr_Environment())->loadById($dbServer->envId);
                 if ($dbServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                     $lst = $env->cloudstack($platform)->instance->describe(['id' => $dbServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID)]);
                     if ($lst && $lst->count() == 1) {
                         $instance = $lst->offsetGet(0);
                         $dbServer->imageId = $instance->templateid;
                         $this->console->notice('Set imageId: %s for serverId: %s', $dbServer->imageId, $serverId);
                         $dbServer->save();
                     } else {
                         $this->console->warning('Instance not found: %s for serverId: %s', $dbServer->GetProperty(\CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID), $serverId);
                     }
                 }
             } catch (\Exception $e) {
                 $this->console->warning($e->getMessage());
             }
         }
     }
     // openstack
     foreach (PlatformFactory::getOpenstackBasedPlatforms() as $platform) {
         $this->db->Execute("\n                UPDATE servers s LEFT JOIN server_properties sp ON s.server_id = sp.server_id\n                SET s.image_id = sp.value\n                WHERE sp.name = ? AND s.platform = ?\n            ", [\OPENSTACK_SERVER_PROPERTIES::IMAGE_ID, $platform]);
     }
 }
コード例 #27
0
ファイル: Billing.php プロジェクト: rakesh-mohanta/scalr
 public function xGetDetailsAction()
 {
     $amazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($this->getParam('cloudLocation'), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE));
     $rInstances = $amazonEC2Client->DescribeReservedInstances();
     $rInstances = $rInstances->reservedInstancesSet->item;
     if ($rInstances instanceof stdClass) {
         $rInstances = array($rInstances);
     }
     $result = array();
     foreach ($rInstances as $rInstance) {
         if ($rInstance->state == 'active') {
             $result[$rInstance->availabilityZone][$rInstance->instanceType]['rCount'] += $rInstance->instanceCount;
         }
     }
     $servers = $this->db->Execute("SELECT servers.server_id FROM `servers` INNER JOIN server_properties ON server_properties.server_id = servers.server_id \r\n\t\t\tWHERE status=? AND name='ec2.region' AND env_id=? AND value=?", array(SERVER_STATUS::RUNNING, $this->getEnvironmentId(), $this->getParam('cloudLocation')));
     while ($server = $servers->FetchRow()) {
         $dbServer = DBServer::LoadByID($server['server_id']);
         $result[$dbServer->GetProperty(EC2_SERVER_PROPERTIES::AVAIL_ZONE)][$dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_TYPE)]['iCount']++;
     }
     $retval = array();
     foreach ($result as $availZone => $i) {
         foreach ($i as $instanceType => $data) {
             $retval[] = array('availZone' => $availZone, 'instanceType' => $instanceType, 'scalrInstances' => (int) $data['iCount'], 'reservedInstances' => (int) $data['rCount']);
         }
     }
     $this->response->data(array('success' => true, 'data' => $retval));
 }
コード例 #28
0
 /**
  * Performs upgrade literally for the stage ONE.
  *
  * Implementation of this method performs update steps needs to be taken
  * to accomplish upgrade successfully.
  *
  * If there are any error during an execution of this scenario it must
  * throw an exception.
  *
  * @param   int  $stage  optional The stage number
  * @throws  \Exception
  */
 protected function run1($stage)
 {
     if (!$this->hasTableColumn('servers', 'cloud_location')) {
         $this->db->Execute("ALTER TABLE `servers`\n                    ADD `cloud_location` VARCHAR(255) NULL AFTER `index`,\n                    ADD `cloud_location_zone` VARCHAR(255) NULL AFTER `cloud_location`\n            ");
     } else {
         if (!$this->hasTableColumnType('servers', 'cloud_location', 'varchar(255)')) {
             $this->db->Execute("ALTER TABLE `servers`\n                    CHANGE `cloud_location` `cloud_location` VARCHAR(255) NULL,\n                    CHANGE `cloud_location_zone` `cloud_location_zone` VARCHAR(255) NULL\n            ");
         }
     }
     $servers = $this->db->Execute("SELECT server_id FROM servers");
     while ($server = $servers->FetchRow()) {
         try {
             $dbServer = \DBServer::LoadByID($server['server_id']);
             $dbServer->cloudLocation = $dbServer->GetCloudLocation();
             if ($dbServer->platform == \SERVER_PLATFORMS::EC2) {
                 $dbServer->cloudLocationZone = $dbServer->GetProperty(\EC2_SERVER_PROPERTIES::AVAIL_ZONE);
             }
             if ($dbServer->platform == \SERVER_PLATFORMS::EUCALYPTUS) {
                 $dbServer->cloudLocationZone = $dbServer->GetProperty(\EUCA_SERVER_PROPERTIES::AVAIL_ZONE);
             }
             if ($dbServer->platform == \SERVER_PLATFORMS::GCE) {
                 $dbServer->cloudLocationZone = $dbServer->GetProperty(\GCE_SERVER_PROPERTIES::CLOUD_LOCATION);
             }
             $dbServer->Save();
         } catch (\Exception $e) {
         }
     }
 }
コード例 #29
0
ファイル: MessagingQueue.php プロジェクト: rickb838/scalr
 function handleWork($msgId)
 {
     $message = $this->db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($msgId));
     try {
         if ($message['handle_attempts'] >= 3) {
             $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
         } else {
             try {
                 $DBServer = DBServer::LoadByID($message['server_id']);
             } catch (Exception $e) {
                 $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
                 return;
             }
             if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) {
                 $msg = $this->messageSerializer->unserialize($message['message']);
                 $msg->dbMessageId = $message['id'];
                 $DBServer->SendMessage($msg);
             } elseif (in_array($DBServer->status, array(SERVER_STATUS::TROUBLESHOOTING, SERVER_STATUS::TERMINATED, SERVER_STATUS::SUSPENDED))) {
                 $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id']));
             }
         }
     } catch (Exception $e) {
         //var_dump($e->getMessage());
     }
 }
コード例 #30
0
ファイル: Snapshots.php プロジェクト: rakesh-mohanta/scalr
 public function xCreateAction()
 {
     $this->request->defineParams(array('volumeId', 'cloudLocation'));
     $amazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($this->getParam('cloudLocation'), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE));
     $res = $amazonEC2Client->CreateSnapshot($this->getParam('volumeId'));
     if ($res->snapshotId) {
         $r = $amazonEC2Client->DescribeVolumes($res->volumeId);
         $info = $r->volumeSet->item;
         if ($info->attachmentSet->item->instanceId) {
             try {
                 $dBServer = DBServer::LoadByPropertyValue(EC2_SERVER_PROPERTIES::INSTANCE_ID, (string) $info->attachmentSet->item->instanceId);
                 $dBFarm = $dBServer->GetFarmObject();
             } catch (Exception $e) {
             }
             if ($dBServer && $dBFarm) {
                 $comment = sprintf(_("Created on farm '%s', server '%s' (Instance ID: %s)"), $dBFarm->Name, $dBServer->serverId, (string) $info->attachmentSet->item->instanceId);
             }
         } else {
             $comment = "";
         }
         $this->db->Execute("INSERT INTO ebs_snaps_info SET snapid=?, comment=?, dtcreated=NOW(), region=?", array($res->snapshotId, $comment, $this->getParam('cloudLocation')));
         $this->response->data(array('data' => array('snapshotId' => $res->snapshotId)));
     } else {
         throw new Exception("Scalr unable to create snapshot. Please try again later.");
     }
 }