Пример #1
0
 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);
 }
Пример #2
0
 public function xGetOfferingsListAction()
 {
     $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_URL), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_KEY), $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Cloudstack::SECRET_KEY));
     $data = array();
     foreach ($cs->listServiceOfferings() as $offering) {
         $data['serviceOfferings'][] = array('id' => $offering->id, 'name' => $offering->displaytext);
     }
     $accountName = $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Cloudstack::ACCOUNT_NAME, false);
     $domainId = $this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Cloudstack::DOMAIN_ID, false);
     foreach ($cs->listNetworks("", $accountName, $domainId) as $network) {
         $data['networks'][] = array('id' => $network->id, 'name' => "{$network->id}: {$network->name} ({$network->networkdomain})");
     }
     $this->response->data(array('data' => $data));
 }
Пример #3
0
 public function getLocations()
 {
     try {
         $environment = Scalr_UI_Request::getInstance()->getEnvironment();
         if ($environment && $environment->isPlatformEnabled($this->platform)) {
             $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($this->getConfigVariable(self::API_URL, $environment), $this->getConfigVariable(self::API_KEY, $environment), $this->getConfigVariable(self::SECRET_KEY, $environment), $this->platform);
             $retval = array();
             foreach ($cs->listZones() as $zone) {
                 $retval[$zone->name] = strtoupper($this->platform) . " / {$zone->name}";
             }
             return $retval;
         }
     } catch (Exception $e) {
     }
     return array("jp-east-t1v" => "IDCF / jp-east-t1v", "jp-east-f2v" => "IDCF / jp-east-f2v");
 }
Пример #4
0
 public function xListIpsAction()
 {
     $this->request->defineParams(array('sort' => array('type' => 'json', 'default' => array('property' => 'ipId', 'direction' => 'ASC')), 'ipId'));
     $platformName = $this->getParam('platform');
     if (!$platformName) {
         throw new Exception("Cloud should be specified");
     }
     $platform = PlatformFactory::NewPlatform($platformName);
     $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $this->environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $this->environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $this->environment), $platformName);
     $accountName = $platform->getConfigVariable(Modules_Platforms_Cloudstack::ACCOUNT_NAME, $this->getEnvironment(), false);
     $domainId = $platform->getConfigVariable(Modules_Platforms_Cloudstack::DOMAIN_ID, $this->getEnvironment(), false);
     $ipAddresses = $cs->listPublicIpAddresses(null, $accountName, null, $domainId, null, null, null, null, null, null, $this->getParam('cloudLocation'));
     $systemIp = $platform->getConfigVariable(Modules_Platforms_Cloudstack::SHARED_IP . "." . $this->getParam('cloudLocation'), $this->environment);
     $ips = array();
     foreach ($ipAddresses->publicipaddress as $pk => $pv) {
         if ($this->getParam('ipId') && $this->getParam('ipId') != $pv->id) {
             continue;
         }
         if ($pv->ipaddress == $systemIp) {
             $pv->purpose = 'ScalrShared';
         }
         if ($pv->isstaticnat && !$pv->issystem) {
             $pv->purpose = 'ElasticIP';
         }
         if ($pv->isstaticnat && $pv->issystem) {
             $pv->purpose = 'PublicIP';
         }
         $item = array('ipId' => $pv->id, 'dtAllocated' => $pv->allocated, 'networkName' => $pv->associatednetworkname, 'purpose' => $pv->purpose ? $pv->purpose : "Not used", 'ip' => $pv->ipaddress, 'state' => $pv->state, 'instanceId' => $pv->virtualmachineid, 'fullinfo' => $pv, 'farmId' => 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['roleName'] = $dbServer->GetFarmRoleObject()->GetRoleObject()->name;
             } catch (Exception $e) {
             }
         }
         $ips[] = $item;
     }
     $response = $this->buildResponseFromData($ips, array('serverId', 'ipId', 'ip', 'farmId', 'farmRoleId'));
     $this->response->data($response);
 }
Пример #5
0
 public function getSnapshots($platformName, $snapshotId = null)
 {
     if (!$platformName) {
         throw new Exception("Cloud should be specified");
     }
     $platform = PlatformFactory::NewPlatform($platformName);
     $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $this->environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $this->environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $this->environment), $platformName);
     $snapshots = $cs->listSnapshots();
     $snaps = array();
     foreach ($snapshots as $pk => $pv) {
         if ($snapshotId && $snapshotId != $pv->id) {
             continue;
         }
         $item = array('snapshotId' => (string) $pv->id, 'type' => $pv->snapshottype, 'volumeId' => $pv->volumeid, 'volumeType' => $pv->volumetype, 'createdAt' => $pv->created, 'intervalType' => $pv->intervaltype, 'state' => $pv->state);
         $snaps[] = $item;
     }
     return $snaps;
 }
Пример #6
0
 public function getLocations()
 {
     try {
         $environment = Scalr_UI_Request::getInstance()->getEnvironment();
     } catch (Exception $e) {
         return array();
     }
     if (!$environment || !$environment->isPlatformEnabled($this->platform)) {
         return array();
     }
     try {
         $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($this->getConfigVariable(self::API_URL, $environment), $this->getConfigVariable(self::API_KEY, $environment), $this->getConfigVariable(self::SECRET_KEY, $environment), $this->platform);
         foreach ($cs->listZones() as $zone) {
             $retval[$zone->name] = ucfirst($this->platform) . " / {$zone->name}";
         }
     } catch (Exception $e) {
         return array();
     }
     return $retval;
 }
Пример #7
0
 public function getLocations()
 {
     try {
         $environment = Scalr_UI_Request::getInstance()->getEnvironment();
     } catch (Exception $e) {
         return array();
     }
     if (!$environment || !$environment->isPlatformEnabled(SERVER_PLATFORMS::CLOUDSTACK)) {
         return array();
     }
     try {
         $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($environment->getPlatformConfigValue(self::API_URL), $environment->getPlatformConfigValue(self::API_KEY), $environment->getPlatformConfigValue(self::SECRET_KEY));
         foreach ($cs->listZones() as $zone) {
             $retval[$zone->name] = "Cloudstack / {$zone->name}";
         }
     } catch (Exception $e) {
         return array();
     }
     return $retval;
 }
Пример #8
0
 public function getLocations()
 {
     try {
         $environment = Scalr_UI_Request::getInstance()->getEnvironment();
     } catch (Exception $e) {
         return array();
     }
     if (!$environment || !$environment->isPlatformEnabled($this->platform)) {
         return array();
     }
     try {
         $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($this->getConfigVariable(self::API_URL, $environment), $this->getConfigVariable(self::API_KEY, $environment), $this->getConfigVariable(self::SECRET_KEY, $environment), $this->platform);
         $products = $cs->listAvailableProductTypes();
         foreach ($products->producttypes as $product) {
             $retval[$product->zoneid] = "KT uCloud / {$product->zonedesc} ({$product->zoneid})";
         }
     } catch (Exception $e) {
         return array();
     }
     return $retval;
 }
Пример #9
0
 public static function farmSave(DBFarm $DBFarm, array $roles)
 {
     foreach ($roles as $DBFarmRole) {
         if ($DBFarmRole->Platform != SERVER_PLATFORMS::CLOUDSTACK) {
             continue;
         }
         $location = $DBFarmRole->CloudLocation;
         $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_URL), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_KEY), $DBFarm->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Cloudstack::SECRET_KEY));
         $sshKey = Scalr_SshKey::init();
         if (!$sshKey->loadGlobalByFarmId($DBFarm->ID, $location)) {
             $key_name = "FARM-{$DBFarm->ID}";
             $result = $cs->createSSHKeyPair($key_name);
             if ($result->keypair->privatekey) {
                 $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::CLOUDSTACK;
                 $sshKey->setPrivate($result->keypair->privatekey);
                 $sshKey->setPublic($sshKey->generatePublicKey());
                 $sshKey->save();
             }
         }
         $networkId = $DBFarmRole->GetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_ID);
         $set = fasle;
         foreach ($cs->listNetworks("", "", "", $networkId) as $network) {
             if ($network->id == $networkId) {
                 $DBFarmRole->SetSetting(DBFarmRole::SETTING_CLOUDSTACK_NETWORK_TYPE, $network->type);
                 $set = true;
             }
         }
         if (!$set) {
             throw new Exception("Unable to get GuestIPType for Network #{$networkId}. Please try again later or choose another network offering.");
         }
     }
 }
 public function StartThread($bundle_task_info)
 {
     $db = \Scalr::getDb();
     // Reconfigure observers;
     Scalr::ReconfigureObservers();
     $BundleTask = BundleTask::LoadById($bundle_task_info['id']);
     try {
         $DBServer = DBServer::LoadByID($BundleTask->serverId);
     } catch (\Scalr\Exception\ServerNotFoundException $e) {
         if (!$BundleTask->snapshotId) {
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::FAILED;
             $BundleTask->setDate('finished');
             $BundleTask->failureReason = sprintf(_("Server '%s' was terminated during snapshot creation process"), $BundleTask->serverId);
             $BundleTask->Save();
             return;
         }
     } catch (Exception $e) {
         //$this->Logger->error($e->getMessage());
     }
     switch ($BundleTask->status) {
         case SERVER_SNAPSHOT_CREATION_STATUS::ESTABLISHING_COMMUNICATION:
             $ctrlPort = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_CTRL_PORT);
             if (!$ctrlPort) {
                 $ctrlPort = 8013;
             }
             if (\Scalr::config('scalr.instances_connection_policy') == 'local') {
                 $requestHost = $DBServer->localIp;
             } elseif (\Scalr::config('scalr.instances_connection_policy') == 'public') {
                 $requestHost = $DBServer->remoteIp;
             } elseif (\Scalr::config('scalr.instances_connection_policy') == 'auto') {
                 if ($DBServer->remoteIp) {
                     $requestHost = $DBServer->remoteIp;
                 } else {
                     $requestHost = $DBServer->localIp;
                 }
             }
             $conn = @fsockopen($requestHost, $ctrlPort, $errno, $errstr, 10);
             if ($conn) {
                 $DBServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_OUT_CONNECTION, 1);
                 $BundleTask->Log("Outbound connection successfully established. Awaiting user action: prebuild automation selection");
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::AWAITING_USER_ACTION;
                 $BundleTask->Log(sprintf(_("Bundle task status: %s"), $BundleTask->status));
                 $BundleTask->Save();
             } else {
                 $errstr = sprintf("Unable to establish outbound (Scalr -> Scalarizr) communication (%s:%s): %s.", $requestHost, $ctrlPort, $errstr);
                 $errMsg = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_OUT_CONNECTION_ERROR);
                 if (!$errMsg || $errstr != $errMsg) {
                     $DBServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_OUT_CONNECTION_ERROR, $errstr);
                     $BundleTask->Log("{$errstr} Will try again in a few minutes.");
                 }
             }
             exit;
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::AWAITING_USER_ACTION:
             //NOTHING TO DO;
             exit;
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::STARING_SERVER:
             $BundleTask->setDate('started');
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV:
         case SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE:
             if (!PlatformFactory::NewPlatform($DBServer->platform)->GetServerID($DBServer)) {
                 $BundleTask->Log(sprintf(_("Waiting for temporary server")));
                 exit;
             }
             if (!PlatformFactory::NewPlatform($DBServer->platform)->IsServerExists($DBServer)) {
                 $DBServer->status = SERVER_STATUS::TERMINATED;
                 $DBServer->save();
                 $BundleTask->SnapshotCreationFailed("Server was terminated and no longer available in cloud.");
                 exit;
             }
             // IF server is in pensing state
             $status = PlatformFactory::NewPlatform($DBServer->platform)->GetServerRealStatus($DBServer);
             if ($status->isPending()) {
                 $BundleTask->Log(sprintf(_("Server status: %s"), $status->getName()));
                 $BundleTask->Log(sprintf(_("Waiting for running state."), $status->getName()));
                 exit;
             } elseif ($status->isTerminated()) {
                 $BundleTask->Log(sprintf(_("Server status: %s"), $status->getName()));
                 $DBServer->status = SERVER_STATUS::TERMINATED;
                 $DBServer->save();
                 $BundleTask->SnapshotCreationFailed("Server was terminated and no longer available in cloud.");
                 exit;
             }
             break;
     }
     switch ($BundleTask->status) {
         case SERVER_SNAPSHOT_CREATION_STATUS::STARING_SERVER:
             $ips = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
             $DBServer->remoteIp = $ips['remoteIp'];
             $DBServer->localIp = $ips['localIp'];
             $DBServer->save();
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV;
             $BundleTask->save();
             $BundleTask->Log(sprintf(_("Bundle task status: %s"), $BundleTask->status));
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV:
             $BundleTask->Log(sprintf(_("Initializing SSH2 session to the server")));
             if ($DBServer->platform == SERVER_PLATFORMS::IDCF && !$DBServer->remoteIp) {
                 try {
                     $BundleTask->Log("Creating port forwarding rules to be able to connect to the server by SSH");
                     $environment = $DBServer->GetEnvironmentObject();
                     $cloudLocation = $DBServer->GetCloudLocation();
                     $platform = PlatformFactory::NewPlatform($DBServer->platform);
                     $sharedIpId = $platform->getConfigVariable(Modules_Platforms_Cloudstack::SHARED_IP_ID . ".{$cloudLocation}", $environment, false);
                     $sharedIp = $platform->getConfigVariable(Modules_Platforms_Cloudstack::SHARED_IP . ".{$cloudLocation}", $environment, false);
                     $BundleTask->Log("Shared IP: {$sharedIp}");
                     $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $environment), $DBServer->platform);
                     // Create port forwarding rules for scalarizr
                     $port = $platform->getConfigVariable(Modules_Platforms_Cloudstack::SZR_PORT_COUNTER . ".{$cloudLocation}.{$sharedIpId}", $environment, false);
                     if (!$port) {
                         $port1 = 30000;
                         $port2 = 30001;
                         $port3 = 30002;
                         $port4 = 30003;
                     } else {
                         $port1 = $port + 1;
                         $port2 = $port1 + 1;
                         $port3 = $port2 + 1;
                         $port4 = $port3 + 1;
                     }
                     $result2 = $cs->createPortForwardingRule($sharedIpId, 8014, "udp", $port1, $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID));
                     $result1 = $cs->createPortForwardingRule($sharedIpId, 8013, "tcp", $port1, $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID));
                     $result3 = $cs->createPortForwardingRule($sharedIpId, 8010, "tcp", $port3, $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID));
                     $result4 = $cs->createPortForwardingRule($sharedIpId, 8008, "tcp", $port2, $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID));
                     $result5 = $cs->createPortForwardingRule($sharedIpId, 22, "tcp", $port4, $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID));
                     $DBServer->SetProperties(array(SERVER_PROPERTIES::SZR_CTRL_PORT => $port1, SERVER_PROPERTIES::SZR_SNMP_PORT => $port1, SERVER_PROPERTIES::SZR_API_PORT => $port3, SERVER_PROPERTIES::SZR_UPDC_PORT => $port2, SERVER_PROPERTIES::CUSTOM_SSH_PORT => $port4));
                     $DBServer->remoteIp = $sharedIp;
                     $DBServer->Save();
                     $platform->setConfigVariable(array(Modules_Platforms_Cloudstack::SZR_PORT_COUNTER . ".{$cloudLocation}.{$sharedIpId}" => $port4), $environment, false);
                 } catch (Exception $e) {
                     $BundleTask->Log("Unable to create port-forwarding rules: {$e->getMessage()}");
                 }
                 exit;
             }
             if ($DBServer->platform == SERVER_PLATFORMS::ECS && !$DBServer->remoteIp) {
                 $BundleTask->Log(sprintf(_("Server doesn't have public IP. Assigning...")));
                 $osClient = $DBServer->GetEnvironmentObject()->openstack($DBServer->platform, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
                 $ports = $osClient->network->ports->list();
                 foreach ($ports as $port) {
                     if ($port->device_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                         $serverNetworkPort = $port->id;
                         break;
                     }
                 }
                 $ips = $osClient->network->floatingIps->list();
                 //Check free existing IP
                 $ipAssigned = false;
                 $ipAddress = false;
                 $ipId = false;
                 $ipInfo = false;
                 foreach ($ips as $ip) {
                     if ($ip->port_id && $ip->port_id == $serverNetworkPort) {
                         $ipAddress = $ip->floating_ip_address;
                         $ipId = $ip->id;
                         $ipAssigned = true;
                         $ipInfo = $ip;
                         break;
                     }
                     if (!$ip->fixed_ip_address && !$ipAddress) {
                         $ipAddress = $ip->floating_ip_address;
                         $ipId = $ip->id;
                         $ipInfo = $ip;
                     }
                 }
                 if (!$ipAssigned) {
                     if (!$serverNetworkPort) {
                         $BundleTask->Log("Unable to identify network port of instance");
                         exit;
                     } else {
                         if (!$ipAddress) {
                             $networks = $osClient->network->listNetworks();
                             foreach ($networks as $network) {
                                 if ($network->{"router:external"} == true) {
                                     $publicNetworkId = $network->id;
                                 }
                             }
                             if (!$publicNetworkId) {
                                 $BundleTask->Log("Unable to identify public network to allocate");
                                 exit;
                             } else {
                                 $ip = $osClient->network->floatingIps->create($publicNetworkId, $serverNetworkPort);
                                 $ipAddress = $ip->floating_ip_address;
                                 $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->floating_ip_address, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id));
                                 $BundleTask->Log("Allocated new IP {$ipAddress} for port: {$serverNetworkPort}");
                             }
                         } else {
                             $BundleTask->Log("Found free floating IP: {$ipAddress} for use (" . json_encode($ipInfo) . ")");
                             $osClient->network->floatingIps->update($ipId, $serverNetworkPort);
                         }
                     }
                 } else {
                     $BundleTask->Log("IP: {$ipAddress} already assigned");
                 }
                 if ($ipAddress) {
                     $DBServer->remoteIp = $ipAddress;
                     $DBServer->Save();
                 }
                 exit;
             }
             try {
                 $ssh2Client = $DBServer->GetSsh2Client();
                 $ssh2Client->connect($DBServer->remoteIp, $DBServer->getPort(DBServer::PORT_SSH));
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scalr unable to establish SSH connection with server on %:%. Error: %s"), $DBServer->remoteIp, $DBServer->getPort(DBServer::PORT_SSH), $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             //Prepare script
             $BundleTask->Log(sprintf(_("Uploading builder scripts...")));
             $behaviors = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR);
             try {
                 if ($DBServer->isOpenstack()) {
                     $platform = SERVER_PLATFORMS::OPENSTACK;
                 } else {
                     $platform = $DBServer->platform;
                 }
                 $baseUrl = \Scalr::config('scalr.endpoint.scheme') . "://" . \Scalr::config('scalr.endpoint.host');
                 $options = array('server-id' => $DBServer->serverId, 'role-name' => $BundleTask->roleName, 'crypto-key' => $DBServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 'platform' => $platform, 'queryenv-url' => $baseUrl . "/query-env", 'messaging-p2p.producer-url' => $baseUrl . "/messaging", 'behaviour' => trim(trim(str_replace("base", "", $behaviors), ",")), 'env-id' => $DBServer->envId, 'region' => $DBServer->GetCloudLocation(), 'scalr-id' => SCALR_ID);
                 $command = 'scalarizr --import -y';
                 foreach ($options as $k => $v) {
                     $command .= sprintf(' -o %s=%s', $k, $v);
                 }
                 if ($DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE) == 'percona') {
                     $recipes = 'mysql=percona';
                 } else {
                     $recipes = '';
                 }
                 $scalarizrBranch = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH);
                 $scriptContents = @file_get_contents(APPPATH . "/templates/services/role_builder/chef_import.tpl");
                 /*
                 %CHEF_SERVER_URL%
                 %CHEF_VALIDATOR_NAME%
                 %CHEF_VALIDATOR_KEY%
                 %CHEF_ENVIRONMENT%
                 %CHEF_ROLE_NAME%
                 */
                 $chefServerId = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_CHEF_SERVER_ID);
                 if ($chefServerId) {
                     $chefServerInfo = $db->GetRow("SELECT * FROM services_chef_servers WHERE id=?", array($chefServerId));
                     $chefServerInfo['v_auth_key'] = $this->crypto->decrypt($chefServerInfo['v_auth_key'], $this->cryptoKey);
                 }
                 $scriptContents = str_replace(array("%PLATFORM%", "%BEHAVIOURS%", "%SZR_IMPORT_STRING%", "%DEV%", "%SCALARIZR_BRANCH%", "%RECIPES%", "%BUILD_ONLY%", "%CHEF_SERVER_URL%", "%CHEF_VALIDATOR_NAME%", "%CHEF_VALIDATOR_KEY%", "%CHEF_ENVIRONMENT%", "%CHEF_ROLE%", "%CHEF_ROLE_NAME%", "%CHEF_NODE_NAME%", "\r\n"), array($platform, trim(str_replace("base", "", str_replace(",", " ", $behaviors))), $command, $scalarizrBranch ? '1' : '0', $scalarizrBranch, $recipes, '0', $chefServerInfo['url'], $chefServerInfo['v_username'], $chefServerInfo['v_auth_key'], $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ENVIRONMENT), $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME), $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME), '', "\n"), $scriptContents);
                 if (!$ssh2Client->sendFile('/tmp/scalr-builder.sh', $scriptContents, "w+", false)) {
                     throw new Exception("Cannot upload script");
                 }
                 /*
                 $BundleTask->Log(sprintf(_("Uploading chef recipes...")));
                 if (!$ssh2Client->sendFile('/tmp/recipes.tar.gz', APPPATH . '/www/storage/chef/recipes.tar.gz')) {
                     throw new Exception("Cannot upload chef recipes");
                 }
                 */
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scripts upload failed: %s"), $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             $BundleTask->Log("Launching role builder routines on server");
             $ssh2Client->exec("chmod 0777 /tmp/scalr-builder.sh");
             // For CGE we need to use sudo
             if ($BundleTask->platform == SERVER_PLATFORMS::GCE || $BundleTask->osFamily == 'amazon') {
                 $shell = $ssh2Client->getShell();
                 fwrite($shell, "sudo su\n");
                 fwrite($shell, "touch /var/log/role-builder-output.log 2>&1\n");
                 fwrite($shell, "chmod 0666 /var/log/role-builder-output.log 2>&1\n");
                 fwrite($shell, "setsid /tmp/scalr-builder.sh > /var/log/role-builder-output.log 2>&1 &\n");
                 // Get output
                 $iterations = 0;
                 while ($l = @fgets($shell, 4096) && $iterations < 10) {
                     $meta = stream_get_meta_data($shell);
                     if ($meta["timed_out"]) {
                         break;
                     }
                     $retval .= $l;
                     $iterations++;
                 }
                 @fclose($shell);
                 $BundleTask->Log("Exec result: {$retval}");
                 /*
                 $r1 = $ssh2Client->exec("sudo touch /var/log/role-builder-output.log");
                 $BundleTask->Log("1: {$r1} ({$ssh2Client->stdErr})");
                 $r2 = $ssh2Client->exec("sudo chmod 0666 /var/log/role-builder-output.log");
                 $BundleTask->Log("2: {$r2} ({$ssh2Client->stdErr})");
                 $r3 = $ssh2Client->exec("sudo setsid /tmp/scalr-builder.sh > /var/log/role-builder-output.log 2>&1 &");
                 $BundleTask->Log("3: {$r3} ({$ssh2Client->stdErr})");
                 */
             } else {
                 $ssh2Client->exec("setsid /tmp/scalr-builder.sh > /var/log/role-builder-output.log 2>&1 &");
             }
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE;
             $BundleTask->save();
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE:
             try {
                 $ssh2Client = $DBServer->GetSsh2Client();
                 $ssh2Client->connect($DBServer->remoteIp, $DBServer->getPort(DBServer::PORT_SSH));
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scalr unable to establish SSH connection with server on %:%. Error: %s"), $DBServer->remoteIp, $DBServer->getPort(DBServer::PORT_SSH), $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             $log = $ssh2Client->getFile('/var/log/role-builder-output.log');
             $log_lines = explode("\r\n", $log);
             $last_msg = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_LAST_LOG_MESSAGE);
             while ($msg = trim(array_shift($log_lines))) {
                 if (substr($msg, -1, 1) != ']') {
                     continue;
                 }
                 if ($last_msg) {
                     if ($msg != $last_msg) {
                         continue;
                     } elseif ($msg == $last_msg) {
                         $last_msg = null;
                         continue;
                     }
                 }
                 if (stristr($msg, '[ Failed ]')) {
                     $stepLog = $ssh2Client->getFile('/var/log/role-builder-step.log');
                     $BundleTask->Log(sprintf("role-builder-step.log: %s", $stepLog));
                     $BundleTask->SnapshotCreationFailed($msg);
                 } else {
                     $BundleTask->Log($msg);
                     $DBServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_LAST_LOG_MESSAGE, $msg);
                 }
             }
             //Read /var/log/role-builder-output.log
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PENDING:
             try {
                 $platformModule = PlatformFactory::NewPlatform($BundleTask->platform);
                 $platformModule->CreateServerSnapshot($BundleTask);
             } catch (Exception $e) {
                 Logger::getLogger(LOG_CATEGORY::BUNDLE)->error($e->getMessage());
                 $BundleTask->SnapshotCreationFailed($e->getMessage());
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING:
             $addedTime = strtotime($BundleTask->dateAdded);
             if ($addedTime + 3600 < time()) {
                 $BundleTask->SnapshotCreationFailed("Server didn't send PrepareBundleResult message in time.");
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS:
             PlatformFactory::NewPlatform($BundleTask->platform)->CheckServerSnapshotStatus($BundleTask);
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS:
             $r_farm_roles = array();
             $BundleTask->Log(sprintf("Bundle task replacement type: %s", $BundleTask->replaceType));
             try {
                 $DBFarm = DBFarm::LoadByID($BundleTask->farmId);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "not found in database")) {
                     $BundleTask->SnapshotCreationFailed("Farm was removed before task was finished");
                 }
                 return;
             }
             if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_FARM) {
                 try {
                     $r_farm_roles[] = $DBFarm->GetFarmRoleByRoleID($BundleTask->prototypeRoleId);
                 } catch (Exception $e) {
                 }
             } elseif ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                 $farm_roles = $db->GetAll("\n                        SELECT id FROM farm_roles\n                        WHERE role_id=? AND new_role_id=?\n                        AND farmid IN (SELECT id FROM farms WHERE env_id=?)\n                    ", array($BundleTask->prototypeRoleId, $BundleTask->roleId, $BundleTask->envId));
                 foreach ($farm_roles as $farm_role) {
                     try {
                         $r_farm_roles[] = DBFarmRole::LoadByID($farm_role['id']);
                     } catch (Exception $e) {
                     }
                 }
             }
             $update_farm_dns_zones = array();
             $completed_roles = 0;
             foreach ($r_farm_roles as $DBFarmRole) {
                 if ($DBFarmRole->CloudLocation != $BundleTask->cloudLocation) {
                     $BundleTask->Log(sprintf("Role '%s' (ID: %s), farm '%s' (ID: %s) using the same role " . "but in abother cloud location. Skiping it.", $DBFarmRole->GetRoleObject()->name, $DBFarmRole->ID, $DBFarmRole->GetFarmObject()->Name, $DBFarmRole->FarmID));
                     $completed_roles++;
                 } else {
                     $servers = $db->GetAll("SELECT server_id FROM servers WHERE farm_roleid = ? AND role_id=? AND status NOT IN (?,?)", array($DBFarmRole->ID, $DBFarmRole->RoleID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE));
                     $BundleTask->Log(sprintf("Found %s servers that need to be replaced with new ones. " . "Role '%s' (ID: %s), farm '%s' (ID: %s)", count($servers), $DBFarmRole->GetRoleObject()->name, $DBFarmRole->ID, $DBFarmRole->GetFarmObject()->Name, $DBFarmRole->FarmID));
                     if (count($servers) == 0) {
                         $DBFarmRole->RoleID = $DBFarmRole->NewRoleID;
                         $DBFarmRole->NewRoleID = null;
                         $DBFarmRole->Save();
                         $update_farm_dns_zones[$DBFarmRole->FarmID] = 1;
                         $completed_roles++;
                     } else {
                         $metaData = $BundleTask->getSnapshotDetails();
                         foreach ($servers as $server) {
                             try {
                                 $DBServer = DBServer::LoadByID($server['server_id']);
                             } catch (Exception $e) {
                                 //TODO:
                                 continue;
                             }
                             if ($DBServer->serverId == $BundleTask->serverId || $metaData['noServersReplace']) {
                                 $DBServer->roleId = $BundleTask->roleId;
                                 $DBServer->Save();
                                 if ($metaData['noServersReplace']) {
                                     $BundleTask->Log(sprintf("'Do not replace servers' option was checked. " . "Server '%s' won't be replaced to new image.", $DBServer->serverId));
                                 } else {
                                     $BundleTask->Log(sprintf("Server '%s', on which snapshot has been taken, " . "already has all modifications. No need to replace it.", $DBServer->serverId));
                                 }
                                 if ($DBServer->GetFarmObject()->Status == FARM_STATUS::SYNCHRONIZING) {
                                     $DBServer->terminate(array('BUNDLE_TASK_FINISHED', 'Synchronizing', $BundleTask->id));
                                 }
                             } else {
                                 if (!$db->GetOne("SELECT server_id FROM servers WHERE replace_server_id=? AND status NOT IN (?,?,?) LIMIT 1", array($DBServer->serverId, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TROUBLESHOOTING))) {
                                     $ServerCreateInfo = new ServerCreateInfo($DBFarmRole->Platform, $DBFarmRole, $DBServer->index, $DBFarmRole->NewRoleID);
                                     $nDBServer = Scalr::LaunchServer($ServerCreateInfo, null, false, "Server replacement after snapshotting", !empty($BundleTask->createdById) ? $BundleTask->createdById : null);
                                     $nDBServer->replaceServerID = $DBServer->serverId;
                                     $nDBServer->Save();
                                     $BundleTask->Log(sprintf(_("Started new server %s to replace server %s"), $nDBServer->serverId, $DBServer->serverId));
                                 }
                             }
                         }
                     }
                 }
             }
             if ($completed_roles == count($r_farm_roles)) {
                 $BundleTask->Log(sprintf(_("No servers with old role. Replacement complete. Bundle task complete."), SERVER_REPLACEMENT_TYPE::NO_REPLACE, SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS));
                 try {
                     if ($DBServer->status == SERVER_STATUS::IMPORTING) {
                         $DBServer->Remove();
                     } elseif ($DBServer->status == SERVER_STATUS::TEMPORARY) {
                         $BundleTask->Log("Terminating temporary server");
                         $DBServer->terminate('TEMPORARY_SERVER_ROLE_BUILDER');
                         $BundleTask->Log("Termination request has been sent");
                     }
                 } catch (Exception $e) {
                     $BundleTask->Log("Warning: {$e->getMessage()}");
                 }
                 $BundleTask->setDate('finished');
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                 $BundleTask->Save();
             }
             try {
                 if (count($update_farm_dns_zones) != 0) {
                     foreach ($update_farm_dns_zones as $farm_id => $v) {
                         $dnsZones = DBDNSZone::loadByFarmId($farm_id);
                         foreach ($dnsZones as $dnsZone) {
                             if ($dnsZone->status != DNS_ZONE_STATUS::INACTIVE && $dnsZone->status != DNS_ZONE_STATUS::PENDING_DELETE) {
                                 $dnsZone->updateSystemRecords();
                                 $dnsZone->save();
                             }
                         }
                     }
                 }
             } catch (Exception $e) {
                 $this->Logger->fatal("DNS ZONE: {$e->getMessage()}");
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::CREATING_ROLE:
             try {
                 if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                     $saveOldRole = false;
                     try {
                         $dbRole = DBRole::loadById($DBServer->roleId);
                         if ($dbRole->name == $BundleTask->roleName && $dbRole->envId == $BundleTask->envId) {
                             $saveOldRole = true;
                         }
                     } catch (Exception $e) {
                         //NO OLD ROLE
                     }
                     if ($dbRole && $saveOldRole) {
                         if ($DBServer) {
                             $new_role_name = BundleTask::GenerateRoleName($DBServer->GetFarmRoleObject(), $DBServer);
                         } else {
                             $new_role_name = $BundleTask->roleName . "-" . rand(1000, 9999);
                         }
                         $dbRole->name = $new_role_name;
                         $BundleTask->Log(sprintf(_("Old role '%s' (ID: %s) renamed to '%s'"), $BundleTask->roleName, $dbRole->id, $new_role_name));
                         $dbRole->save();
                     } else {
                         //TODO:
                         //$this->Logger->error("dbRole->replace->fail({$BundleTask->roleName}, {$BundleTask->envId})");
                     }
                 }
                 try {
                     $DBRole = DBRole::createFromBundleTask($BundleTask);
                 } catch (Exception $e) {
                     $BundleTask->SnapshotCreationFailed("Role creation failed due to internal error ({$e->getMessage()}). Please try again.");
                     return;
                 }
                 if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::NO_REPLACE) {
                     $BundleTask->setDate('finished');
                     $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                     $BundleTask->Log(sprintf(_("Replacement type: %s. Bundle task status: %s"), SERVER_REPLACEMENT_TYPE::NO_REPLACE, SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS));
                     try {
                         $DBServer = DBServer::LoadByID($BundleTask->serverId);
                         if ($DBServer->status == SERVER_STATUS::IMPORTING) {
                             if ($DBServer->farmId) {
                                 // Create DBFarmRole object
                                 // TODO: create DBFarm role
                             }
                         }
                     } catch (Exception $e) {
                     }
                 } else {
                     try {
                         $BundleTask->Log(sprintf(_("Replacement type: %s. Bundle task status: %s"), $BundleTask->replaceType, SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS));
                         if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_FARM) {
                             $DBFarm = DBFarm::LoadByID($BundleTask->farmId);
                             $DBFarmRole = $DBFarm->GetFarmRoleByRoleID($BundleTask->prototypeRoleId);
                             $DBFarmRole->NewRoleID = $BundleTask->roleId;
                             $DBFarmRole->Save();
                         } else {
                             $farm_roles = $db->GetAll("SELECT id FROM farm_roles WHERE role_id=? AND farmid IN (SELECT id FROM farms WHERE env_id=?)", array($BundleTask->prototypeRoleId, $BundleTask->envId));
                             foreach ($farm_roles as $farm_role) {
                                 $DBFarmRole = DBFarmRole::LoadByID($farm_role['id']);
                                 $DBFarmRole->NewRoleID = $BundleTask->roleId;
                                 $DBFarmRole->Save();
                             }
                         }
                         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS;
                     } catch (Exception $e) {
                         $this->Logger->error($e->getMessage());
                         $BundleTask->Log(sprintf(_("Server replacement failed: %s"), $e->getMessage()));
                         $BundleTask->setDate('finished');
                         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                     }
                 }
                 if ($BundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS) {
                     try {
                         if ($DBServer->status == SERVER_STATUS::IMPORTING) {
                             $DBServer->Remove();
                         } elseif ($DBServer->status == SERVER_STATUS::TEMPORARY) {
                             $BundleTask->Log("Terminating temporary server");
                             $DBServer->terminate('TEMPORARY_SERVER_ROLE_BUILDER');
                             $BundleTask->Log("Termination request has been sent");
                         }
                     } catch (Exception $e) {
                         $BundleTask->Log("Warning: {$e->getMessage()}");
                     }
                 }
                 $BundleTask->Save();
             } catch (Exception $e) {
                 $this->Logger->error($e->getMessage());
             }
             break;
     }
 }
Пример #11
0
 private function getCloudStackClient($environment, $cloudLoction = null)
 {
     return Scalr_Service_Cloud_Cloudstack::newCloudstack($environment->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_URL), $environment->getPlatformConfigValue(Modules_Platforms_Cloudstack::API_KEY), $environment->getPlatformConfigValue(Modules_Platforms_Cloudstack::SECRET_KEY));
 }
Пример #12
0
 function handleWork($farmId)
 {
     $this->cleanup();
     $DBFarm = DBFarm::LoadByID($farmId);
     $account = Scalr_Account::init()->loadById($DBFarm->ClientID);
     $payAsYouGoTime = $account->getSetting(Scalr_Account::SETTING_BILLING_PAY_AS_YOU_GO_DATE);
     $GLOBALS["SUB_TRANSACTIONID"] = abs(crc32(posix_getpid() . $farmId));
     $GLOBALS["LOGGER_FARMID"] = $farmId;
     $this->logger->info("[" . $GLOBALS["SUB_TRANSACTIONID"] . "] Begin polling farm (ID: {$DBFarm->ID}, Name: {$DBFarm->Name}, Status: {$DBFarm->Status})");
     //
     // Collect information from database
     //
     $servers_count = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id = ? AND status != ?", array($DBFarm->ID, SERVER_STATUS::TERMINATED));
     $this->logger->info("[FarmID: {$DBFarm->ID}] Found {$servers_count} farm instances in database");
     if ($DBFarm->Status == FARM_STATUS::TERMINATED && $servers_count == 0) {
         return;
     }
     foreach ($DBFarm->GetServersByFilter(array(), array('status' => SERVER_STATUS::PENDING_LAUNCH)) as $DBServer) {
         try {
             if ($DBServer->status != SERVER_STATUS::PENDING && $DBServer->status != SERVER_STATUS::PENDING_TERMINATE) {
                 $p = PlatformFactory::NewPlatform($DBServer->platform);
                 if (!$p->IsServerExists($DBServer)) {
                     try {
                         $serverInfo = $p->GetServerExtendedInformation($DBServer);
                     } catch (Exception $e) {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: {$DBFarm->ID}] Crash check for server '{$DBServer->serverId}' failed: {$e->getMessage()}"));
                     }
                     if (!$serverInfo) {
                         if ($DBServer->status != SERVER_STATUS::PENDING_TERMINATE && $DBServer->status != SERVER_STATUS::TERMINATED) {
                             if ($DBServer->GetProperty("system.crashed") == 1) {
                                 $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                                 Scalr::FireEvent($DBFarm->ID, new HostCrashEvent($DBServer));
                             } else {
                                 $DBServer->SetProperty(SERVER_PROPERTIES::REBOOTING, 0);
                                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' found in database but not found on {$DBServer->platform}. Crashed.", $DBServer->serverId)));
                                 $DBServer->SetProperty("system.crashed", "1");
                             }
                             continue;
                         }
                     } else {
                         Logger::getLogger(LOG_CATEGORY::FARM)->error(sprintf("[CRASH][FarmID: {$DBFarm->ID}] False-positive crash check: {$DBServer->serverId}"));
                         if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->fatal(sprintf("[CRASH][FarmID: {$DBFarm->ID}] InstanceID: %s, List: %s", $DBServer->GetCloudServerID(), json_encode($p->instancesListCache)));
                         }
                     }
                 } else {
                     $DBServer->SetProperty("system.crashed", "0");
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "AWS was not able to validate the provided access credentials") || stristr($e->getMessage(), "Unable to sign AWS API request. Please, check your X.509")) {
                 $env = Scalr_Environment::init()->LoadById($DBFarm->EnvID);
                 $env->status = Scalr_Environment::STATUS_INACTIVE;
                 $env->save();
                 $env->setPlatformConfig(array('system.auto-disable-reason' => $e->getMessage()), false);
                 return;
             }
             if (stristr($e->getMessage(), "Could not connect to host")) {
                 continue;
             }
             print "[0][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             continue;
         }
         try {
             $realStatus = $DBServer->GetRealStatus()->getName();
             if ($realStatus == 'stopped') {
                 $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, $realStatus);
                 continue;
             } else {
                 if ($DBServer->GetProperty(SERVER_PROPERTIES::SUB_STATUS) == 'stopped') {
                     $DBServer->SetProperty(SERVER_PROPERTIES::SUB_STATUS, "");
                 }
             }
         } catch (Exception $e) {
         }
         try {
             if (!in_array($DBServer->status, array(SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE)) && $DBServer->GetRealStatus()->isTerminated()) {
                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' (Platform: %s) not running (Real state: %s, Scalr status: %s).", $DBServer->serverId, $DBServer->platform, $DBServer->GetRealStatus()->getName(), $DBServer->status)));
                 $DBServer->terminate(DBServer::TERMINATE_REASON_CRASHED);
                 $DBServer->SetProperty(SERVER_PROPERTIES::REBOOTING, 0);
                 Scalr::FireEvent($DBFarm->ID, new HostDownEvent($DBServer));
                 continue;
             } elseif ($DBServer->status != SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->IsRunning()) {
                 if ($DBServer->status != SERVER_STATUS::TERMINATED && $DBServer->status != SERVER_STATUS::TROUBLESHOOTING) {
                     /*
                     if ($DBServer->platform == SERVER_PLATFORMS::NIMBULA)
                     {
                         if (!$DBServer->GetProperty(NIMBULA_SERVER_PROPERTIES::USER_DATA_INJECTED))
                         {
                             $dbRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
                     
                             $ssh2Client = new Scalr_Net_Ssh2_Client();
                             $ssh2Client->addPassword(
                                 $dbRole->getProperty(DBRole::PROPERTY_NIMBULA_INIT_ROOT_USER),
                                 $dbRole->getProperty(DBRole::PROPERTY_NIMBULA_INIT_ROOT_PASS)
                             );
                     
                             $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                     
                             $port = $dbRole->getProperty(DBRole::PROPERTY_SSH_PORT);
                             if (!$port) $port = 22;
                     
                             try {
                                 $ssh2Client->connect($info['remoteIp'], $port);
                     
                                 foreach ($DBServer->GetCloudUserData() as $k=>$v)
                                     $u_data .= "{$k}={$v};";
                     
                                 $u_data = trim($u_data, ";");
                                 $ssh2Client->sendFile('/etc/scalr/private.d/.user-data', $u_data, "w+", false);
                     
                                 $DBServer->SetProperty(NIMBULA_SERVER_PROPERTIES::USER_DATA_INJECTED, 1);
                             }
                             catch(Exception $e) {
                                 Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBFarm->ID, $e->getMessage()));
                             }
                         }
                     }
                     */
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         if ($DBServer->status == SERVER_STATUS::PENDING && $DBFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
                             if ($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_AWS_VPC_INTERNET_ACCESS) != 'outbound-only') {
                                 $ipAddress = Modules_Platforms_Ec2_Helpers_Eip::setEipForServer($DBServer);
                                 if ($ipAddress) {
                                     $DBServer->remoteIp = $ipAddress;
                                     $DBServer->Save();
                                 }
                             }
                         }
                     }
                     if ($DBServer->isOpenstack()) {
                         $ipPool = $DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_OPENSTACK_IP_POOL);
                         if (!$DBServer->remoteIp && ($DBServer->status == SERVER_STATUS::PENDING || $DBServer->status == SERVER_STATUS::INIT) && $ipPool) {
                             $osClient = $DBServer->GetEnvironmentObject()->openstack($DBServer->platform, $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
                             if ($osClient->hasService('network')) {
                                 $platform = PlatformFactory::NewPlatform($DBServer->platform);
                                 $serverIps = $platform->GetServerIPAddresses($DBServer);
                                 /********* USE Quantum (Neuron) NETWORK *******/
                                 $ips = $osClient->network->floatingIps->list();
                                 //Check free existing IP
                                 $ipAssigned = false;
                                 $ipAddress = false;
                                 $ipId = false;
                                 $ipInfo = false;
                                 foreach ($ips as $ip) {
                                     if ($ip->fixed_ip_address == $serverIps['localIp'] && $ip->port_id) {
                                         $ipAddress = $ip->floating_ip_address;
                                         $ipId = $ip->id;
                                         $ipAssigned = true;
                                         $ipInfo = $ip;
                                         break;
                                     }
                                     /*
                                     if (!$ip->fixed_ip_address && !$ipAddress) {
                                         $ipAddress = $ip->floating_ip_address;
                                         $ipId = $ip->id;
                                         $ipInfo = $ip;
                                     }
                                     */
                                 }
                                 if ($ipInfo) {
                                     Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Found free floating IP: {$ipAddress} for use (" . json_encode($ipInfo) . ")"));
                                 }
                                 if (!$ipAssigned) {
                                     // Get instance port
                                     $ports = $osClient->network->ports->list();
                                     foreach ($ports as $port) {
                                         if ($port->device_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                                             $serverNetworkPort = $port->id;
                                             break;
                                         }
                                     }
                                     if (!$serverNetworkPort) {
                                         Logger::getLogger("Openstack")->error(new FarmLogMessage($DBServer->farmId, "Unable to identify network port of instance"));
                                     } else {
                                         if (!$ipAddress) {
                                             $publicNetworkId = $ipPool;
                                             /*
                                             $networks = $osClient->network->listNetworks();
                                             foreach ($networks as $network) {
                                                 if ($network->{"router:external"} == true) {
                                                     $publicNetworkId = $network->id;
                                                 }
                                             }
                                             
                                             if (!$publicNetworkId) {
                                                 Logger::getLogger("Openstack")->error(new FarmLogMessage($DBServer->farmId,
                                                                                                     "Unable to identify public network to allocate"
                                                                                                 ));
                                             } else {
                                             */
                                             $ip = $osClient->network->floatingIps->create($publicNetworkId, $serverNetworkPort);
                                             $ipAddress = $ip->floating_ip_address;
                                             $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->floating_ip_address, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id));
                                             Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "Allocated new IP {$ipAddress} for port: {$serverNetworkPort}"));
                                             //}
                                         } else {
                                             /*
                                             Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId,
                                               "Updating IP {$ipAddress} ({$ipId}) with port: {$serverNetworkPort}"
                                             ));
                                             $osClient->network->floatingIps->update($ipId, $serverNetworkPort);
                                             */
                                         }
                                     }
                                 } else {
                                     Logger::getLogger("Openstack")->warn(new FarmLogMessage($DBServer->farmId, "IP: {$ipAddress} already assigned"));
                                 }
                             } else {
                                 /********* USE NOVA NETWORK *******/
                                 //Check free existing IP
                                 $ipAssigned = false;
                                 $ipAddress = false;
                                 $ips = $osClient->servers->floatingIps->list($ipPool);
                                 foreach ($ips as $ip) {
                                     //if (!$ip->instance_id) {
                                     //	$ipAddress = $ip->ip;
                                     //}
                                     if ($ip->instance_id == $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID)) {
                                         $ipAddress = $ip->ip;
                                         $ipAssigned = true;
                                     }
                                 }
                                 //If no free IP allocate new from pool
                                 if (!$ipAddress) {
                                     $ip = $osClient->servers->floatingIps->create($ipPool);
                                     $ipAddress = $ip->ip;
                                     $DBServer->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::FLOATING_IP => $ip->ip, OPENSTACK_SERVER_PROPERTIES::FLOATING_IP_ID => $ip->id));
                                 }
                                 if (!$ipAssigned) {
                                     //Associate floating IP with Instance
                                     $osClient->servers->addFloatingIp($DBServer->GetCloudServerID(), $ipAddress);
                                 }
                             }
                             if ($ipAddress) {
                                 $DBServer->remoteIp = $ipAddress;
                                 $DBServer->Save();
                                 $DBServer->SetProperty(SERVER_PROPERTIES::SYSTEM_IGNORE_INBOUND_MESSAGES, null);
                             }
                         }
                     }
                     if ($DBServer->isCloudstack()) {
                         if ($DBServer->status == SERVER_STATUS::PENDING) {
                             $jobId = $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::LAUNCH_JOB_ID);
                             try {
                                 $platform = PlatformFactory::NewPlatform($DBServer->platform);
                                 $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $DBServer->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $DBServer->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $DBServer->GetEnvironmentObject()), $DBServer->platform);
                                 $res = $cs->queryAsyncJobResult($jobId);
                                 if ($res->jobresult->jobstatus == 1) {
                                     $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::TMP_PASSWORD, $res->jobresult->virtualmachine->password);
                                     $DBServer->SetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_NAME, $res->jobresult->virtualmachine->name);
                                 }
                                 //TODO: handle failed job: $res->jobresult->jobstatus == 2
                             } catch (Exception $e) {
                                 if ($DBServer->farmId) {
                                     Logger::getLogger("CloudStack")->error(new FarmLogMessage($DBServer->farmId, $e->getMessage()));
                                 }
                             }
                         }
                     }
                     try {
                         $dtadded = strtotime($DBServer->dateAdded);
                         $DBFarmRole = $DBServer->GetFarmRoleObject();
                         $launch_timeout = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) > 0 ? $DBFarmRole->GetSetting(DBFarmRole::SETTING_SYSTEM_LAUNCH_TIMEOUT) : 900;
                     } catch (Exception $e) {
                         if (stristr($e->getMessage(), "not found")) {
                             $DBServer->terminate('FARM_ROLE_NOT_FOUND');
                         }
                     }
                     $scripting_event = false;
                     if ($DBServer->status == SERVER_STATUS::PENDING) {
                         $event = "hostInit";
                         $scripting_event = EVENT_TYPE::HOST_INIT;
                     } elseif ($DBServer->status == SERVER_STATUS::INIT) {
                         $event = "hostUp";
                         $scripting_event = EVENT_TYPE::HOST_UP;
                     }
                     if ($scripting_event && $dtadded) {
                         $scripting_timeout = (int) $this->db->GetOne("\n                                SELECT sum(timeout)\n                                FROM farm_role_scripts\n                                WHERE event_name=? AND\n                                farm_roleid=? AND issync='1'\n                            ", array($scripting_event, $DBServer->farmRoleId));
                         if ($scripting_timeout) {
                             $launch_timeout = $launch_timeout + $scripting_timeout;
                         }
                         if ($dtadded + $launch_timeout < time() && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //Add entry to farm log
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Server '%s' did not send '%s' event in %s seconds after launch (Try increasing timeouts in role settings). Considering it broken. Terminating instance.", $DBServer->serverId, $event, $launch_timeout)));
                             try {
                                 $DBServer->terminate(array('SERVER_DID_NOT_SEND_EVENT', $event, $launch_timeout), false);
                             } catch (Exception $err) {
                                 $this->logger->fatal($err->getMessage());
                             }
                         } elseif ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                             //DO NOT TERMINATE MONGODB INSTANCES BY TIMEOUT! IT'S NOT SAFE
                             //THINK ABOUT WORKAROUND
                         }
                     }
                     // Is IP address changed?
                     if (!$DBServer->IsRebooting()) {
                         $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                         if ($ipaddresses['remoteIp'] && $DBServer->remoteIp && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp && $DBServer->localIp != $ipaddresses['localIp']) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("RemoteIP: %s (%s), LocalIp: %s (%s) (Poller).", $DBServer->remoteIp, $ipaddresses['remoteIp'], $DBServer->localIp, $ipaddresses['localIp'])));
                             Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                         }
                         //TODO: Check health:
                     }
                 }
             } elseif ($DBServer->status == SERVER_STATUS::RUNNING && $DBServer->GetRealStatus()->isRunning()) {
                 // Is IP address changed?
                 if (!$DBServer->IsRebooting()) {
                     $ipaddresses = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
                     if ($ipaddresses['remoteIp'] && $DBServer->remoteIp && $DBServer->remoteIp != $ipaddresses['remoteIp'] || $ipaddresses['localIp'] && $DBServer->localIp && $DBServer->localIp != $ipaddresses['localIp']) {
                         Scalr::FireEvent($DBServer->farmId, new IPAddressChangedEvent($DBServer, $ipaddresses['remoteIp'], $ipaddresses['localIp']));
                     }
                     if ($payAsYouGoTime) {
                         $initTime = $DBServer->GetProperty(SERVER_PROPERTIES::INITIALIZED_TIME);
                         if ($initTime < $payAsYouGoTime) {
                             $initTime = $payAsYouGoTime;
                         }
                         $runningHours = ceil((time() - $initTime) / 3600);
                         $scuUsed = $runningHours * Scalr_Billing::getSCUByInstanceType($DBServer->GetFlavor());
                         $this->db->Execute("UPDATE servers_history SET scu_used = ?, scu_updated = 0 WHERE server_id = ?", array($scuUsed, $DBServer->serverId));
                     }
                     //Update GCE ServerID
                     if ($DBServer->platform == SERVER_PLATFORMS::GCE) {
                         if ($DBServer->GetProperty(GCE_SERVER_PROPERTIES::SERVER_ID) == $DBServer->serverId) {
                             $info = PlatformFactory::NewPlatform($DBServer->platform)->GetServerExtendedInformation($DBServer);
                             $DBServer->SetProperty(GCE_SERVER_PROPERTIES::SERVER_ID, $info['Cloud Server ID']);
                         }
                     }
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $env = Scalr_Environment::init()->loadById($DBServer->envId);
                         $ec2 = $env->aws($DBServer->GetCloudLocation())->ec2;
                         //TODO:
                         $isEnabled = $ec2->instance->describeAttribute($DBServer->GetCloudServerID(), InstanceAttributeType::disableApiTermination());
                         $DBServer->SetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED, $isEnabled);
                     }
                 } else {
                     //TODO: Check reboot timeout
                 }
             }
         } catch (Exception $e) {
             if (stristr($e->getMessage(), "not found")) {
                 print $e->getTraceAsString() . "\n";
             } else {
                 print "[1][Farm: {$farmId}] {$e->getMessage()} at {$e->getFile()}:{$e->getLine()}\n\n";
             }
         }
     }
 }
Пример #13
0
 /**
  *
  * @return Scalr_Service_Cloud_Cloudstack_Client
  */
 private function getCloudStackClient($environment, $cloudLoction = null, $platformName)
 {
     $platform = PlatformFactory::NewPlatform($platformName);
     return Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $environment), $platformName);
 }
Пример #14
0
 public static function farmUpdateRoleSettings(DBFarmRole $dbFarmRole, $oldSettings, $newSettings)
 {
     $db = \Scalr::getDb();
     $dbFarm = $dbFarmRole->GetFarmObject();
     $dbFarmRole->SetSetting(DBFarmRole::SETIING_CLOUDSTACK_STATIC_NAT_MAP, null, DBFarmRole::TYPE_LCL);
     $platform = PlatformFactory::NewPlatform($dbFarmRole->Platform);
     $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $dbFarm->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $dbFarm->GetEnvironmentObject()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $dbFarm->GetEnvironmentObject()), $dbFarmRole->Platform);
     // Disassociate IP addresses if checkbox was unchecked
     if (!$newSettings[DBFarmRole::SETIING_CLOUDSTACK_USE_STATIC_NAT] && $oldSettings[DBFarmRole::SETIING_CLOUDSTACK_USE_STATIC_NAT]) {
         $eips = $db->Execute("\n                    SELECT * FROM elastic_ips WHERE farm_roleid = ?\n                ", array($dbFarmRole->ID));
         while ($eip = $eips->FetchRow()) {
             try {
                 $cs->disassociateIpAddress($eip['allocation_id']);
             } catch (Exception $e) {
             }
         }
         $db->Execute("DELETE FROM elastic_ips WHERE farm_roleid = ?", array($dbFarmRole->ID));
     }
     //TODO: Handle situation when tab was not opened, but max instances setting was changed.
     if ($newSettings[DBFarmRole::SETIING_CLOUDSTACK_STATIC_NAT_MAP] && $newSettings[DBFarmRole::SETIING_CLOUDSTACK_USE_STATIC_NAT]) {
         $map = explode(";", $newSettings[DBFarmRole::SETIING_CLOUDSTACK_STATIC_NAT_MAP]);
         foreach ($map as $ipconfig) {
             list($serverIndex, $ipAddress) = explode("=", $ipconfig);
             if (!$serverIndex) {
                 continue;
             }
             $dbServer = false;
             try {
                 $dbServer = DBServer::LoadByFarmRoleIDAndIndex($dbFarmRole->ID, $serverIndex);
                 if ($dbServer->remoteIp == $ipAddress) {
                     continue;
                 }
                 // Remove old association
                 $db->Execute("\n                            DELETE FROM elastic_ips WHERE farm_roleid = ? AND instance_index=?\n                        ", array($dbFarmRole->ID, $serverIndex));
             } catch (Exception $e) {
             }
             // Allocate new IP if needed
             if (!$ipAddress || $ipAddress == '0.0.0.0') {
                 if ($dbServer) {
                     $ipAddress = self::setStaticNatForServer($dbServer);
                 } else {
                     continue;
                 }
             } else {
                 //Remove old IP association
                 $db->Execute("\n                            DELETE FROM elastic_ips WHERE ipaddress=?\n                        ", array($ipAddress));
                 $info = $cs->listPublicIpAddresses(null, null, null, null, null, $ipAddress);
                 $info = $info->publicipaddress[0];
                 // Associate IP with server in our db
                 $db->Execute("INSERT INTO elastic_ips SET\n                            env_id=?,\n                            farmid=?,\n                            farm_roleid=?,\n                            ipaddress=?,\n                            state='0',\n                            instance_id='',\n                            clientid=?,\n                            instance_index=?,\n                            allocation_id=?\n                        ", array($dbFarm->EnvID, $dbFarmRole->FarmID, $dbFarmRole->ID, $ipAddress, $dbFarm->ClientID, $serverIndex, $info->id));
             }
             $ipInfo = $db->GetRow("SELECT allocation_id FROM elastic_ips WHERE ipaddress = ? LIMIT 1", $ipAddress);
             // Associate IP on AWS with running server
             if ($dbServer) {
                 try {
                     $db->Execute("UPDATE elastic_ips SET state='1', server_id = ? WHERE ipaddress = ?", array($dbServer->serverId, $ipAddress));
                     $update = false;
                     if ($dbServer->remoteIp != $ipAddress) {
                         if ($dbServer && $dbServer->status == SERVER_STATUS::RUNNING) {
                             $fireEvent = self::associateIpAddress($dbServer, $ipAddress, $ipInfo['allocation_id']);
                         }
                     }
                     if ($fireEvent) {
                         $event = new IPAddressChangedEvent($dbServer, $ipAddress, $dbServer->localIp);
                         Scalr::FireEvent($dbServer->farmId, $event);
                     }
                 } catch (Exception $e) {
                 }
             }
         }
     }
 }
Пример #15
0
 public function xGetCloudServersListAction()
 {
     $this->request->defineParams(array('platform', 'cloudLocation'));
     if (!$this->environment->isPlatformEnabled($this->getParam('platform'))) {
         throw new Exception(sprintf('Cloud %s is not enabled for current environment', $this->getParam('platform')));
     }
     $results = array();
     $platform = PlatformFactory::NewPlatform($this->getParam('platform'));
     //TODO: Added support for GCE
     if ($this->getParam('platform') == SERVER_PLATFORMS::GCE) {
         $gce = $platform->getClient($this->environment, $this->getParam('cloudLocation'));
         $result = $gce->instances->listInstances($this->environment->getPlatformConfigValue(Modules_Platforms_GoogleCE::PROJECT_ID), $this->getParam('cloudLocation'), array());
         if (is_array($result->items)) {
             foreach ($result->items as $server) {
                 if ($server->status != 'RUNNING') {
                     continue;
                 }
                 $ips = $platform->determineServerIps($gce, $server);
                 $itm = array('id' => $server->name, 'localIp' => $ips['localIp'], 'publicIp' => $ips['remoteIp'], 'zone' => $this->getParam('cloudLocation'), 'isImporting' => false, 'isManaged' => false);
                 //Check is instance already importing
                 try {
                     $dbServer = DBServer::LoadByPropertyValue(GCE_SERVER_PROPERTIES::SERVER_ID, $server->id);
                     if ($dbServer && $dbServer->status != SERVER_STATUS::TERMINATED) {
                         if ($dbServer->status == SERVER_STATUS::IMPORTING) {
                             $itm['isImporting'] = true;
                         } else {
                             $itm['isManaged'] = true;
                         }
                         $itm['serverId'] = $dbServer->serverId;
                     }
                 } catch (Exception $e) {
                 }
                 $results[] = $itm;
             }
         }
     } elseif (PlatformFactory::isOpenstack($this->getParam('platform'))) {
         $client = $this->environment->openstack($this->getParam('platform'), $this->getParam('cloudLocation'));
         $r = $client->servers->list(true);
         foreach ($r as $server) {
             if ($server->status != 'ACTIVE') {
                 continue;
             }
             $ips = $platform->determineServerIps($client, $server);
             $itm = array('id' => $server->id, 'localIp' => $ips['localIp'], 'publicIp' => $ips['remoteIp'], 'zone' => $this->getParam('cloudLocation'), 'isImporting' => false, 'isManaged' => false);
             //Check is instance already importing
             try {
                 $dbServer = DBServer::LoadByPropertyValue(OPENSTACK_SERVER_PROPERTIES::SERVER_ID, $server->id);
                 if ($dbServer && $dbServer->status != SERVER_STATUS::TERMINATED) {
                     if ($dbServer->status == SERVER_STATUS::IMPORTING) {
                         $itm['isImporting'] = true;
                     } else {
                         $itm['isManaged'] = true;
                     }
                     $itm['serverId'] = $dbServer->serverId;
                 }
             } catch (Exception $e) {
             }
             $results[] = $itm;
         }
     } elseif (PlatformFactory::isCloudstack($this->getParam('platform'))) {
         $client = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $this->environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $this->environment), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $this->environment), $this->getParam('platform'));
         $platform = PlatformFactory::NewPlatform($this->getParam('platform'));
         $r = $client->listVirtualMachines(null, $this->getParam('cloudLocation'));
         foreach ($r as $server) {
             $ips = $platform->determineServerIps($client, $server);
             $itm = array('id' => $server->id, 'localIp' => $ips['localIp'], 'publicIp' => $ips['remoteIp'], 'zone' => $this->getParam('cloudLocation'), 'isImporting' => false, 'isManaged' => false);
             //Check is instance already importing
             try {
                 $dbServer = DBServer::LoadByPropertyValue(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID, $server->id);
                 if ($dbServer && $dbServer->status != SERVER_STATUS::TERMINATED) {
                     if ($dbServer->status == SERVER_STATUS::IMPORTING) {
                         $itm['isImporting'] = true;
                     } else {
                         $itm['isManaged'] = true;
                     }
                     $itm['serverId'] = $dbServer->serverId;
                 }
             } catch (Exception $e) {
             }
             $results[] = $itm;
         }
     } elseif ($this->getParam('platform') == SERVER_PLATFORMS::EC2) {
         $client = $this->environment->aws($this->getParam('cloudLocation'))->ec2;
         $r = $client->instance->describe();
         if (count($r)) {
             foreach ($r as $reservation) {
                 /* @var $reservation Scalr\Service\Aws\Ec2\DataType\ReservationData */
                 foreach ($reservation->instancesSet as $instance) {
                     /* @var $instance Scalr\Service\Aws\Ec2\DataType\InstanceData */
                     if ($instance->instanceState->name != 'running') {
                         continue;
                     }
                     $itm = array('id' => $instance->instanceId, 'localIp' => $instance->privateIpAddress, 'publicIp' => $instance->ipAddress, 'zone' => $instance->placement->availabilityZone, 'isImporting' => false, 'isManaged' => false);
                     //Check is instance already importing
                     try {
                         $dbServer = DBServer::LoadByPropertyValue(EC2_SERVER_PROPERTIES::INSTANCE_ID, $instance->instanceId);
                         if ($dbServer && $dbServer->status != SERVER_STATUS::TERMINATED) {
                             if ($dbServer->status == SERVER_STATUS::IMPORTING) {
                                 $itm['isImporting'] = true;
                             } else {
                                 $itm['isManaged'] = true;
                             }
                             $itm['serverId'] = $dbServer->serverId;
                         }
                     } catch (Exception $e) {
                     }
                     $results[] = $itm;
                 }
             }
         }
     }
     $this->response->data(array('data' => $results));
 }
Пример #16
0
 public function xGetNetworksAction()
 {
     $platform = PlatformFactory::NewPlatform($this->getParam('platform'));
     $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($platform->getConfigVariable(Modules_Platforms_Cloudstack::API_URL, $this->getEnvironment()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::API_KEY, $this->getEnvironment()), $platform->getConfigVariable(Modules_Platforms_Cloudstack::SECRET_KEY, $this->getEnvironment()), $this->getParam('platform'));
     $data = array();
     if (!$this->getParam('cloudLocation')) {
         $cloudLocations = array_keys(self::loadController('Platforms')->getCloudLocations($this->getParam('platform'), false));
     } else {
         $cloudLocations = array($this->getParam('cloudLocation'));
     }
     $accountName = $platform->getConfigVariable(Modules_Platforms_Cloudstack::ACCOUNT_NAME, $this->getEnvironment(), false);
     $domainId = $platform->getConfigVariable(Modules_Platforms_Cloudstack::DOMAIN_ID, $this->getEnvironment(), false);
     foreach ($cloudLocations as $cloudLocation) {
         $networks = $cs->listNetworks($cloudLocation, $accountName, $domainId);
         $data[$cloudLocation][] = array('id' => '', 'name' => 'Do not use network offering');
         foreach ($networks as $network) {
             $data[$cloudLocation][] = array('id' => (string) $network->id, 'name' => "{$network->id}: {$network->name} ({$network->networkdomain})");
         }
     }
     $this->response->data(array('data' => $data));
 }
Пример #17
0
 public function xSaveCloudstackAction()
 {
     $pars = array();
     $enabled = false;
     if ($this->getParam('cloudstack_is_enabled')) {
         $enabled = true;
         $pars[Modules_Platforms_Cloudstack::API_URL] = $this->checkVar(Modules_Platforms_Cloudstack::API_URL, 'string', 'API URL required');
         $pars[Modules_Platforms_Cloudstack::API_KEY] = $this->checkVar(Modules_Platforms_Cloudstack::API_KEY, 'string', 'API key required');
         $pars[Modules_Platforms_Cloudstack::SECRET_KEY] = $this->checkVar(Modules_Platforms_Cloudstack::SECRET_KEY, 'string', 'Secret key required');
     }
     if (count($this->checkVarError)) {
         $this->response->failure();
         $this->response->data(array('errors' => $this->checkVarError));
     } else {
         $cs = Scalr_Service_Cloud_Cloudstack::newCloudstack($pars[Modules_Platforms_Cloudstack::API_URL], $pars[Modules_Platforms_Cloudstack::API_KEY], $pars[Modules_Platforms_Cloudstack::SECRET_KEY]);
         $accounts = $cs->listAccounts();
         foreach ($accounts as $account) {
             foreach ($account->user as $user) {
                 if ($user->apikey == $pars[Modules_Platforms_Cloudstack::API_KEY]) {
                     $dPars[Modules_Platforms_Cloudstack::ACCOUNT_NAME] = $user->account;
                     $dPars[Modules_Platforms_Cloudstack::DOMAIN_NAME] = $user->domain;
                     $dPars[Modules_Platforms_Cloudstack::DOMAIN_ID] = $user->domainid;
                 }
             }
         }
         if (!$dPars[Modules_Platforms_Cloudstack::ACCOUNT_NAME]) {
             throw new Exception("Cannot determine account name for provided keys");
         }
         $this->db->BeginTrans();
         try {
             $this->env->enablePlatform(SERVER_PLATFORMS::CLOUDSTACK, $enabled);
             if ($enabled) {
                 $this->env->setPlatformConfig($pars);
                 $this->env->setPlatformConfig($dPars, false);
             }
             if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) {
                 $this->user->getAccount()->setSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED, time());
             }
             $this->response->success('Environment saved');
             $this->response->data(array('enabled' => $enabled));
         } catch (Exception $e) {
             $this->db->RollbackTrans();
             throw new Exception(_('Failed to save Cloudstack settings'));
         }
         $this->db->CommitTrans();
     }
 }