コード例 #1
0
ファイル: Bundletasks.php プロジェクト: scalr/scalr
 /**
  * @param   int     $bundleTaskId       ID of BundleTask
  * @param   string  $status   optional  Status of BundleTask
  * @param   bool    $taskInfo optional  Get updated information about task
  */
 public function xListLogsAction($bundleTaskId, $status = '', $taskInfo = false)
 {
     $task = BundleTask::LoadById($bundleTaskId);
     $this->user->getPermissions()->validate($task);
     $sql = "SELECT * FROM bundle_task_log WHERE bundle_task_id = ?";
     $response = $this->buildResponseFromSql2($sql, array('id', 'dtadded', 'message'), array(), array($bundleTaskId));
     foreach ($response["data"] as &$row) {
         $row['dtadded'] = Scalr_Util_DateTime::convertTz($row['dtadded']);
     }
     if ($taskInfo && $task->status != $status) {
         // status has been changed, also include information about task
         $row = $this->db->GetRow("SELECT b.*, (SELECT EXISTS (SELECT 1 FROM servers s WHERE s.server_id = b.server_id)) as server_exists FROM bundle_tasks b WHERE id = ?", [$task->id]);
         // temporary solution, refactor all on new model and replace this code
         $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']);
         }
         $response['task'] = $row;
     }
     $this->response->data($response);
 }
コード例 #2
0
ファイル: Bundletasks.php プロジェクト: rickb838/scalr
 public function failureDetailsAction()
 {
     $this->request->defineParams(array('bundleTaskId' => array('type' => 'int')));
     $task = BundleTask::LoadById($this->getParam('bundleTaskId'));
     $this->user->getPermissions()->validate($task);
     $this->response->page('ui/bundletasks/failuredetails.js', array('failureReason' => nl2br($task->failureReason)));
 }
コード例 #3
0
ファイル: Update20140915094208.php プロジェクト: mheydt/scalr
 protected function run2()
 {
     $this->console->notice('Modify os columns and re-fill it from bundle tasks');
     $this->db->Execute('ALTER TABLE images CHANGE `os_name` `os` varchar(60) DEFAULT NULL AFTER `name`,
          MODIFY `os_family` varchar(30) DEFAULT NULL,
          ADD `os_generation` varchar(10) DEFAULT NULL AFTER `os_family`,
          MODIFY `os_version` varchar(10) DEFAULT NULL
     ');
     $bunimages = Image::find([['source' => Image::SOURCE_BUNDLE_TASK]]);
     foreach ($bunimages as $image) {
         /* @var Image $image */
         try {
             $task = \BundleTask::LoadById($image->bundleTaskId);
             $os = $task->getOsDetails();
             $image->osId = $os->id;
             $image->save();
         } catch (\Exception $e) {
             $this->console->warning($e->getMessage());
         }
     }
 }
コード例 #4
0
ファイル: class.DBRole.php プロジェクト: rakesh-mohanta/scalr
 public static function createFromBundleTask(BundleTask $BundleTask)
 {
     $db = Core::GetDBInstance();
     if ($BundleTask->prototypeRoleId) {
         $proto_role = $db->GetRow("SELECT * FROM roles WHERE id=?", array($BundleTask->prototypeRoleId));
         $DBServer = DBServer::LoadByID($BundleTask->serverId);
     } else {
         $DBServer = DBServer::LoadByID($BundleTask->serverId);
         if ($DBServer->platform != SERVER_PLATFORMS::RDS) {
             $proto_role = array("behaviors" => $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR), "architecture" => $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE), "name" => "*import*");
         }
     }
     if (!$BundleTask->cloudLocation) {
         if ($DBServer) {
             $BundleTask->cloudLocation = $DBServer->GetCloudLocation();
         }
     }
     $meta = $BundleTask->getSnapshotDetails();
     $dist = new stdClass();
     if ($meta) {
         if ($meta['os']) {
             $os = $meta['os']->version;
         }
         if ($meta['dist']) {
             $dist = $meta['dist'];
         }
     } else {
         $os = $proto_role['os'];
     }
     $db->Execute("INSERT INTO roles SET\r\n\t\t\t\tname\t\t\t= ?,\r\n\t\t\t\torigin\t\t\t= ?,\r\n\t\t\t\tclient_id\t\t= ?,\r\n\t\t\t\tenv_id\t\t\t= ?,\r\n\t\t\t\tdescription\t\t= ?,\r\n\t\t\t\tbehaviors\t\t= ?,\r\n\t\t\t\tarchitecture\t= ?,\r\n\t\t\t\tis_stable\t\t= '1',\r\n\t\t\t\thistory\t\t\t= ?,\r\n\t\t\t\tapproval_state\t= ?,\r\n\t\t\t\tgeneration\t\t= ?,\r\n\t\t\t\tos\t\t\t\t= ?,\r\n\t\t\t\tszr_version\t\t= ?\r\n\t\t\t", array($BundleTask->roleName, ROLE_TYPE::CUSTOM, $BundleTask->clientId, $BundleTask->envId, $BundleTask->description, $proto_role['behaviors'], $proto_role['architecture'], trim("{$proto_role['history']},{$proto_role['name']}", ","), APPROVAL_STATE::APPROVED, $DBServer->IsSupported("0.5") ? 2 : 1, $os ? $os : "Unknown", $meta['szr_version']));
     $role_id = $db->Insert_Id();
     $BundleTask->roleId = $role_id;
     $BundleTask->Save();
     $BundleTask->Log(sprintf("Created new role. Role name: %s. Role ID: %s", $BundleTask->roleName, $BundleTask->roleId));
     $role = self::loadById($role_id);
     $behaviors = explode(",", $proto_role['behaviors']);
     foreach ($behaviors as $behavior) {
         $db->Execute("INSERT INTO role_behaviors SET\r\n\t\t\t\t\trole_id\t\t\t= ?,\r\n\t\t\t\t\tbehavior\t\t= ?\r\n\t\t\t\t", array($role_id, $behavior));
     }
     // Set image
     $role->setImage($BundleTask->snapshotId, $BundleTask->platform, $BundleTask->cloudLocation, $meta['szr_version'], $dist->distributor, $dist->codename, $dist->release, $proto_role['architecture']);
     // Set params
     if ($proto_role['id']) {
         $dbParams = $db->GetAll("SELECT name,type,isrequired,defval,allow_multiple_choice,options,hash,issystem\r\n\t\t\t\t\tFROM role_parameters WHERE role_id = ?", array($proto_role['id']));
         $role->setParameters($dbParams);
         $dbSecRules = $db->GetAll("SELECT * FROM role_security_rules WHERE role_id = ?", array($proto_role['id']));
         foreach ($dbSecRules as $dbSecRule) {
             $db->Execute("INSERT INTO role_security_rules SET role_id = ?, rule = ?", array($role_id, $dbSecRule['rule']));
         }
         $props = $db->GetAll("SELECT * FROM role_properties WHERE role_id=?", array($proto_role['id']));
         foreach ($props as $prop) {
             $role->setProperty($prop['name'], $prop['value']);
         }
     } else {
         if ($role->hasBehavior(ROLE_BEHAVIORS::NGINX)) {
             // Add nginx parameter
             $params[] = array('name' => 'Nginx HTTPS Vhost Template', 'type' => 'textarea', 'required' => '1', 'defval' => @file_get_contents(dirname(__FILE__) . "/../templates/services/nginx/ssl.vhost.tpl"));
             $role->setParameters($params);
         }
     }
     // Set software
     if ($meta) {
         $software = array();
         foreach ((array) $meta['software'] as $soft) {
             $software[$soft->name] = $soft->version;
         }
         $role->setSoftware($software);
         $role->setTags((array) $meta['tags']);
         if ($BundleTask->platform == SERVER_PLATFORMS::NIMBULA) {
             $props = array(array('name' => self::PROPERTY_NIMBULA_INIT_ROOT_USER, 'value' => $meta['init_root_user']), array('name' => self::PROPERTY_NIMBULA_INIT_ROOT_PASS, 'value' => $meta['init_root_pass']), array('name' => self::PROPERTY_NIMBULA_ENTRY, 'value' => ''));
             foreach ($props as $prop) {
                 $role->setProperty($prop['name'], $prop['value']);
             }
         }
     }
     return $role;
 }
コード例 #5
0
ファイル: ScalarizrMessaging.php プロジェクト: rickb838/scalr
 private function onHello($message, DBServer $dbserver)
 {
     if ($dbserver->status == SERVER_STATUS::TEMPORARY) {
         $bundleTask = BundleTask::LoadById($dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID));
         $bundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PENDING;
         $bundleTask->Log("Received Hello message from scalarizr on server. Creating image");
         $bundleTask->osFamily = $message->dist->distributor;
         $bundleTask->osName = $message->dist->codename;
         $bundleTask->osVersion = $message->dist->release;
         if (in_array($message->dist->distributor, array('redhat', 'oel', 'scientific')) && $dbserver->platform == SERVER_PLATFORMS::EC2) {
             $bundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
         }
         $bundleTask->save();
     }
     if ($dbserver->status == SERVER_STATUS::IMPORTING) {
         if (!$dbserver->remoteIp || !$dbserver->localIp) {
             if (!$dbserver->remoteIp && $message->remoteIp && $dbserver->platform != SERVER_PLATFORMS::IDCF) {
                 $dbserver->remoteIp = $message->remoteIp;
             }
             if (!$dbserver->localIp && $message->localIp) {
                 $dbserver->localIp = $message->localIp;
             }
             if (!$message->behaviour) {
                 $message->behaviour = array('base');
             }
             if ((!$dbserver->remoteIp || $dbserver->localIp == $dbserver->remoteIp) && $message->messageIpAddress != $dbserver->remoteIp) {
                 $dbserver->remoteIp = $message->messageIpAddress;
             }
         }
         if (count($message->behaviour) == 1 && $message->behaviour[0] == ROLE_BEHAVIORS::CHEF) {
             $message->behaviour[] = ROLE_BEHAVIORS::BASE;
         }
         $dbserver->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR, @implode(",", $message->behaviour));
         $dbserver->save();
         $importVersion = $dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_VERSION);
         if ($importVersion == 2) {
             $dbserver->SetProperties(array(SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
         } else {
             if ($dbserver->isOpenstack()) {
                 $env = $dbserver->GetEnvironmentObject();
                 $os = $env->openstack($dbserver->platform, $dbserver->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
                 $csServer = null;
                 $list = $os->servers->list(true);
                 do {
                     foreach ($list as $_tmp) {
                         $ipaddresses = array();
                         if (!is_array($_tmp->addresses)) {
                             $_tmp->addresses = (array) $_tmp->addresses;
                         }
                         foreach ($_tmp->addresses as $net => $addresses) {
                             foreach ($addresses as $addr) {
                                 if ($addr->version == 4) {
                                     array_push($ipaddresses, $addr->addr);
                                 }
                             }
                         }
                         if ($_tmp->accessIPv4) {
                             array_push($ipaddresses, $_tmp->accessIPv4);
                         }
                         if (in_array($dbserver->localIp, $ipaddresses) || in_array($dbserver->remoteIp, $ipaddresses)) {
                             $osServer = $_tmp;
                         }
                     }
                 } while (false !== ($list = $list->getNextPage()));
                 if (!$osServer) {
                     $this->logger->error(sprintf("Server not found on Openstack (server_id: %s, remote_ip: %s, local_ip: %s)", $dbserver->serverId, $dbserver->remoteIp, $dbserver->localIp));
                     return;
                 }
                 $dbserver->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $osServer->id, OPENSTACK_SERVER_PROPERTIES::NAME => $osServer->name, OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $osServer->image->id, OPENSTACK_SERVER_PROPERTIES::FLAVOR_ID => $osServer->flavor->id, OPENSTACK_SERVER_PROPERTIES::HOST_ID => $osServer->hostId, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
             } elseif ($dbserver->isCloudstack()) {
                 $dbserver->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $message->cloudstack->instanceId, CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $message->cloudstack->availZone, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
             } else {
                 switch ($dbserver->platform) {
                     case SERVER_PLATFORMS::EC2:
                         $dbserver->SetProperties(array(EC2_SERVER_PROPERTIES::AMIID => $message->awsAmiId, EC2_SERVER_PROPERTIES::INSTANCE_ID => $message->awsInstanceId, EC2_SERVER_PROPERTIES::INSTANCE_TYPE => $message->awsInstanceType, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $message->awsAvailZone, EC2_SERVER_PROPERTIES::REGION => substr($message->awsAvailZone, 0, -1), SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                         break;
                     case SERVER_PLATFORMS::EUCALYPTUS:
                         $dbserver->SetProperties(array(EUCA_SERVER_PROPERTIES::EMIID => $message->awsAmiId, EUCA_SERVER_PROPERTIES::INSTANCE_ID => $message->awsInstanceId, EUCA_SERVER_PROPERTIES::INSTANCE_TYPE => $message->awsInstanceType, EUCA_SERVER_PROPERTIES::AVAIL_ZONE => $message->awsAvailZone, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                         break;
                     case SERVER_PLATFORMS::GCE:
                         $dbserver->SetProperties(array(GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $message->{$dbserver->platform}->cloudLocation, GCE_SERVER_PROPERTIES::SERVER_ID => $message->{$dbserver->platform}->serverId, GCE_SERVER_PROPERTIES::SERVER_NAME => $message->{$dbserver->platform}->serverName, GCE_SERVER_PROPERTIES::MACHINE_TYPE => $message->{$dbserver->platform}->machineType, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                         break;
                     case SERVER_PLATFORMS::NIMBULA:
                         $dbserver->SetProperties(array(NIMBULA_SERVER_PROPERTIES::NAME => $message->serverName, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                         break;
                     case SERVER_PLATFORMS::RACKSPACE:
                         $env = $dbserver->GetEnvironmentObject();
                         $cs = Scalr_Service_Cloud_Rackspace::newRackspaceCS($env->getPlatformConfigValue(RackspacePlatformModule::USERNAME, true, $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)), $env->getPlatformConfigValue(RackspacePlatformModule::API_KEY, true, $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)), $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER));
                         $csServer = null;
                         $list = $cs->listServers(true);
                         if ($list) {
                             foreach ($list->servers as $_tmp) {
                                 if ($_tmp->addresses->public && in_array($message->remoteIp, $_tmp->addresses->public)) {
                                     $csServer = $_tmp;
                                 }
                             }
                         }
                         if (!$csServer) {
                             $this->logger->error(sprintf("Server not found on CloudServers (server_id: %s, remote_ip: %s, local_ip: %s)", $dbserver->serverId, $message->remoteIp, $message->localIp));
                             return;
                         }
                         $dbserver->SetProperties(array(RACKSPACE_SERVER_PROPERTIES::SERVER_ID => $csServer->id, RACKSPACE_SERVER_PROPERTIES::NAME => $csServer->name, RACKSPACE_SERVER_PROPERTIES::IMAGE_ID => $csServer->imageId, RACKSPACE_SERVER_PROPERTIES::FLAVOR_ID => $csServer->flavorId, RACKSPACE_SERVER_PROPERTIES::HOST_ID => $csServer->hostId, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                         break;
                 }
             }
         }
         //TODO: search for existing bundle task
         // Bundle image
         $creInfo = new ServerSnapshotCreateInfo($dbserver, $dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME), SERVER_REPLACEMENT_TYPE::NO_REPLACE);
         $bundleTask = BundleTask::Create($creInfo);
         $bundleTask->osFamily = $message->dist->distributor;
         $bundleTask->osName = $message->dist->codename;
         $bundleTask->osVersion = $message->dist->release;
         if (in_array($message->dist->distributor, array('oel', 'redhat', 'scientific')) && $dbserver->platform == SERVER_PLATFORMS::EC2) {
             $bundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
         }
         $bundleTask->setDate("started");
         $bundleTask->createdByEmail = $dbserver->GetProperty(SERVER_PROPERTIES::LAUNCHED_BY_EMAIL);
         $bundleTask->createdById = $dbserver->GetProperty(SERVER_PROPERTIES::LAUNCHED_BY_ID);
         if ($importVersion == 2) {
             $bundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::ESTABLISHING_COMMUNICATION;
         }
         $bundleTask->Save();
         $dbserver->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     }
 }
コード例 #6
0
ファイル: Cloudstack.php プロジェクト: recipe/scalr
 public function CreateServerSnapshot(BundleTask $BundleTask)
 {
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
     $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::CSTACK_DEF;
     $msg = new Scalr_Messaging_Msg_Rebundle($BundleTask->id, $BundleTask->roleName, array());
     if (!$DBServer->SendMessage($msg)) {
         $BundleTask->SnapshotCreationFailed("Cannot send rebundle message to server. Please check event log for more details.");
         return;
     } else {
         $BundleTask->Log(sprintf(_("Snapshot creating initialized (MessageID: %s). Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
     }
     $BundleTask->setDate('started');
     $BundleTask->Save();
 }
コード例 #7
0
ファイル: Roles.php プロジェクト: scalr/scalr
 /**
  * @param   string      $platform
  * @param   string      $architecture
  * @param   JsonData    $behaviors
  * @param   string      $name
  * @param   bool        $createImage
  * @param   string      $imageId
  * @param   string      $cloudLocation
  * @param   string      $osId
  * @param   integer     $hvm
  * @param   JsonData    $advanced
  * @param   JsonData    $chef
  * @throws  Exception
  */
 public function xBuildAction($platform, $architecture, JsonData $behaviors, $name = '', $createImage = false, $imageId, $cloudLocation, $osId, $hvm = 0, JsonData $advanced, JsonData $chef)
 {
     $this->request->restrictAccess(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_BUILD);
     if (!Role::isValidName($name)) {
         throw new Exception(_("Name is incorrect"));
     }
     if (!$createImage) {
         $this->request->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
     }
     if (!$createImage && Role::isNameUsed($name, $this->user->getAccountId(), $this->getEnvironmentId())) {
         throw new Exception('Selected role name is already used. Please select another one.');
     }
     $behaviours = implode(",", array_values($behaviors->getArrayCopy()));
     $os = Os::findPk($osId);
     if (!$os) {
         throw new Exception('Operating system not found.');
     }
     // Create server
     $creInfo = new ServerCreateInfo($platform, null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_IMPORTING_IMAGE_ID => $imageId, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.13.0", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => "mysql", SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $advanced['scalrbranch'], SERVER_PROPERTIES::ARCHITECTURE => $architecture, SERVER_PROPERTIES::SZR_IMPORTING_LEAVE_ON_FAIL => $advanced['dontterminatefailed'] == 'on' ? 1 : 0, SERVER_PROPERTIES::SZR_IMPORTING_CHEF_SERVER_ID => $chef['chef.server'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ENVIRONMENT => $chef['chef.environment'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME => $chef['chef.role']));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->imageId = $imageId;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $cloudLocation;
     $launchOptions->architecture = $architecture;
     $platformObj = PlatformFactory::NewPlatform($platform);
     switch ($platform) {
         case SERVER_PLATFORMS::IDCF:
             $launchOptions->serverType = 24;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_US:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_UK:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::EC2:
             if ($cloudLocation == Aws::REGION_AP_NORTHEAST_2) {
                 if ($hvm == 1 || $this->isHvmBundleTypeOs($os)) {
                     $launchOptions->serverType = 't2.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 }
             } else {
                 if ($hvm == 1) {
                     $launchOptions->serverType = "m3.xlarge";
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } else {
                     $launchOptions->serverType = "m3.large";
                     if ($this->isHvmBundleTypeOs($os)) {
                         $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                     }
                     if ($os->family == 'oel' && $os->generation == '5') {
                         $launchOptions->serverType = "m1.large";
                     }
                 }
             }
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
         case SERVER_PLATFORMS::GCE:
             $launchOptions->serverType = 'n1-standard-1';
             $location = null;
             $locations = array_keys($platformObj->getLocations($this->environment));
             while (count($locations) != 0) {
                 $location = array_shift($locations);
                 if (strstr($location, "us-")) {
                     break;
                 }
             }
             $launchOptions->cloudLocation = $locations[0];
             $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::GCE_STORAGE;
             break;
     }
     if ($advanced['servertype']) {
         $launchOptions->serverType = $advanced['servertype'];
     }
     if ($advanced['availzone']) {
         $launchOptions->availZone = $advanced['availzone'];
     }
     if ($advanced['region']) {
         $launchOptions->cloudLocation = $advanced['region'];
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $name, SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     if ($bundleType) {
         $bundleTask->bundleType = $bundleType;
     }
     $bundleTask->createdById = $this->user->id;
     $bundleTask->createdByEmail = $this->user->getEmail();
     $bundleTask->osFamily = $os->family;
     $bundleTask->object = $createImage ? BundleTask::BUNDLETASK_OBJECT_IMAGE : BundleTask::BUNDLETASK_OBJECT_ROLE;
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         $platformObj->LaunchServer($dbServer, $launchOptions);
         $dbServer->Save();
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('serverId' => $dbServer->serverId, 'bundleTaskId' => $bundleTask->id));
 }
コード例 #8
0
 public function StartThread($bundle_task_info)
 {
     $db = Core::GetDBInstance();
     // Reconfigure observers;
     Scalr::ReconfigureObservers();
     $BundleTask = BundleTask::LoadById($bundle_task_info['id']);
     try {
         $DBServer = DBServer::LoadByID($BundleTask->serverId);
     } catch (ServerNotFoundException $e) {
         if (!$BundleTask->snapshotId) {
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::FAILED;
             $BundleTask->setDate('finished');
             $BundleTask->failureReason = sprintf(_("Server '%s' was terminated during snapshot creation process"), $BundleTask->serverId);
             $BundleTask->Save();
             return;
         }
     } catch (Exception $e) {
         //$this->Logger->error($e->getMessage());
     }
     switch ($BundleTask->status) {
         case SERVER_SNAPSHOT_CREATION_STATUS::STARING_SERVER:
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV:
         case SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE:
             if (!PlatformFactory::NewPlatform($DBServer->platform)->IsServerExists($DBServer)) {
                 $DBServer->status = SERVER_STATUS::TERMINATED;
                 $DBServer->save();
                 $BundleTask->SnapshotCreationFailed("Server was terminated and no longer available in cloud.");
                 exit;
             }
             // IF server is in pensing state
             $status = PlatformFactory::NewPlatform($DBServer->platform)->GetServerRealStatus($DBServer);
             $BundleTask->Log(sprintf(_("Server status: %s"), $status->getName()));
             if ($status->isPending()) {
                 $BundleTask->Log(sprintf(_("Waiting for running state."), $status->getName()));
                 exit;
             } elseif ($status->isTerminated()) {
                 $DBServer->status = SERVER_STATUS::TERMINATED;
                 $DBServer->save();
                 $BundleTask->SnapshotCreationFailed("Server was terminated and no longer available in cloud.");
                 exit;
             }
             break;
     }
     switch ($BundleTask->status) {
         case SERVER_SNAPSHOT_CREATION_STATUS::STARING_SERVER:
             $ips = PlatformFactory::NewPlatform($DBServer->platform)->GetServerIPAddresses($DBServer);
             $DBServer->remoteIp = $ips['remoteIp'];
             $DBServer->localIp = $ips['locateIp'];
             $DBServer->save();
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV;
             $BundleTask->save();
             $BundleTask->Log(sprintf(_("Bundle task status: %s"), $BundleTask->status));
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING_ENV:
             $BundleTask->Log(sprintf(_("Initializing SSH2 session to the server")));
             try {
                 $ssh2Client = $DBServer->GetSsh2Client();
                 $ssh2Client->connect($DBServer->remoteIp, 22);
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scalr unable to establish SSH connection with server on %:%. Error: %s"), $DBServer->remoteIp, 22, $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             //Prepare script
             $BundleTask->Log(sprintf(_("Uploading builder scripts...")));
             $behaviors = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR);
             try {
                 $options = array('server-id' => $DBServer->serverId, 'role-name' => $BundleTask->roleName, 'crypto-key' => $DBServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 'platform' => $DBServer->platform, 'behaviour' => trim(str_replace("base", "", $behaviors)), 'queryenv-url' => CONFIG::$HTTP_PROTO . "://" . CONFIG::$EVENTHANDLER_URL . "/query-env", 'messaging-p2p.producer-url' => CONFIG::$HTTP_PROTO . "://" . CONFIG::$EVENTHANDLER_URL . "/messaging");
                 $command = 'scalarizr --import -y';
                 foreach ($options as $k => $v) {
                     $command .= sprintf(' -o %s=%s', $k, $v);
                 }
                 if ($DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE) == 'percona') {
                     $recipes = 'mysql=percona';
                 } else {
                     $recipes = '';
                 }
                 $scalarizrBranch = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH);
                 $scriptContents = @file_get_contents(APPPATH . "/templates/services/role_builder/chef_import.tpl");
                 $scriptContents = str_replace(array("%PLATFORM%", "%BEHAVIOURS%", "%SZR_IMPORT_STRING%", "%DEV%", "%SCALARIZR_BRANCH%", "%RECIPES%", "%BUILD_ONLY%", "%CHEF_SERVER_URL%", "%CHEF_VALIDATOR_NAME%", "%CHEF_VALIDATOR_KEY%", "%CHEF_ENVIRONMENT%", "%CHEF_ROLE%", "%CHEF_NODE_NAME%", "\r\n"), array($DBServer->platform, trim(str_replace("base", "", str_replace(",", " ", $behaviors))), $command, $scalarizrBranch ? '1' : '0', $scalarizrBranch, $recipes, '0', '', '', '', '', '', '', "\n"), $scriptContents);
                 if (!$ssh2Client->sendFile('/tmp/scalr-builder.sh', $scriptContents, "w+", false)) {
                     throw new Exception("Cannot upload script");
                 }
                 $BundleTask->Log(sprintf(_("Uploading chef recipes...")));
                 if (!$ssh2Client->sendFile('/tmp/recipes.tar.gz', APPPATH . '/www/storage/chef/recipes.tar.gz')) {
                     throw new Exception("Cannot upload chef recipes");
                 }
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scripts upload failed: %s"), $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             $BundleTask->Log("Launching role builder routines on server");
             $ssh2Client->exec("chmod 0777 /tmp/scalr-builder.sh");
             $ssh2Client->exec("setsid /tmp/scalr-builder.sh > /var/log/role-builder-output.log 2>&1 &");
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE;
             $BundleTask->save();
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::INTALLING_SOFTWARE:
             try {
                 $ssh2Client = $DBServer->GetSsh2Client();
                 $ssh2Client->connect($DBServer->remoteIp, 22);
             } catch (Exception $e) {
                 $BundleTask->Log(sprintf(_("Scalr unable to establish SSH connection with server on %:%. Error: %s"), $DBServer->remoteIp, 22, $e->getMessage()));
                 //TODO: Set status of bundle log to failed
                 exit;
             }
             $log = $ssh2Client->getFile('/var/log/role-builder-output.log');
             $log_lines = explode("\r\n", $log);
             $last_msg = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_LAST_LOG_MESSAGE);
             while ($msg = trim(array_shift($log_lines))) {
                 if (substr($msg, -1, 1) != ']') {
                     continue;
                 }
                 if ($last_msg) {
                     if ($msg != $last_msg) {
                         continue;
                     } elseif ($msg == $last_msg) {
                         $last_msg = null;
                         continue;
                     }
                 }
                 if (stristr($msg, '[ Failed ]')) {
                     $stepLog = $ssh2Client->getFile('/var/log/role-builder-step.log');
                     $BundleTask->Log(sprintf("role-builder-step.log: %s", $stepLog));
                     $BundleTask->SnapshotCreationFailed($msg);
                     /** Terminate server **/
                     PlatformFactory::NewPlatform($DBServer->platform)->TerminateServer($DBServer);
                     $DBServer->status = SERVER_STATUS::PENDING_TERMINATE;
                     $DBServer->save();
                     $BundleTask->Log(sprintf("Temporary server '%s' (%s) has been terminated", $DBServer->serverId, $DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID)));
                 } else {
                     $BundleTask->Log($msg);
                     $DBServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_LAST_LOG_MESSAGE, $msg);
                 }
             }
             //Read /var/log/role-builder-output.log
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PENDING:
             try {
                 $platformModule = PlatformFactory::NewPlatform($BundleTask->platform);
                 $platformModule->CreateServerSnapshot($BundleTask);
             } catch (Exception $e) {
                 Logger::getLogger(LOG_CATEGORY::BUNDLE)->error($e->getMessage());
                 $BundleTask->SnapshotCreationFailed($e->getMessage());
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::PREPARING:
             $addedTime = strtotime($BundleTask->dateAdded);
             if ($addedTime + 3600 < time()) {
                 $BundleTask->SnapshotCreationFailed("Server didn't send PrepareBundleResult message in time.");
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS:
             PlatformFactory::NewPlatform($BundleTask->platform)->CheckServerSnapshotStatus($BundleTask);
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS:
             $r_farm_roles = array();
             $BundleTask->Log(sprintf("Bundle task replacement type: %s", $BundleTask->replaceType));
             try {
                 $DBFarm = DBFarm::LoadByID($BundleTask->farmId);
             } catch (Exception $e) {
                 if (stristr($e->getMessage(), "not found in database")) {
                     $BundleTask->SnapshotCreationFailed("Farm was removed before task was finished");
                 }
                 return;
             }
             if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_FARM) {
                 try {
                     $r_farm_roles[] = $DBFarm->GetFarmRoleByRoleID($BundleTask->prototypeRoleId);
                 } catch (Exception $e) {
                 }
             } elseif ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                 $farm_roles = $db->GetAll("SELECT id FROM farm_roles WHERE role_id=? AND new_role_id=? AND farmid IN (SELECT id FROM farms WHERE env_id=?)", array($BundleTask->prototypeRoleId, $BundleTask->roleId, $BundleTask->envId));
                 foreach ($farm_roles as $farm_role) {
                     try {
                         $r_farm_roles[] = DBFarmRole::LoadByID($farm_role['id']);
                     } catch (Exception $e) {
                     }
                 }
             }
             $update_farm_dns_zones = array();
             $completed_roles = 0;
             foreach ($r_farm_roles as $DBFarmRole) {
                 if ($DBFarmRole->CloudLocation != $BundleTask->cloudLocation) {
                     $BundleTask->Log(sprintf("Role '%s' (ID: %s), farm '%s' (ID: %s) using the same role but in abother cloud location. Skiping it.", $DBFarmRole->GetRoleObject()->name, $DBFarmRole->ID, $DBFarmRole->GetFarmObject()->Name, $DBFarmRole->FarmID));
                     $completed_roles++;
                 } else {
                     $servers = $db->GetAll("SELECT server_id FROM servers WHERE farm_roleid = ? AND role_id=? AND status NOT IN (?,?)", array($DBFarmRole->ID, $DBFarmRole->RoleID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE));
                     $BundleTask->Log(sprintf("Found %s servers that need to be replaced with new ones. Role '%s' (ID: %s), farm '%s' (ID: %s)", count($servers), $DBFarmRole->GetRoleObject()->name, $DBFarmRole->ID, $DBFarmRole->GetFarmObject()->Name, $DBFarmRole->FarmID));
                     if (count($servers) == 0) {
                         $DBFarmRole->RoleID = $DBFarmRole->NewRoleID;
                         $DBFarmRole->NewRoleID = null;
                         $DBFarmRole->Save();
                         $update_farm_dns_zones[$DBFarmRole->FarmID] = 1;
                         $completed_roles++;
                     } else {
                         $metaData = $BundleTask->getSnapshotDetails();
                         foreach ($servers as $server) {
                             try {
                                 $DBServer = DBServer::LoadByID($server['server_id']);
                             } catch (Exception $e) {
                                 //TODO:
                                 continue;
                             }
                             if ($DBServer->serverId == $BundleTask->serverId || $metaData['noServersReplace']) {
                                 $DBServer->roleId = $BundleTask->roleId;
                                 $DBServer->Save();
                                 if ($metaData['noServersReplace']) {
                                     $BundleTask->Log(sprintf("'Do not replace servers' option was checked. Server '%s' won't be replaced to new image.", $DBServer->serverId));
                                 } else {
                                     $BundleTask->Log(sprintf("Server '%s', on which snapshot has been taken, already has all modifications. No need to replace it.", $DBServer->serverId));
                                 }
                                 if ($DBServer->GetFarmObject()->Status == FARM_STATUS::SYNCHRONIZING) {
                                     PlatformFactory::NewPlatform($DBServer->platform)->TerminateServer($DBServer);
                                     $db->Execute("UPDATE servers_history SET\r\n\t\t\t\t\t\t\t\t\t\t\t\tdtterminated\t= NOW(),\r\n\t\t\t\t\t\t\t\t\t\t\t\tterminate_reason\t= ?\r\n\t\t\t\t\t\t\t\t\t\t\t\tWHERE server_id = ?\r\n\t\t\t\t\t\t\t\t\t\t\t", array(sprintf("Farm was in 'Synchronizing' state. Server terminated when bundling was completed. Bundle task #%s", $BundleTask->id), $DBServer->serverId));
                                 }
                             } else {
                                 if (!$db->GetOne("SELECT server_id FROM servers WHERE replace_server_id=? AND status NOT IN (?,?)", array($DBServer->serverId, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE))) {
                                     $ServerCreateInfo = new ServerCreateInfo($DBFarmRole->Platform, $DBFarmRole, $DBServer->index, $DBFarmRole->NewRoleID);
                                     $nDBServer = Scalr::LaunchServer($ServerCreateInfo);
                                     $nDBServer->replaceServerID = $DBServer->serverId;
                                     $nDBServer->Save();
                                     $BundleTask->Log(sprintf(_("Started new server %s to replace server %s"), $nDBServer->serverId, $DBServer->serverId));
                                 }
                             }
                             // if serverid != bundletask->serverID
                         }
                         // foreach server
                     }
                     // count($servers)
                 }
             }
             if ($completed_roles == count($r_farm_roles)) {
                 $BundleTask->Log(sprintf(_("No servers with old role. Replacement complete. Bundle task complete."), SERVER_REPLACEMENT_TYPE::NO_REPLACE, SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS));
                 $BundleTask->setDate('finished');
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                 $BundleTask->Save();
             }
             try {
                 if (count($update_farm_dns_zones) != 0) {
                     foreach ($update_farm_dns_zones as $farm_id => $v) {
                         $dnsZones = DBDNSZone::loadByFarmId($farm_id);
                         foreach ($dnsZones as $dnsZone) {
                             if ($dnsZone->status != DNS_ZONE_STATUS::INACTIVE && $dnsZone->status != DNS_ZONE_STATUS::PENDING_DELETE) {
                                 $dnsZone->updateSystemRecords();
                                 $dnsZone->save();
                             }
                         }
                     }
                 }
             } catch (Exception $e) {
                 $this->Logger->fatal("DNS ZONE: {$e->getMessage()}");
             }
             break;
         case SERVER_SNAPSHOT_CREATION_STATUS::CREATING_ROLE:
             try {
                 if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                     $saveOldRole = false;
                     try {
                         $dbRole = DBRole::loadById($DBServer->roleId);
                         if ($dbRole->name == $BundleTask->roleName && $dbRole->envId == $BundleTask->envId) {
                             $saveOldRole = true;
                         }
                     } catch (Exception $e) {
                         //NO OLD ROLE
                     }
                     if ($dbRole && $saveOldRole) {
                         if ($DBServer) {
                             $new_role_name = BundleTask::GenerateRoleName($DBServer->GetFarmRoleObject(), $DBServer);
                         } else {
                             $new_role_name = $BundleTask->roleName . "-" . rand(1000, 9999);
                         }
                         $dbRole->name = $new_role_name;
                         $BundleTask->Log(sprintf(_("Old role '%s' (ID: %s) renamed to '%s'"), $BundleTask->roleName, $dbRole->id, $new_role_name));
                         $dbRole->save();
                     } else {
                         //TODO:
                         //$this->Logger->error("dbRole->replace->fail({$BundleTask->roleName}, {$BundleTask->envId})");
                     }
                 }
                 try {
                     $DBRole = DBRole::createFromBundleTask($BundleTask);
                 } catch (Exception $e) {
                     $BundleTask->SnapshotCreationFailed("Role creation failed due to internal error ({$e->getMessage()}). Please try again.");
                     return;
                 }
                 if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::NO_REPLACE) {
                     $BundleTask->setDate('finished');
                     $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                     $BundleTask->Log(sprintf(_("Replacement type: %s. Bundle task status: %s"), SERVER_REPLACEMENT_TYPE::NO_REPLACE, SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS));
                     try {
                         $DBServer = DBServer::LoadByID($BundleTask->serverId);
                         if ($DBServer->status == SERVER_STATUS::IMPORTING) {
                             if ($DBServer->farmId) {
                                 // Create DBFarmRole object
                                 // TODO: create DBFarm role
                             }
                             //$DBServer->Delete();
                         }
                     } catch (Exception $e) {
                     }
                 } else {
                     try {
                         $BundleTask->Log(sprintf(_("Replacement type: %s. Bundle task status: %s"), $BundleTask->replaceType, SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS));
                         if ($BundleTask->replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_FARM) {
                             $DBFarm = DBFarm::LoadByID($BundleTask->farmId);
                             $DBFarmRole = $DBFarm->GetFarmRoleByRoleID($BundleTask->prototypeRoleId);
                             $DBFarmRole->NewRoleID = $BundleTask->roleId;
                             $DBFarmRole->Save();
                         } else {
                             $farm_roles = $db->GetAll("SELECT id FROM farm_roles WHERE role_id=? AND farmid IN (SELECT id FROM farms WHERE env_id=?)", array($BundleTask->prototypeRoleId, $BundleTask->envId));
                             foreach ($farm_roles as $farm_role) {
                                 $DBFarmRole = DBFarmRole::LoadByID($farm_role['id']);
                                 $DBFarmRole->NewRoleID = $BundleTask->roleId;
                                 $DBFarmRole->Save();
                             }
                         }
                         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::REPLACING_SERVERS;
                     } catch (Exception $e) {
                         $this->Logger->error($e->getMessage());
                         $BundleTask->Log(sprintf(_("Server replacement failed: %s"), $e->getMessage()));
                         $BundleTask->setDate('finished');
                         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::SUCCESS;
                     }
                 }
                 $BundleTask->Save();
             } catch (Exception $e) {
                 $this->Logger->error($e->getMessage());
             }
             break;
     }
 }
コード例 #9
0
 private function onHello($message, DBServer $dbserver)
 {
     if ($dbserver->status == SERVER_STATUS::TEMPORARY) {
         $bundleTask = BundleTask::LoadById($dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID));
         $bundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PENDING;
         $bundleTask->Log("Received Hello message from scalarizr on server. Creating image");
         $bundleTask->save();
     }
     if ($dbserver->status == SERVER_STATUS::IMPORTING) {
         switch ($dbserver->platform) {
             case SERVER_PLATFORMS::EC2:
                 $dbserver->SetProperties(array(EC2_SERVER_PROPERTIES::AMIID => $message->awsAmiId, EC2_SERVER_PROPERTIES::INSTANCE_ID => $message->awsInstanceId, EC2_SERVER_PROPERTIES::INSTANCE_TYPE => $message->awsInstanceType, EC2_SERVER_PROPERTIES::AVAIL_ZONE => $message->awsAvailZone, EC2_SERVER_PROPERTIES::REGION => substr($message->awsAvailZone, 0, -1), SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                 break;
             case SERVER_PLATFORMS::EUCALYPTUS:
                 $dbserver->SetProperties(array(EUCA_SERVER_PROPERTIES::EMIID => $message->awsAmiId, EUCA_SERVER_PROPERTIES::INSTANCE_ID => $message->awsInstanceId, EUCA_SERVER_PROPERTIES::INSTANCE_TYPE => $message->awsInstanceType, EUCA_SERVER_PROPERTIES::AVAIL_ZONE => $message->awsAvailZone, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                 break;
             case SERVER_PLATFORMS::NIMBULA:
                 $dbserver->SetProperties(array(NIMBULA_SERVER_PROPERTIES::NAME => $message->serverName, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                 break;
             case SERVER_PLATFORMS::CLOUDSTACK:
                 $dbserver->SetProperties(array(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID => $message->cloudstack->instanceId, CLOUDSTACK_SERVER_PROPERTIES::CLOUD_LOCATION => $message->cloudstack->availZone, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                 break;
             case SERVER_PLATFORMS::RACKSPACE:
                 $env = $dbserver->GetEnvironmentObject();
                 $cs = Scalr_Service_Cloud_Rackspace::newRackspaceCS($env->getPlatformConfigValue(Modules_Platforms_Rackspace::USERNAME, true, $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)), $env->getPlatformConfigValue(Modules_Platforms_Rackspace::API_KEY, true, $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER)), $dbserver->GetProperty(RACKSPACE_SERVER_PROPERTIES::DATACENTER));
                 $csServer = null;
                 $list = $cs->listServers(true);
                 if ($list) {
                     foreach ($list->servers as $_tmp) {
                         if ($_tmp->addresses->public && in_array($message->remoteIp, $_tmp->addresses->public)) {
                             $csServer = $_tmp;
                         }
                     }
                 }
                 if (!$csServer) {
                     $this->logger->error(sprintf("Server not found on CloudServers (server_id: %s, remote_ip: %s, local_ip: %s)", $dbserver->serverId, $message->remoteIp, $message->localIp));
                     return;
                 }
                 $dbserver->SetProperties(array(RACKSPACE_SERVER_PROPERTIES::SERVER_ID => $csServer->id, RACKSPACE_SERVER_PROPERTIES::NAME => $csServer->name, RACKSPACE_SERVER_PROPERTIES::IMAGE_ID => $csServer->imageId, RACKSPACE_SERVER_PROPERTIES::FLAVOR_ID => $csServer->flavorId, RACKSPACE_SERVER_PROPERTIES::HOST_ID => $csServer->hostId, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                 break;
             case SERVER_PLATFORMS::OPENSTACK:
                 $env = $dbserver->GetEnvironmentObject();
                 $os = Scalr_Service_Cloud_Openstack::newNovaCC($env->getPlatformConfigValue(Modules_Platforms_Openstack::API_URL, true, $dbserver->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)), $env->getPlatformConfigValue(Modules_Platforms_Openstack::USERNAME, true, $dbserver->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)), $env->getPlatformConfigValue(Modules_Platforms_Openstack::API_KEY, true, $dbserver->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)), $env->getPlatformConfigValue(Modules_Platforms_Openstack::PROJECT_NAME, true, $dbserver->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION)));
                 $csServer = null;
                 $list = $os->serversList(true);
                 if ($list) {
                     foreach ($list->servers as $_tmp) {
                         $ipaddresses = array();
                         if ($_tmp->addresses->private) {
                             foreach ($_tmp->addresses->private as $addr) {
                                 if ($addr->version == 4) {
                                     array_push($ipaddresses, $addr->addr);
                                 }
                             }
                         }
                         if ($_tmp->addresses->internet) {
                             foreach ($_tmp->addresses->internet as $addr) {
                                 if ($addr->version == 4) {
                                     array_push($ipaddresses, $addr->addr);
                                 }
                             }
                         }
                         if (in_array($message->localIp, $ipaddresses) || in_array($message->remoteIp, $ipaddresses)) {
                             $osServer = $_tmp;
                         }
                     }
                 }
                 if (!$osServer) {
                     $this->logger->error(sprintf("Server not found on Openstack (server_id: %s, remote_ip: %s, local_ip: %s)", $dbserver->serverId, $message->remoteIp, $message->localIp));
                     return;
                 }
                 $dbserver->SetProperties(array(OPENSTACK_SERVER_PROPERTIES::SERVER_ID => $osServer->id, OPENSTACK_SERVER_PROPERTIES::NAME => $osServer->name, OPENSTACK_SERVER_PROPERTIES::IMAGE_ID => $osServer->image->id, OPENSTACK_SERVER_PROPERTIES::FLAVOR_ID => $osServer->flavor->id, OPENSTACK_SERVER_PROPERTIES::HOST_ID => $osServer->hostId, SERVER_PROPERTIES::ARCHITECTURE => $message->architecture));
                 break;
         }
         // Bundle image
         $creInfo = new ServerSnapshotCreateInfo($dbserver, $dbserver->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_ROLE_NAME), SERVER_REPLACEMENT_TYPE::NO_REPLACE);
         $bundleTask = BundleTask::Create($creInfo);
     }
 }
コード例 #10
0
ファイル: Servers.php プロジェクト: rakesh-mohanta/scalr
 public function xServerCreateSnapshotAction()
 {
     $this->request->defineParams(array('rootVolumeSize' => array('type' => 'int')));
     if (!$this->getParam('serverId')) {
         throw new Exception(_('Server not found'));
     }
     $dbServer = DBServer::LoadByID($this->getParam('serverId'));
     $this->user->getPermissions()->validate($dbServer);
     $err = array();
     if (strlen($this->getParam('roleName')) < 3) {
         $err[] = _("Role name should be greater than 3 chars");
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         $err[] = _("Role name is incorrect");
     }
     $roleinfo = $this->db->GetRow("SELECT * FROM roles WHERE name=? AND (env_id=? OR env_id='0')", array($this->getParam('roleName'), $dbServer->envId, $dbServer->roleId));
     if ($this->getParam('replaceType') != SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
         if ($roleinfo && $roleinfo['id'] != $dbServer->roleId) {
             $err[] = _("Specified role name is already used by another role. You can use this role name only if you will replace old on on ALL your farms.");
         }
     } else {
         if ($roleinfo && $roleinfo['env_id'] == 0) {
             $err[] = _("Selected role name is reserved and cannot be used for custom role");
         }
     }
     //Check for already running bundle on selected instance
     $chk = $this->db->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed')", array($dbServer->serverId));
     if ($chk) {
         $err[] = sprintf(_("Server '%s' is already synchonizing."), $dbServer->serverId);
     }
     //Check is role already synchronizing...
     $chk = $this->db->GetOne("SELECT server_id FROM bundle_tasks WHERE prototype_role_id=? AND status NOT IN ('success', 'failed')", array($dbServer->roleId));
     if ($chk && $chk != $dbServer->serverId) {
         try {
             $bDBServer = DBServer::LoadByID($chk);
             if ($bDBServer->farmId == $DBServer->farmId) {
                 $err[] = sprintf(_("Role '%s' is already synchonizing."), $dbServer->GetFarmRoleObject()->GetRoleObject()->name);
             }
         } catch (Exception $e) {
         }
     }
     if ($dbServer->GetFarmRoleObject()->NewRoleID) {
         $err[] = sprintf(_("Role '%s' is already synchonizing."), $dbServer->GetFarmRoleObject()->GetRoleObject()->name);
     }
     if (count($err)) {
         throw new Exception(nl2br(implode('\\n', $err)));
     }
     $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo($dbServer, $this->getParam('roleName'), $this->getParam('replaceType'), false, $this->getParam('roleDescription'), $this->getParam('rootVolumeSize'), $this->getParam('noServersReplace') == 'on' ? true : false);
     $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
     $this->response->success("Bundle task successfully created. <a href='#/bundletasks/{$BundleTask->id}/logs'>Click here to check status.</a>");
 }
コード例 #11
0
 public function ServerImageCreate($ServerID, $RoleName)
 {
     $this->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE);
     $DBServer = DBServer::LoadByID($ServerID);
     // Validate client and server
     if ($DBServer->envId != $this->Environment->id) {
         throw new Exception(sprintf("Server ID #%s not found", $ServerID));
     }
     $this->user->getPermissions()->validate($DBServer);
     //Check for already running bundle on selected instance
     $chk = $this->DB->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($ServerID));
     if ($chk) {
         throw new Exception(sprintf(_("Server '%s' is already synchonizing."), $ServerID));
     }
     //Check is role already synchronizing...
     $chk = $this->DB->GetOne("SELECT server_id FROM bundle_tasks WHERE prototype_role_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($DBServer->GetFarmRoleObject()->RoleID));
     if ($chk && $chk != $DBServer->serverId) {
         try {
             $bDBServer = DBServer::LoadByID($chk);
             if ($bDBServer->farmId == $DBServer->farmId) {
                 throw new Exception(sprintf(_("Role '%s' is already synchonizing."), $DBServer->GetFarmRoleObject()->GetRoleObject()->name));
             }
         } catch (Exception $e) {
         }
     }
     try {
         $DBRole = DBRole::loadByFilter(array("name" => $RoleName, "env_id" => $DBServer->envId));
     } catch (Exception $e) {
     }
     if (!$DBRole) {
         $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo($DBServer, $RoleName, SERVER_REPLACEMENT_TYPE::NO_REPLACE, BundleTask::BUNDLETASK_OBJECT_ROLE, 'Bundled via API');
         $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
         $BundleTask->createdById = $this->user->id;
         $BundleTask->createdByEmail = $this->user->getEmail();
         $BundleTask->save();
         $response = $this->CreateInitialResponse();
         $response->BundleTaskID = $BundleTask->id;
         return $response;
     } else {
         throw new Exception(_("Specified role name is already used by another role"));
     }
 }
コード例 #12
0
 /**
  * Called when instance going down
  *
  * @param HostDownEvent $event
  */
 public function OnHostDown(HostDownEvent $event)
 {
     if ($event->DBServer->IsRebooting()) {
         return;
     }
     //         if ($event->DBServer->status != SERVER_STATUS::TROUBLESHOOTING) {
     //             $event->DBServer->status = SERVER_STATUS::TERMINATED;
     //             $event->DBServer->dateShutdownScheduled = date("Y-m-d H:i:s");
     //         }
     $this->DB->Execute("UPDATE servers_history SET scu_collecting = '0' WHERE server_id = ?", array($event->DBServer->serverId));
     //TODO: move to alerts;
     $this->DB->Execute("UPDATE server_alerts SET status='resolved' WHERE server_id = ?", array($event->DBServer->serverId));
     try {
         $DBFarmRole = $event->DBServer->GetFarmRoleObject();
         if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_BCP_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_IS_BCP_RUNNING, 0, DBFarmRole::TYPE_LCL);
         }
         if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_BUNDLE_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_IS_BUNDLE_RUNNING, 0, DBFarmRole::TYPE_LCL);
         }
         if ($DBFarmRole->GetSetting(Scalr_Db_Msr::DATA_BACKUP_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(Scalr_Db_Msr::DATA_BACKUP_IS_RUNNING, 0, DBFarmRole::TYPE_LCL);
         }
         if ($DBFarmRole->GetSetting(Scalr_Db_Msr::DATA_BUNDLE_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, 0, DBFarmRole::TYPE_LCL);
         }
     } catch (Exception $e) {
     }
     if ($event->replacementDBServer) {
         $event->replacementDBServer->replaceServerID = null;
         $event->replacementDBServer->Save();
     }
     //Check active bundle task:
     $bundle_task_id = $this->DB->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status IN (?,?) LIMIT 1", array($event->DBServer->serverId, SERVER_SNAPSHOT_CREATION_STATUS::PENDING, SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS));
     if ($bundle_task_id) {
         $BundleTask = BundleTask::LoadById($bundle_task_id);
         $BundleTask->SnapshotCreationFailed("Server was terminated before image was created.");
     }
 }
コード例 #13
0
ファイル: Servers.php プロジェクト: mheydt/scalr
 /**
  * @param   string  $serverId
  * @param   string  $name
  * @param   string  $description
  * @param   bool    $createRole
  * @param   string  $replaceRole
  * @param   bool    $replaceImage
  * @param   int     $rootVolumeSize
  * @param   string  $rootVolumeType
  * @param   int     $rootVolumeIops
  * @throws Exception
  */
 public function xServerCreateSnapshotAction($serverId, $name = '', $description = '', $createRole = false, $replaceRole = '', $replaceImage = false, $rootVolumeSize = 0, $rootVolumeType = '', $rootVolumeIops = 0)
 {
     $this->request->restrictAccess(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE);
     if (!$serverId) {
         throw new Exception('Server not found');
     }
     $dbServer = DBServer::LoadByID($serverId);
     $this->user->getPermissions()->validate($dbServer);
     $errorMsg = [];
     //Check for already running bundle on selected instance
     $chk = $this->db->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($dbServer->serverId));
     if ($chk) {
         $errorMsg[] = sprintf(_("Server '%s' is already synchonizing."), $dbServer->serverId);
     }
     //Check is role already synchronizing...
     $chk = $this->db->GetOne("SELECT server_id FROM bundle_tasks WHERE prototype_role_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($dbServer->GetFarmRoleObject()->RoleID));
     if ($chk && $chk != $dbServer->serverId) {
         try {
             $bDBServer = DBServer::LoadByID($chk);
             if ($bDBServer->farmId == $dbServer->farmId) {
                 $errorMsg[] = sprintf(_("Role '%s' is already synchronizing."), $dbServer->GetFarmRoleObject()->GetRoleObject()->name);
             }
         } catch (Exception $e) {
         }
     }
     if (!empty($errorMsg)) {
         throw new Exception(implode('\\n', $errorMsg));
     }
     $validator = new \Scalr\UI\Request\Validator();
     $validator->addErrorIf(strlen($name) < 3, 'name', _("Role name should be greater than 3 chars"));
     $validator->addErrorIf(!preg_match("/^[A-Za-z0-9-]+\$/si", $name), 'name', _("Role name is incorrect"));
     $validator->addErrorIf(!in_array($replaceRole, ['farm', 'all', '']), 'replaceRole', 'Invalid value');
     $object = $createRole ? BundleTask::BUNDLETASK_OBJECT_ROLE : BundleTask::BUNDLETASK_OBJECT_IMAGE;
     $replaceType = SERVER_REPLACEMENT_TYPE::NO_REPLACE;
     if ($createRole) {
         $this->request->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
         if ($replaceRole == 'farm') {
             $this->request->restrictFarmAccess($dbServer->GetFarmObject(), Acl::PERM_FARMS_MANAGE);
             $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_FARM;
         } else {
             if ($replaceRole == 'all') {
                 $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE);
                 $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_ALL;
             }
         }
     } else {
         $scope = $dbServer->GetFarmRoleObject()->GetRoleObject()->__getNewRoleObject()->getScope();
         if ($replaceImage && ($scope == ScopeInterface::SCOPE_ENVIRONMENT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE) || $scope == ScopeInterface::SCOPE_ACCOUNT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ACCOUNT, Acl::PERM_ROLES_ACCOUNT_MANAGE))) {
             $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_ALL;
         }
     }
     if ($createRole) {
         $roleInfo = $this->db->GetRow("SELECT * FROM roles WHERE name=? AND (client_id IS NULL OR client_id = ? AND env_id IS NULL OR env_id=?) LIMIT 1", array($name, $dbServer->clientId, $dbServer->envId, $dbServer->GetFarmRoleObject()->RoleID));
         if ($roleInfo) {
             if (empty($roleInfo['client_id'])) {
                 $validator->addError('name', _("Selected role name is reserved and cannot be used for custom role"));
             } else {
                 if ($replaceType != SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                     $validator->addError('name', _("Specified role name is already used by another role. You can use this role name only if you will replace old one on ALL your farms."));
                 } else {
                     if ($replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL && $roleInfo['id'] != $dbServer->GetFarmRoleObject()->RoleID) {
                         $validator->addError('name', _("This Role name is already in use. You cannot replace a Role different from the one you are currently snapshotting."));
                     }
                 }
             }
         }
     }
     $roleImage = $dbServer->GetFarmRoleObject()->GetRoleObject()->__getNewRoleObject()->getImage($dbServer->platform, $dbServer->GetCloudLocation());
     $rootBlockDevice = [];
     if ($dbServer->platform == SERVER_PLATFORMS::EC2 && ($dbServer->IsSupported('0.7') && $dbServer->osType == 'linux' || $roleImage->getImage()->isEc2HvmImage())) {
         if ($rootVolumeSize > 0) {
             $rootBlockDevice['size'] = $rootVolumeSize;
         }
         if (in_array($rootVolumeType, ['standard', 'gp2', 'io1'])) {
             $rootBlockDevice['volume_type'] = $rootVolumeType;
             if ($rootVolumeType == 'io1' && $rootVolumeIops > 0) {
                 $rootBlockDevice['iops'] = $rootVolumeIops;
             }
         }
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo($dbServer, $name, $replaceType, $object, $description, $rootBlockDevice);
     $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
     $BundleTask->createdById = $this->user->id;
     $BundleTask->createdByEmail = $this->user->getEmail();
     if ($dbServer->GetFarmRoleObject()->GetSetting('user-data.scm_branch') == 'feature/image-api') {
         $BundleTask->generation = 2;
     }
     $protoRole = DBRole::loadById($dbServer->GetFarmRoleObject()->RoleID);
     $BundleTask->osId = $protoRole->osId;
     if ($protoRole->getOs()->family == 'windows') {
         $BundleTask->osFamily = $protoRole->getOs()->family;
         $BundleTask->osVersion = $protoRole->getOs()->generation;
         $BundleTask->osName = '';
     } else {
         $BundleTask->osFamily = $protoRole->getOs()->family;
         $BundleTask->osVersion = $protoRole->getOs()->version;
         $BundleTask->osName = $protoRole->getOs()->name;
     }
     if (in_array($protoRole->getOs()->family, array('redhat', 'oel', 'scientific')) && $dbServer->platform == SERVER_PLATFORMS::EC2) {
         $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
     }
     $BundleTask->save();
     $this->response->data(['bundleTaskId' => $BundleTask->id]);
     $this->response->success("Bundle task successfully created.");
 }
コード例 #14
0
 /**
  * Called when instance going down
  *
  * @param HostDownEvent $event
  */
 public function OnHostDown(HostDownEvent $event)
 {
     if ($event->DBServer->IsRebooting()) {
         return;
     }
     $event->DBServer->status = SERVER_STATUS::TERMINATED;
     $event->DBServer->dateShutdownScheduled = date("Y-m-d H:i:s");
     $this->DB->Execute("UPDATE servers_history SET\r\n\t\t\t\tdtterminated_scalr\t= NOW()\r\n\t\t\t\tWHERE server_id = ?\r\n\t\t\t", array($event->DBServer->serverId));
     try {
         $DBFarmRole = $event->DBServer->GetFarmRoleObject();
         if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_BCP_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_IS_BCP_RUNNING, 0);
         }
         if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_MYSQL_BUNDLE_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(DBFarmRole::SETTING_MYSQL_IS_BUNDLE_RUNNING, 0);
         }
         if ($DBFarmRole->GetSetting(Scalr_Db_Msr::DATA_BACKUP_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(Scalr_Db_Msr::DATA_BACKUP_IS_RUNNING, 0);
         }
         if ($DBFarmRole->GetSetting(Scalr_Db_Msr::DATA_BUNDLE_SERVER_ID) == $event->DBServer->serverId) {
             $DBFarmRole->SetSetting(Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, 0);
         }
     } catch (Exception $e) {
     }
     if ($event->replacementDBServer) {
         $event->replacementDBServer->replaceServerID = null;
         $event->replacementDBServer->Save();
     }
     //Check active bundle task:
     $bundle_task_id = $this->DB->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status IN (?,?)", array($event->DBServer->serverId, SERVER_SNAPSHOT_CREATION_STATUS::PENDING, SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS));
     if ($bundle_task_id) {
         $BundleTask = BundleTask::LoadById($bundle_task_id);
         $BundleTask->SnapshotCreationFailed("Server was terminated before image was created.");
     }
     //
     //
     //
     //TODO:
     $farminfo = $this->DB->GetRow("SELECT * FROM farms WHERE id=?", array($this->FarmID));
     if ($farminfo['status'] == FARM_STATUS::SYNCHRONIZING) {
         $event->DBServer->SkipEBSObserver = true;
         $farm_servers_count = $this->DB->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id=? and server_id != ? and status != ?", array($this->FarmID, $event->DBServer->serverId, SERVER_STATUS::TERMINATED));
         if ($farm_servers_count == 0) {
             $this->DB->Execute("UPDATE farms SET status=? WHERE id=?", array(FARM_STATUS::TERMINATED, $this->FarmID));
         }
     }
     $event->DBServer->Save();
 }
コード例 #15
0
ファイル: class.DBRole.php プロジェクト: recipe/scalr
 public static function createFromBundleTask(BundleTask $BundleTask)
 {
     $db = \Scalr::getDb();
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     if ($BundleTask->prototypeRoleId) {
         $proto_role = $db->GetRow("SELECT * FROM roles WHERE id=? LIMIT 1", array($BundleTask->prototypeRoleId));
         if (!$proto_role['architecture']) {
             $proto_role['architecture'] = $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE);
         }
     } else {
         $proto_role = array("behaviors" => $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR), "architecture" => $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE), "name" => "*import*");
     }
     if (!$proto_role['architecture']) {
         $proto_role['architecture'] = 'x86_64';
     }
     if (!$BundleTask->cloudLocation) {
         if ($DBServer) {
             $BundleTask->cloudLocation = $DBServer->GetCloudLocation();
         }
     }
     $osInfo = $BundleTask->getOsDetails();
     $meta = $BundleTask->getSnapshotDetails();
     if (!$osInfo->family || !$osInfo->generation) {
         $osInfo = new stdClass();
         if ($proto_role) {
             $osInfo->name = $proto_role['os'];
             $osInfo->family = $proto_role['os_family'];
             $osInfo->generation = $proto_role['os_generation'];
             $osInfo->version = $proto_role['os_version'];
         } elseif ($meta['os'] && $meta['os']->version) {
             if ($meta['os']->version == '2008Server') {
                 $osInfo->name = 'Windows 2008 Server';
                 $osInfo->family = 'windows';
                 $osInfo->generation = '2008';
                 $osInfo->version = '2008Server';
             } elseif ($meta['os']->version == '2008ServerR2') {
                 $osInfo->name = 'Windows 2008 Server R2';
                 $osInfo->family = 'windows';
                 $osInfo->generation = '2008';
                 $osInfo->version = '2008ServerR2';
             }
         }
     }
     if ($proto_role['cat_id']) {
         $catId = $proto_role['cat_id'];
     } else {
         $catId = ROLE_BEHAVIORS::GetCategoryId($proto_role['behaviors']);
     }
     $db->Execute("INSERT INTO roles SET\n            name\t\t\t= ?,\n            origin\t\t\t= ?,\n            dtadded         = NOW(),\n            client_id\t\t= ?,\n            env_id\t\t\t= ?,\n            cat_id          = ?,\n            description\t\t= ?,\n            behaviors\t\t= ?,\n            history\t\t\t= ?,\n            generation\t\t= ?,\n            added_by_email  = ?,\n            added_by_userid = ?,\n            os\t\t\t\t= ?,\n            os_family       = ?,\n            os_version      = ?,\n            os_generation   = ?\n        ", array($BundleTask->roleName, ROLE_TYPE::CUSTOM, $BundleTask->clientId, $BundleTask->envId, $catId, $BundleTask->description, $proto_role['behaviors'], trim("{$proto_role['history']},{$proto_role['name']}", ","), 2, $BundleTask->createdByEmail, $BundleTask->createdById, $osInfo->name, $osInfo->family, $osInfo->version, $osInfo->generation));
     $role_id = $db->Insert_Id();
     $BundleTask->roleId = $role_id;
     $BundleTask->Save();
     $BundleTask->Log(sprintf("Created new role. Role name: %s. Role ID: %s", $BundleTask->roleName, $BundleTask->roleId));
     $role = self::loadById($role_id);
     $behaviors = explode(",", $proto_role['behaviors']);
     foreach ($behaviors as $behavior) {
         $db->Execute("INSERT INTO role_behaviors SET\n                role_id\t\t\t= ?,\n                behavior\t\t= ?\n            ", array($role_id, $behavior));
     }
     // Set image
     $role->setImage($BundleTask->snapshotId, $BundleTask->platform, $BundleTask->platform != SERVER_PLATFORMS::GCE ? $BundleTask->cloudLocation : "", $meta['szr_version'], $proto_role['architecture']);
     // Set params
     if ($proto_role['id']) {
         $dbParams = $db->GetAll("SELECT name,type,isrequired,defval,allow_multiple_choice,options,hash,issystem\n                FROM role_parameters WHERE role_id = ?", array($proto_role['id']));
         $role->setParameters($dbParams);
         $dbSecRules = $db->GetAll("SELECT * FROM role_security_rules WHERE role_id = ?", array($proto_role['id']));
         foreach ($dbSecRules as $dbSecRule) {
             $db->Execute("INSERT INTO role_security_rules SET role_id = ?, rule = ?", array($role_id, $dbSecRule['rule']));
         }
         $props = $db->GetAll("SELECT * FROM role_properties WHERE role_id=?", array($proto_role['id']));
         foreach ($props as $prop) {
             $role->setProperty($prop['name'], $prop['value']);
         }
         $scripts = $db->GetAll("SELECT * FROM role_scripts WHERE role_id=?", array($proto_role['id']));
         foreach ($scripts as &$script) {
             $script['params'] = unserialize($script['params']);
         }
         $role->setScripts($scripts);
         $variables = new Scalr_Scripting_GlobalVariables($proto_role['env_id'], Scalr_Scripting_GlobalVariables::SCOPE_ROLE);
         $variables->setValues($variables->getValues($proto_role['id']), $role->id);
     }
     // Set software
     if ($meta) {
         $software = array();
         foreach ((array) $meta['software'] as $soft) {
             $software[$soft->name] = $soft->version;
         }
         $role->setSoftware($software);
         $role->setTags((array) $meta['tags']);
         if ($BundleTask->platform == SERVER_PLATFORMS::NIMBULA) {
             $props = array(array('name' => self::PROPERTY_NIMBULA_INIT_ROOT_USER, 'value' => $meta['init_root_user']), array('name' => self::PROPERTY_NIMBULA_INIT_ROOT_PASS, 'value' => $meta['init_root_pass']), array('name' => self::PROPERTY_NIMBULA_ENTRY, 'value' => ''));
             foreach ($props as $prop) {
                 $role->setProperty($prop['name'], $prop['value']);
             }
         }
     }
     return $role;
 }
コード例 #16
0
ファイル: Ec2.php プロジェクト: rakesh-mohanta/scalr
 public function CreateServerSnapshot(BundleTask $BundleTask)
 {
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     $EC2Client = Scalr_Service_Cloud_Aws::newEc2($DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::PRIVATE_KEY), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(self::CERTIFICATE));
     if (!$BundleTask->prototypeRoleId) {
         $proto_image_id = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::AMIID);
     } else {
         $proto_image_id = DBRole::loadById($BundleTask->prototypeRoleId)->getImageId(SERVER_PLATFORMS::EC2, $DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION));
     }
     $DescribeImagesType = new DescribeImagesType();
     $DescribeImagesType->imagesSet->item[] = array("imageId" => $proto_image_id);
     $ami_info = $EC2Client->DescribeImages($DescribeImagesType);
     $platfrom = (string) $ami_info->imagesSet->item->platform;
     if ($platfrom == 'windows') {
         if ((string) $ami_info->imagesSet->item->rootDeviceType != 'ebs') {
             $BundleTask->SnapshotCreationFailed("Only EBS root filesystem supported for Windows servers.");
             return;
         }
         if ($BundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PENDING) {
             $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_WIN200X;
             $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PREPARING;
             try {
                 $msg = $DBServer->SendMessage(new Scalr_Messaging_Msg_Win_PrepareBundle($BundleTask->id));
                 if ($msg) {
                     $BundleTask->Log(sprintf(_("PrepareBundle message sent. MessageID: %s. Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
                 } else {
                     throw new Exception("Cannot send message");
                 }
             } catch (Exception $e) {
                 $BundleTask->SnapshotCreationFailed("Cannot send PrepareBundle message to server.");
                 return false;
             }
         } elseif ($BundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PREPARING) {
             $BundleTask->Log(sprintf(_("Selected platform snapshot type: %s"), $BundleTask->bundleType));
             try {
                 $CreateImageType = new CreateImageType($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $BundleTask->roleName . "-" . date("YmdHi"), $BundleTask->roleName, false);
                 $result = $EC2Client->CreateImage($CreateImageType);
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
                 $BundleTask->snapshotId = $result->imageId;
                 $BundleTask->Log(sprintf(_("Snapshot creating initialized (AMIID: %s). Bundle task status changed to: %s"), $BundleTask->snapshotId, $BundleTask->status));
             } catch (Exception $e) {
                 $BundleTask->SnapshotCreationFailed($e->getMessage());
                 return;
             }
         }
     } else {
         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
         if ((string) $ami_info->imagesSet->item->rootDeviceType == 'ebs') {
             if ((string) $ami_info->imagesSet->item->virtualizationType == 'hvm') {
                 $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
             } else {
                 $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS;
             }
         } else {
             $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_S3I;
         }
         $BundleTask->Save();
         $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
         if ($BundleTask->bundleType == SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM) {
             try {
                 $CreateImageType = new CreateImageType($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $BundleTask->roleName . "-" . date("YmdHi"), $BundleTask->roleName, false);
                 $result = $EC2Client->CreateImage($CreateImageType);
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
                 $BundleTask->snapshotId = $result->imageId;
                 $BundleTask->Log(sprintf(_("Snapshot creating initialized (AMIID: %s). Bundle task status changed to: %s"), $BundleTask->snapshotId, $BundleTask->status));
             } catch (Exception $e) {
                 $BundleTask->SnapshotCreationFailed($e->getMessage());
                 return;
             }
         } else {
             $msg = new Scalr_Messaging_Msg_Rebundle($BundleTask->id, $BundleTask->roleName, array());
             $metaData = $BundleTask->getSnapshotDetails();
             if ($metaData['rootVolumeSize']) {
                 $msg->volumeSize = $metaData['rootVolumeSize'];
             }
             if (!$DBServer->SendMessage($msg)) {
                 $BundleTask->SnapshotCreationFailed("Cannot send rebundle message to server. Please check event log for more details.");
                 return;
             } else {
                 $BundleTask->Log(sprintf(_("Snapshot creation started (MessageID: %s). Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
             }
         }
     }
     $BundleTask->setDate('started');
     $BundleTask->Save();
 }
コード例 #17
0
ファイル: class.ScalrAPI_2_0_0.php プロジェクト: scalr/scalr
 public function ServerImageCreate($ServerID, $RoleName)
 {
     $this->restrictAccess(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE);
     $this->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
     $DBServer = DBServer::LoadByID($ServerID);
     // Validate client and server
     if ($DBServer->envId != $this->Environment->id) {
         throw new Exception(sprintf("Server ID #%s not found", $ServerID));
     }
     $this->user->getPermissions()->validate($DBServer);
     //Check for already running bundle on selected instance
     $chk = $this->DB->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($ServerID));
     if ($chk) {
         throw new Exception(sprintf(_("Server '%s' is already synchonizing."), $ServerID));
     }
     if (!Role::isValidName($RoleName)) {
         throw new Exception(_("Role name is incorrect"));
     }
     if (Role::isNameUsed($RoleName, $this->user->getAccountId(), $this->Environment->id)) {
         throw new Exception("Specified role name is already used by another role");
     }
     if ($btId = BundleTask::getActiveTaskIdByName($RoleName, $this->user->getAccountId(), $this->Environment->id)) {
         throw new Exception(sprintf("Specified role name is already reserved for BundleTask with ID: %d.", $btId));
     }
     $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo($DBServer, $RoleName, SERVER_REPLACEMENT_TYPE::NO_REPLACE, BundleTask::BUNDLETASK_OBJECT_ROLE, 'Bundled via API');
     $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
     $BundleTask->createdById = $this->user->id;
     $BundleTask->createdByEmail = $this->user->getEmail();
     $BundleTask->save();
     $response = $this->CreateInitialResponse();
     $response->BundleTaskID = $BundleTask->id;
     return $response;
 }
コード例 #18
0
ファイル: Roles.php プロジェクト: rakesh-mohanta/scalr
 public function xBuildAction()
 {
     $this->request->defineParams(array('platform' => array('type' => 'string'), 'architecture' => array('type' => 'string'), 'behaviors' => array('type' => 'json'), 'roleName' => array('type' => 'string'), 'imageId' => array('type' => 'string'), 'location' => array('type' => 'string'), 'mysqlServerType' => array('type' => 'string'), 'devScalarizrBranch' => array('type' => 'string')));
     if (strlen($this->getParam('roleName')) < 3) {
         throw new Exception(_("Role name should be greater than 3 chars"));
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         throw new Exception(_("Role name is incorrect"));
     }
     $chkRoleId = $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?)", array($this->getParam('roleName'), $this->getEnvironmentId()));
     if ($chkRoleId) {
         if (!$this->db->GetOne("SELECT id FROM roles_queue WHERE role_id=?", array($chkRoleId))) {
             throw new Exception('Selected role name is already used. Please select another one.');
         }
     }
     $imageId = $this->getParam('imageId');
     if ($this->getParam('platform') == SERVER_PLATFORMS::RACKSPACE) {
         $imageId = str_replace('lon', '', $imageId);
     }
     $behaviours = implode(",", array_values($this->getParam('behaviors')));
     // Create server
     $creInfo = new ServerCreateInfo($this->getParam('platform'), null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.6", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => $this->getParam('mysqlServerType'), SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $this->getParam('devScalarizrBranch')));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $this->getParam('location');
     $launchOptions->architecture = $this->getParam('architecture');
     switch ($this->getParam('platform')) {
         case SERVER_PLATFORMS::RACKSPACE:
             $launchOptions->serverType = 1;
             break;
         case SERVER_PLATFORMS::EC2:
             $launchOptions->serverType = 'm1.small';
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
     }
     if ($this->getParam('serverType')) {
         $launchOptions->serverType = $this->getParam('serverType');
     }
     if ($this->getParam('availZone')) {
         $launchOptions->availZone = $this->getParam('availZone');
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $this->getParam('roleName'), SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         PlatformFactory::NewPlatform($this->getParam('platform'))->LaunchServer($dbServer, $launchOptions);
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('bundleTaskId' => $bundleTask->id));
 }
コード例 #19
0
ファイル: Eucalyptus.php プロジェクト: recipe/scalr
 public function CreateServerSnapshot(BundleTask $BundleTask)
 {
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     $euca = $DBServer->GetEnvironmentObject()->eucalyptus($DBServer);
     if (!$BundleTask->prototypeRoleId) {
         $protoImageId = $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::EMIID);
     } else {
         $protoImageId = DBRole::loadById($BundleTask->prototypeRoleId)->getImageId(SERVER_PLATFORMS::EUCALYPTUS, $DBServer->GetProperty(EUCA_SERVER_PROPERTIES::REGION));
     }
     $ami = $euca->ec2->image->describe($protoImageId)->get(0);
     $platfrom = $ami->platform;
     $rootDeviceType = $ami->rootDeviceType;
     if ($rootDeviceType == 'ebs') {
         $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EUCA_EBS;
         $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
         $BundleTask->SnapshotCreationFailed("Not supported yet");
         return;
     } else {
         if ($platfrom == 'windows') {
             //TODO: Windows platfrom is not supported yet.
             $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EUCA_WIN;
             $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
             $BundleTask->SnapshotCreationFailed("Not supported yet");
             return;
         } else {
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
             $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EUCA_WSI;
             $BundleTask->Save();
             $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
             $msg = new Scalr_Messaging_Msg_Rebundle($BundleTask->id, $BundleTask->roleName, array());
             if (!$DBServer->SendMessage($msg)) {
                 $BundleTask->SnapshotCreationFailed("Cannot send rebundle message to server. Please check event log for more details.");
                 return;
             } else {
                 $BundleTask->Log(sprintf(_("Snapshot creation started (MessageID: %s). Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
             }
         }
     }
     $BundleTask->setDate('started');
     $BundleTask->Save();
 }
コード例 #20
0
ファイル: Servers.php プロジェクト: scalr/scalr
 /**
  * @param   string  $serverId
  * @param   string  $name
  * @param   string  $description
  * @param   bool    $createRole
  * @param   string  $scope
  * @param   string  $replaceRole
  * @param   bool    $replaceImage
  * @param   int     $rootVolumeSize
  * @param   string  $rootVolumeType
  * @param   int     $rootVolumeIops
  * @throws  Exception
  */
 public function xServerCreateSnapshotAction($serverId, $name = '', $description = '', $createRole = false, $scope = '', $replaceRole = '', $replaceImage = false, $rootVolumeSize = 0, $rootVolumeType = '', $rootVolumeIops = 0)
 {
     $this->request->restrictAccess(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE);
     $server = $this->getServerEntity($serverId);
     $this->request->checkPermissions($server, true);
     $farm = $server->getFarm();
     $role = $server->getFarmRole()->getRole();
     //Check for already running bundle on selected instance
     if ($this->db->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($server->serverId))) {
         throw new Exception(sprintf(_("Server '%s' is already synchonizing."), $server->serverId));
     }
     $validator = new Validator();
     $validator->addErrorIf(!Entity\Role::isValidName($name), 'name', "Role name is incorrect");
     $validator->addErrorIf(!in_array($replaceRole, ['farm', 'all', '']), 'replaceRole', 'Invalid value');
     $object = $createRole ? BundleTask::BUNDLETASK_OBJECT_ROLE : BundleTask::BUNDLETASK_OBJECT_IMAGE;
     $replaceType = SERVER_REPLACEMENT_TYPE::NO_REPLACE;
     $createScope = ScopeInterface::SCOPE_ENVIRONMENT;
     if ($createRole) {
         $this->request->restrictAccess(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE);
         if ($replaceRole == 'farm') {
             if ($farm->hasAccessPermissions($this->getUser(), $this->getEnvironment(), Acl::PERM_FARMS_UPDATE)) {
                 $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_FARM;
             } else {
                 $validator->addError('replaceRole', "You don't have permissions to update farm");
             }
         } else {
             if ($replaceRole == 'all') {
                 if ($this->request->isAllowed([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS], Acl::PERM_FARMS_UPDATE)) {
                     $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_ALL;
                 } else {
                     $validator->addError('replaceRole', "You don't have permissions to update farms");
                 }
             }
         }
         /* @var $existRole Entity\Role */
         $existRole = Entity\Role::findOne([['name' => $name], ['$or' => [['accountId' => null], ['$and' => [['accountId' => $this->getUser()->accountId], ['$or' => [['envId' => null], ['envId' => $this->getEnvironment()->id]]]]]]]]);
         if ($existRole) {
             if (empty($existRole->accountId)) {
                 $validator->addError('name', _("Selected role name is reserved and cannot be used for custom role"));
             } else {
                 if ($replaceType != SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
                     $validator->addError('name', _("Specified role name is already used by another role. You can use this role name only if you will replace old one on ALL your farms."));
                 } else {
                     if ($replaceType == SERVER_REPLACEMENT_TYPE::REPLACE_ALL && $existRole->id != $role->id) {
                         $validator->addError('name', _("Specified role name is already in use. You cannot replace a Role different from the one you are currently snapshotting."));
                     }
                 }
             }
         }
         if ($btId = BundleTask::getActiveTaskIdByName($name, $this->getUser()->accountId, $this->getEnvironment()->id)) {
             $validator->addError('name', sprintf("Specified role name is already reserved for BundleTask with ID: %d.", $btId));
         }
         if ($replaceType != SERVER_REPLACEMENT_TYPE::NO_REPLACE) {
             $chk = BundleTask::getActiveTaskIdByRoleId($role->id, $this->getEnvironment()->id, BundleTask::BUNDLETASK_OBJECT_ROLE);
             $validator->addErrorIf($chk, 'replaceRole', sprintf("Role is already synchronizing in BundleTask: %d.", $chk));
         }
     } else {
         $sc = $role->getScope();
         if ($replaceImage) {
             if ($sc == ScopeInterface::SCOPE_ENVIRONMENT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE) || $sc == ScopeInterface::SCOPE_ACCOUNT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ACCOUNT, Acl::PERM_ROLES_ACCOUNT_MANAGE)) {
                 $replaceType = SERVER_REPLACEMENT_TYPE::REPLACE_ALL;
                 $chk = BundleTask::getActiveTaskIdByRoleId($role->id, $this->getEnvironment()->id, BundleTask::BUNDLETASK_OBJECT_IMAGE);
                 $validator->addErrorIf($chk, 'replaceImage', sprintf("Role is already synchronizing in BundleTask: %d.", $chk));
             } else {
                 $validator->addError('replaceImage', "You don't have permissions to replace image in role");
             }
         }
     }
     if ($scope && ($createRole || $scope != $createScope)) {
         if ($createRole) {
             $c = $scope == ScopeInterface::SCOPE_ENVIRONMENT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ENVIRONMENT, Acl::PERM_ROLES_ENVIRONMENT_MANAGE) || $scope == ScopeInterface::SCOPE_ACCOUNT && $this->request->isAllowed(Acl::RESOURCE_ROLES_ACCOUNT, Acl::PERM_ROLES_ACCOUNT_MANAGE);
             $validator->addErrorIf(!$c, 'scope', sprintf("You don't have permissions to create role in scope %s", $scope));
         }
         $c = $scope == ScopeInterface::SCOPE_ENVIRONMENT && $this->request->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE) || $scope == ScopeInterface::SCOPE_ACCOUNT && $this->request->isAllowed(Acl::RESOURCE_IMAGES_ACCOUNT, Acl::PERM_IMAGES_ACCOUNT_MANAGE);
         $validator->addErrorIf(!$c, 'scope', sprintf("You don't have permissions to create image in scope %s", $scope));
         $createScope = $scope;
     }
     $image = $role->getImage($server->platform, $server->cloudLocation)->getImage();
     $rootBlockDevice = [];
     if ($server->platform == SERVER_PLATFORMS::EC2 && ($server->isVersionSupported('0.7') && $server->os == 'linux' || $image->isEc2HvmImage())) {
         if ($rootVolumeSize > 0) {
             $rootBlockDevice['size'] = $rootVolumeSize;
         }
         if (in_array($rootVolumeType, [CreateVolumeRequestData::VOLUME_TYPE_STANDARD, CreateVolumeRequestData::VOLUME_TYPE_GP2, CreateVolumeRequestData::VOLUME_TYPE_IO1, CreateVolumeRequestData::VOLUME_TYPE_SC1, CreateVolumeRequestData::VOLUME_TYPE_ST1])) {
             $rootBlockDevice['volume_type'] = $rootVolumeType;
             if ($rootVolumeType == CreateVolumeRequestData::VOLUME_TYPE_IO1 && $rootVolumeIops > 0) {
                 $rootBlockDevice['iops'] = $rootVolumeIops;
             }
         }
     }
     if (!$validator->isValid($this->response)) {
         return;
     }
     $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo(DBServer::LoadByID($server->serverId), $name, $replaceType, $object, $description, $rootBlockDevice);
     $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
     $BundleTask->createdById = $this->user->id;
     $BundleTask->createdByEmail = $this->user->getEmail();
     $BundleTask->osId = $role->osId;
     $BundleTask->objectScope = $createScope;
     if ($role->getOs()->family == 'windows') {
         $BundleTask->osFamily = $role->getOs()->family;
         $BundleTask->osVersion = $role->getOs()->generation;
         $BundleTask->osName = '';
     } else {
         $BundleTask->osFamily = $role->getOs()->family;
         $BundleTask->osVersion = $role->getOs()->version;
         $BundleTask->osName = $role->getOs()->name;
     }
     if (in_array($role->getOs()->family, array('redhat', 'oel', 'scientific')) && $server->platform == SERVER_PLATFORMS::EC2) {
         $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
     }
     $BundleTask->save();
     $this->response->data(['bundleTaskId' => $BundleTask->id]);
     $this->response->success("Bundle task successfully created.");
 }
コード例 #21
0
ファイル: Ec2.php プロジェクト: recipe/scalr
 /**
  * {@inheritdoc}
  * @see IPlatformModule::CreateServerSnapshot()
  */
 public function CreateServerSnapshot(BundleTask $BundleTask)
 {
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     $aws = $DBServer->GetEnvironmentObject()->aws($DBServer);
     if (!$BundleTask->prototypeRoleId) {
         $proto_image_id = $DBServer->GetProperty(EC2_SERVER_PROPERTIES::AMIID);
     } else {
         $protoRole = DBRole::loadById($BundleTask->prototypeRoleId);
         $proto_image_id = $protoRole->getImageId(SERVER_PLATFORMS::EC2, $DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION));
         $details = $protoRole->getImageDetails(SERVER_PLATFORMS::EC2, $DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION));
         if (in_array($details['os_family'], array('oel', 'redhat', 'scientific'))) {
             $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
         }
     }
     $ami = $aws->ec2->image->describe($proto_image_id)->get(0);
     $platfrom = $ami->platform;
     if ($platfrom == 'windows') {
         if ($ami->rootDeviceType != 'ebs') {
             $BundleTask->SnapshotCreationFailed("Only EBS root filesystem supported for Windows servers.");
             return;
         }
         if ($BundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PENDING) {
             $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_WIN200X;
             $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PREPARING;
             try {
                 $msg = $DBServer->SendMessage(new Scalr_Messaging_Msg_Win_PrepareBundle($BundleTask->id));
                 if ($msg) {
                     $BundleTask->Log(sprintf(_("PrepareBundle message sent. MessageID: %s. Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
                 } else {
                     throw new Exception("Cannot send message");
                 }
             } catch (Exception $e) {
                 $BundleTask->SnapshotCreationFailed("Cannot send PrepareBundle message to server.");
                 return false;
             }
         } elseif ($BundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PREPARING) {
             $BundleTask->Log(sprintf(_("Selected platform snapshot type: %s"), $BundleTask->bundleType));
             try {
                 $request = new CreateImageRequestData($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $BundleTask->roleName . "-" . date("YmdHi"));
                 $request->description = $BundleTask->roleName;
                 $request->noReboot = false;
                 $imageId = $aws->ec2->image->create($request);
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
                 $BundleTask->snapshotId = $imageId;
                 $BundleTask->Log(sprintf(_("Snapshot creating initialized (AMIID: %s). Bundle task status changed to: %s"), $BundleTask->snapshotId, $BundleTask->status));
             } catch (Exception $e) {
                 $BundleTask->SnapshotCreationFailed($e->getMessage());
                 return;
             }
         }
     } else {
         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
         if (!$BundleTask->bundleType) {
             if ($ami->rootDeviceType == 'ebs') {
                 if ($ami->virtualizationType == 'hvm') {
                     $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } else {
                     $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS;
                 }
             } else {
                 $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_S3I;
             }
         }
         $BundleTask->Save();
         $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
         if ($BundleTask->bundleType == SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM) {
             try {
                 $request = new CreateImageRequestData($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID), $BundleTask->roleName . "-" . date("YmdHi"));
                 $request->description = $BundleTask->roleName;
                 $request->noReboot = false;
                 $imageId = $aws->ec2->image->create($request);
                 $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
                 $BundleTask->snapshotId = $imageId;
                 $BundleTask->Log(sprintf(_("Snapshot creating initialized (AMIID: %s). Bundle task status changed to: %s"), $BundleTask->snapshotId, $BundleTask->status));
             } catch (Exception $e) {
                 $BundleTask->SnapshotCreationFailed($e->getMessage());
                 return;
             }
         } else {
             $msg = new Scalr_Messaging_Msg_Rebundle($BundleTask->id, $BundleTask->roleName, array());
             $metaData = $BundleTask->getSnapshotDetails();
             if ($metaData['rootVolumeSize']) {
                 $msg->volumeSize = $metaData['rootVolumeSize'];
             }
             if (!$DBServer->SendMessage($msg)) {
                 $BundleTask->SnapshotCreationFailed("Cannot send rebundle message to server. Please check event log for more details.");
                 return;
             } else {
                 $BundleTask->Log(sprintf(_("Snapshot creation started (MessageID: %s). Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
             }
         }
     }
     $BundleTask->setDate('started');
     $BundleTask->Save();
 }
コード例 #22
0
ファイル: Roles.php プロジェクト: recipe/scalr
 public function xBuildAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE);
     $this->request->defineParams(array('platform' => array('type' => 'string'), 'architecture' => array('type' => 'string'), 'behaviors' => array('type' => 'json'), 'roleName' => array('type' => 'string'), 'imageId' => array('type' => 'string'), 'location' => array('type' => 'string'), 'advanced' => array('type' => 'json'), 'chef' => array('type' => 'json')));
     if (strlen($this->getParam('roleName')) < 3) {
         throw new Exception(_("Role name should be greater than 3 chars"));
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         throw new Exception(_("Role name is incorrect"));
     }
     $chkRoleId = $this->db->GetOne("SELECT id FROM roles WHERE name=? AND (env_id = '0' OR env_id = ?) LIMIT 1", array($this->getParam('roleName'), $this->getEnvironmentId()));
     if ($chkRoleId) {
         if (!$this->db->GetOne("SELECT id FROM roles_queue WHERE role_id=? LIMIT 1", array($chkRoleId))) {
             throw new Exception('Selected role name is already used. Please select another one.');
         }
     }
     $imageId = $this->getParam('imageId');
     $advanced = $this->getParam('advanced');
     $chef = $this->getParam('chef');
     $behaviours = implode(",", array_values($this->getParam('behaviors')));
     // Create server
     $creInfo = new ServerCreateInfo($this->getParam('platform'), null, 0, 0);
     $creInfo->clientId = $this->user->getAccountId();
     $creInfo->envId = $this->getEnvironmentId();
     $creInfo->farmId = 0;
     $creInfo->SetProperties(array(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR => $behaviours, SERVER_PROPERTIES::SZR_IMPORTING_IMAGE_ID => $imageId, SERVER_PROPERTIES::SZR_KEY => Scalr::GenerateRandomKey(40), SERVER_PROPERTIES::SZR_KEY_TYPE => SZR_KEY_TYPE::PERMANENT, SERVER_PROPERTIES::SZR_VESION => "0.13.0", SERVER_PROPERTIES::SZR_IMPORTING_MYSQL_SERVER_TYPE => "mysql", SERVER_PROPERTIES::SZR_DEV_SCALARIZR_BRANCH => $advanced['scalrbranch'], SERVER_PROPERTIES::ARCHITECTURE => $this->getParam('architecture'), SERVER_PROPERTIES::SZR_IMPORTING_LEAVE_ON_FAIL => $advanced['dontterminatefailed'] == 'on' ? 1 : 0, SERVER_PROPERTIES::SZR_IMPORTING_CHEF_SERVER_ID => $chef['chef.server'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ENVIRONMENT => $chef['chef.environment'], SERVER_PROPERTIES::SZR_IMPORTING_CHEF_ROLE_NAME => $chef['chef.role']));
     $dbServer = DBServer::Create($creInfo, true);
     $dbServer->status = SERVER_STATUS::TEMPORARY;
     $dbServer->save();
     //Launch server
     $launchOptions = new Scalr_Server_LaunchOptions();
     $launchOptions->imageId = $imageId;
     $launchOptions->cloudLocation = $this->getParam('cloud_location');
     $launchOptions->architecture = $this->getParam('architecture');
     $platform = PlatformFactory::NewPlatform($this->getParam('platform'));
     switch ($this->getParam('platform')) {
         case SERVER_PLATFORMS::ECS:
             $launchOptions->serverType = 10;
             break;
         case SERVER_PLATFORMS::IDCF:
             $launchOptions->serverType = 24;
             break;
         case SERVER_PLATFORMS::RACKSPACE:
             if ($this->getParam('osfamily') == 'ubuntu') {
                 $launchOptions->serverType = 1;
             } else {
                 $launchOptions->serverType = 3;
             }
             break;
         case SERVER_PLATFORMS::RACKSPACENG_US:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::RACKSPACENG_UK:
             $launchOptions->serverType = 3;
             break;
         case SERVER_PLATFORMS::EC2:
             if ($this->getParam('hvm') == 1) {
                 $launchOptions->serverType = 'm3.xlarge';
                 $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
             } else {
                 if ($this->getParam('osfamily') == 'oel') {
                     $launchOptions->serverType = 'm1.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($this->getParam('osfamily') == 'rhel') {
                     $launchOptions->serverType = 'm1.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } elseif ($this->getParam('osfamily') == 'scientific') {
                     $launchOptions->serverType = 'm1.large';
                     $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
                 } else {
                     $launchOptions->serverType = 'm1.small';
                 }
             }
             $launchOptions->userData = "#cloud-config\ndisable_root: false";
             break;
         case SERVER_PLATFORMS::GCE:
             $launchOptions->serverType = 'n1-standard-1';
             $locations = array_keys($platform->getLocations());
             $launchOptions->cloudLocation = $locations[0];
             $bundleType = SERVER_SNAPSHOT_CREATION_TYPE::GCE_STORAGE;
             break;
     }
     if ($advanced['servertype']) {
         $launchOptions->serverType = $advanced['servertype'];
     }
     if ($advanced['availzone']) {
         $launchOptions->availZone = $advanced['availzone'];
     }
     if ($advanced['region']) {
         $launchOptions->cloudLocation = $advanced['region'];
     }
     //Add Bundle task
     $creInfo = new ServerSnapshotCreateInfo($dbServer, $this->getParam('roleName'), SERVER_REPLACEMENT_TYPE::NO_REPLACE);
     $bundleTask = BundleTask::Create($creInfo, true);
     if ($bundleType) {
         $bundleTask->bundleType = $bundleType;
     }
     $bundleTask->createdById = $this->user->id;
     $bundleTask->createdByEmail = $this->user->getEmail();
     $bundleTask->osFamily = $this->getParam('osfamily');
     $bundleTask->cloudLocation = $launchOptions->cloudLocation;
     $bundleTask->save();
     $bundleTask->Log(sprintf("Launching temporary server (%s)", serialize($launchOptions)));
     $dbServer->SetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID, $bundleTask->id);
     try {
         $platform->LaunchServer($dbServer, $launchOptions);
         $bundleTask->Log(_("Temporary server launched. Waiting for running state..."));
     } catch (Exception $e) {
         $bundleTask->SnapshotCreationFailed(sprintf(_("Unable to launch temporary server: %s"), $e->getMessage()));
     }
     $this->response->data(array('serverId' => $dbServer->serverId, 'bundleTaskId' => $bundleTask->id));
 }
コード例 #23
0
ファイル: Rds.php プロジェクト: rakesh-mohanta/scalr
 public function CreateServerSnapshot(BundleTask $BundleTask)
 {
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     $RDSClient = $this->getRdsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(RDS_SERVER_PROPERTIES::REGION));
     try {
         $RDSClient->CreateDBSnapshot($BundleTask->roleName, $DBServer->GetProperty(RDS_SERVER_PROPERTIES::INSTANCE_ID));
         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
         $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::RDS_SPT;
         $BundleTask->snapshotId = $BundleTask->roleName;
         $BundleTask->Log(sprintf(_("Snapshot creation initialized. SnapshotID: %s"), $BundleTask->snapshotId));
         $BundleTask->setDate('started');
         $BundleTask->Save();
     } catch (Exception $e) {
         $BundleTask->SnapshotCreationFailed($e->getMessage());
     }
 }
コード例 #24
0
ファイル: Import.php プロジェクト: scalr/scalr
 public function xGetBundleTaskDataAction()
 {
     $task = BundleTask::LoadById($this->getParam('bundleTaskId'));
     $this->user->getPermissions()->validate($task);
     $logs = $this->db->GetAll("SELECT * FROM bundle_task_log WHERE bundle_task_id = " . $this->db->qstr($this->getParam('bundleTaskId')) . ' ORDER BY id DESC LIMIT 3');
     foreach ($logs as &$row) {
         $row['dtadded'] = Scalr_Util_DateTime::convertTz($row['dtadded']);
     }
     $image = $task->getImageEntity();
     $this->response->data(array('status' => $task->status, 'failureReason' => $task->failureReason, 'logs' => $logs, 'roleId' => $task->roleId, 'roleName' => $task->roleName, 'platform' => $task->platform, 'imageId' => $task->snapshotId, 'imageHash' => !empty($image) ? $image->hash : null));
 }
コード例 #25
0
ファイル: class.DBRole.php プロジェクト: mheydt/scalr
 public static function createFromBundleTask(BundleTask $BundleTask)
 {
     $db = \Scalr::getDb();
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     if ($BundleTask->prototypeRoleId) {
         $proto_role = $db->GetRow("SELECT * FROM roles WHERE id=? LIMIT 1", array($BundleTask->prototypeRoleId));
         if (!$proto_role['architecture']) {
             $proto_role['architecture'] = $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE);
         }
     } else {
         $behaviors = array_unique(explode(',', $DBServer->GetProperty(SERVER_PROPERTIES::SZR_IMPORTING_BEHAVIOR)));
         sort($behaviors);
         $proto_role = array("behaviors" => join(',', $behaviors), "architecture" => $DBServer->GetProperty(SERVER_PROPERTIES::ARCHITECTURE), "name" => "*import*");
     }
     if (!$proto_role['architecture']) {
         $proto_role['architecture'] = 'x86_64';
     }
     if (!$BundleTask->cloudLocation) {
         if ($DBServer) {
             $BundleTask->cloudLocation = $DBServer->GetCloudLocation();
         }
     }
     $osId = $BundleTask->osId;
     $meta = $BundleTask->getSnapshotDetails();
     if (!$osId) {
         if ($proto_role) {
             $osId = $proto_role['os_id'];
         } elseif ($meta['os'] && $meta['os']->version) {
             /*
                             if ($meta['os']->version == '2008Server') {
                                 $osInfo->name = 'Windows 2008 Server';
                                 $osInfo->family = 'windows';
                                 $osInfo->generation = '2008';
                                 $osInfo->version = '2008Server';
                             } elseif ($meta['os']->version == '2008ServerR2') {
                                 $osInfo->name = 'Windows 2008 Server R2';
                                 $osInfo->family = 'windows';
                                 $osInfo->generation = '2008';
                                 $osInfo->version = '2008ServerR2';
                             }*/
             //TODO:
         }
     }
     if ($proto_role['cat_id']) {
         $catId = $proto_role['cat_id'];
     } else {
         $catId = ROLE_BEHAVIORS::GetCategoryId($proto_role['behaviors']);
     }
     $db->Execute("INSERT INTO roles SET\n            name\t\t\t= ?,\n            origin\t\t\t= ?,\n            dtadded         = NOW(),\n            client_id\t\t= ?,\n            env_id\t\t\t= ?,\n            cat_id          = ?,\n            description\t\t= ?,\n            behaviors\t\t= ?,\n            generation\t\t= ?,\n            added_by_email  = ?,\n            added_by_userid = ?,\n            os_id\t\t\t= ?\n        ", array($BundleTask->roleName, ROLE_TYPE::CUSTOM, $BundleTask->clientId, $BundleTask->envId, $catId, $BundleTask->description, $proto_role['behaviors'], 2, $BundleTask->createdByEmail, $BundleTask->createdById, $osId));
     $role_id = $db->Insert_Id();
     $BundleTask->roleId = $role_id;
     $BundleTask->Save();
     $BundleTask->Log(sprintf("Created new role. Role name: %s. Role ID: %s", $BundleTask->roleName, $BundleTask->roleId));
     $role = self::loadById($role_id);
     $behaviors = explode(",", $proto_role['behaviors']);
     foreach ($behaviors as $behavior) {
         $db->Execute("INSERT IGNORE INTO role_behaviors SET\n                role_id\t\t\t= ?,\n                behavior\t\t= ?\n            ", array($role_id, $behavior));
     }
     // Set image
     $role->__getNewRoleObject()->setImage($BundleTask->platform, $BundleTask->cloudLocation, $BundleTask->snapshotId, $BundleTask->createdById, $BundleTask->createdByEmail);
     // Set params
     if ($proto_role['id']) {
         $dbSecRules = $db->GetAll("SELECT * FROM role_security_rules WHERE role_id = ?", array($proto_role['id']));
         foreach ($dbSecRules as $dbSecRule) {
             $db->Execute("INSERT INTO role_security_rules SET role_id = ?, rule = ?", array($role_id, $dbSecRule['rule']));
         }
         $props = $db->GetAll("SELECT * FROM role_properties WHERE role_id=?", array($proto_role['id']));
         foreach ($props as $prop) {
             $role->setProperty($prop['name'], $prop['value']);
         }
         $scripts = $db->GetAll("SELECT * FROM role_scripts WHERE role_id=?", array($proto_role['id']));
         foreach ($scripts as &$script) {
             $script['params'] = unserialize($script['params']);
         }
         $role->setScripts($scripts);
         $variables = new Scalr_Scripting_GlobalVariables($BundleTask->clientId, $proto_role['env_id'], ScopeInterface::SCOPE_ROLE);
         $variables->setValues($variables->getValues($proto_role['id']), $role->id);
     }
     $role->syncAnalyticsTags();
     return $role;
 }
コード例 #26
0
ファイル: Servers.php プロジェクト: rickb838/scalr
 public function xServerCreateSnapshotAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS_ROLES, Acl::PERM_FARMS_ROLES_CREATE);
     $this->request->defineParams(array('rootVolumeSize' => array('type' => 'int')));
     if (!$this->getParam('serverId')) {
         throw new Exception(_('Server not found'));
     }
     $dbServer = DBServer::LoadByID($this->getParam('serverId'));
     $this->user->getPermissions()->validate($dbServer);
     $err = array();
     if (strlen($this->getParam('roleName')) < 3) {
         $err[] = _("Role name should be greater than 3 chars");
     }
     if (!preg_match("/^[A-Za-z0-9-]+\$/si", $this->getParam('roleName'))) {
         $err[] = _("Role name is incorrect");
     }
     $roleinfo = $this->db->GetRow("SELECT * FROM roles WHERE name=? AND (env_id=? OR env_id='0') LIMIT 1", array($this->getParam('roleName'), $dbServer->envId, $dbServer->roleId));
     if ($this->getParam('replaceType') != SERVER_REPLACEMENT_TYPE::REPLACE_ALL) {
         if ($roleinfo) {
             $err[] = _("Specified role name is already used by another role. You can use this role name only if you will replace old one on ALL your farms.");
         }
     } else {
         if ($roleinfo && $roleinfo['env_id'] == 0) {
             $err[] = _("Selected role name is reserved and cannot be used for custom role");
         }
     }
     //Check for already running bundle on selected instance
     $chk = $this->db->GetOne("SELECT id FROM bundle_tasks WHERE server_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($dbServer->serverId));
     if ($chk) {
         $err[] = sprintf(_("Server '%s' is already synchonizing."), $dbServer->serverId);
     }
     //Check is role already synchronizing...
     $chk = $this->db->GetOne("SELECT server_id FROM bundle_tasks WHERE prototype_role_id=? AND status NOT IN ('success', 'failed') LIMIT 1", array($dbServer->roleId));
     if ($chk && $chk != $dbServer->serverId) {
         try {
             $bDBServer = DBServer::LoadByID($chk);
             if ($bDBServer->farmId == $DBServer->farmId) {
                 $err[] = sprintf(_("Role '%s' is already synchonizing."), $dbServer->GetFarmRoleObject()->GetRoleObject()->name);
             }
         } catch (Exception $e) {
         }
     }
     if ($dbServer->GetFarmRoleObject()->NewRoleID) {
         $err[] = sprintf(_("Role '%s' is already synchonizing."), $dbServer->GetFarmRoleObject()->GetRoleObject()->name);
     }
     if (count($err)) {
         throw new Exception(nl2br(implode('\\n', $err)));
     }
     $ServerSnapshotCreateInfo = new ServerSnapshotCreateInfo($dbServer, $this->getParam('roleName'), $this->getParam('replaceType'), false, $this->getParam('roleDescription'), $this->getParam('rootVolumeSize'), $this->getParam('noServersReplace') == 'on' ? true : false);
     $BundleTask = BundleTask::Create($ServerSnapshotCreateInfo);
     $BundleTask->createdById = $this->user->id;
     $BundleTask->createdByEmail = $this->user->getEmail();
     if ($dbServer->GetFarmRoleObject()->GetSetting('user-data.scm_branch') == 'feature/image-api') {
         $BundleTask->generation = 2;
     }
     $protoRole = DBRole::loadById($dbServer->roleId);
     $BundleTask->osFamily = $protoRole->osFamily;
     $BundleTask->osVersion = $protoRole->osVersion;
     if (in_array($protoRole->osFamily, array('redhat', 'oel', 'scientific')) && $dbServer->platform == SERVER_PLATFORMS::EC2) {
         $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::EC2_EBS_HVM;
     }
     $BundleTask->save();
     $this->response->success("Bundle task successfully created. <a href='#/bundletasks/{$BundleTask->id}/logs'>Click here to check status.</a>", true);
 }
コード例 #27
0
ファイル: event_handler.php プロジェクト: rickb838/scalr
             if (trim($stderr)) {
                 $stderr = "\n stderr: {$stderr}";
             }
             $stdout = base64_decode($data['stdout']);
             if (trim($stdout)) {
                 $stdout = "\n stdout: {$stdout}";
             }
             if (!$stderr && !$stdout) {
                 $stdout = _("Script executed without any output.");
             }
             $Logger->warn(new ScriptingLogMessage($req_FarmID, $event_name, $DBServer->serverId, sprintf(_("Script '%s' execution result (Execution time: %s seconds). %s %s"), $data['script_path'], $data['time_elapsed'], $stderr, $stdout)));
             break;
         case "rebundleStatus":
             if ($data['bundletaskid']) {
                 try {
                     $BundleTask = BundleTask::LoadById($data['bundletaskid']);
                     if ($BundleTask->serverId == $DBServer->serverId) {
                         $BundleTask->Log($data['message']);
                     }
                 } catch (Exception $e) {
                 }
             }
             break;
         case "logEvent":
             $message = base64_decode($data["msg"]);
             $tm = date('YmdH');
             $hash = md5("{$DBServer->serverId}:{$message}:{$req_FarmID}:{$data['source']}:{$tm}", true);
             $db->Execute("INSERT DELAYED INTO logentries SET id=?, serverid=?, message=?, `time`=?, severity=?, `source`=?, farmid=? ON DUPLICATE KEY UPDATE cnt = cnt + 1, `time` = ?", array($hash, $DBServer->serverId, $message, time(), $data["severity"], $data["source"], $req_FarmID, time()));
             break;
     }
 }
コード例 #28
0
 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:
             $conn = @fsockopen($DBServer->getSzrHost(), $DBServer->getPort(DBServer::PORT_CTRL), $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(CloudstackPlatformModule::SHARED_IP_ID . ".{$cloudLocation}", $environment, false);
                     $sharedIp = $platform->getConfigVariable(CloudstackPlatformModule::SHARED_IP . ".{$cloudLocation}", $environment, false);
                     $BundleTask->Log("Shared IP: {$sharedIp}");
                     $cs = $environment->cloudstack($DBServer->platform);
                     // Create port forwarding rules for scalarizr
                     $port = $platform->getConfigVariable(CloudstackPlatformModule::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;
                     }
                     $virtualmachineid = $DBServer->GetProperty(CLOUDSTACK_SERVER_PROPERTIES::SERVER_ID);
                     $result2 = $cs->firewall->createPortForwardingRule(array('ipaddressid' => $sharedIpId, 'privateport' => 8014, 'protocol' => "udp", 'publicport' => $port1, 'virtualmachineid' => $virtualmachineid));
                     $result1 = $cs->firewall->createPortForwardingRule(array('ipaddressid' => $sharedIpId, 'privateport' => 8013, 'protocol' => "tcp", 'publicport' => $port1, 'virtualmachineid' => $virtualmachineid));
                     $result3 = $cs->firewall->createPortForwardingRule(array('ipaddressid' => $sharedIpId, 'privateport' => 8010, 'protocol' => "tcp", 'publicport' => $port3, 'virtualmachineid' => $virtualmachineid));
                     $result4 = $cs->firewall->createPortForwardingRule(array('ipaddressid' => $sharedIpId, 'privateport' => 8008, 'protocol' => "tcp", 'publicport' => $port2, 'virtualmachineid' => $virtualmachineid));
                     $result5 = $cs->firewall->createPortForwardingRule(array('ipaddressid' => $sharedIpId, 'privateport' => 22, 'protocol' => "tcp", 'publicport' => $port4, 'virtualmachineid' => $virtualmachineid));
                     $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(CloudstackPlatformModule::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;
             }
             $BundleTask->Log(sprintf(_("Created SSH session. Username: %s"), $ssh2Client->getLogin()));
             //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 = rtrim(\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();
                 @stream_set_blocking($shell, true);
                 @stream_set_timeout($shell, 5);
                 @fwrite($shell, "sudo touch /var/log/role-builder-output.log 2>&1" . PHP_EOL);
                 $output = @fgets($shell, 4096);
                 $BundleTask->Log("Verbose 1: {$output}");
                 @fwrite($shell, "sudo chmod 0666 /var/log/role-builder-output.log 2>&1" . PHP_EOL);
                 $output2 = @fgets($shell, 4096);
                 $BundleTask->Log("Verbose 2: {$output2}");
                 @fwrite($shell, "sudo setsid /tmp/scalr-builder.sh > /var/log/role-builder-output.log 2>&1 &" . PHP_EOL);
                 $output3 = @fgets($shell, 4096);
                 $BundleTask->Log("Verbose 3: {$output3}");
                 sleep(5);
                 $meta = stream_get_meta_data($shell);
                 $BundleTask->Log(sprintf("Verbose (Meta): %s", json_encode($meta)));
                 $i = 4;
                 if ($meta['eof'] == false && $meta['unread_bytes'] != 0) {
                     $output4 = @fread($shell, $meta['unread_bytes']);
                     $BundleTask->Log("Verbose {$i}: {$output4}");
                     $meta = stream_get_meta_data($shell);
                     $BundleTask->Log(sprintf("Verbose (Meta): %s", json_encode($meta)));
                 }
                 @fclose($shell);
                 /*
                 $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));
                                 }
                             } 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, SERVER_STATUS::SUSPENDED))) {
                                     $ServerCreateInfo = new ServerCreateInfo($DBFarmRole->Platform, $DBFarmRole, $DBServer->index, $DBFarmRole->NewRoleID);
                                     $nDBServer = Scalr::LaunchServer($ServerCreateInfo, null, false, DBServer::LAUNCH_REASON_REPLACE_SERVER_FROM_SNAPSHOT, !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(DBServer::TERMINATE_REASON_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();
                 $BundleTask->createImageEntity();
             }
             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})");
                     }
                 }
                 if ($BundleTask->object == BundleTask::BUNDLETASK_OBJECT_ROLE) {
                     try {
                         $DBRole = DBRole::createFromBundleTask($BundleTask);
                     } catch (Exception $e) {
                         $BundleTask->SnapshotCreationFailed("Role creation failed due to internal error ({$e->getMessage()}). Please try again.");
                         return;
                     }
                 } else {
                     // roleName is empty, just create image
                     $BundleTask->createImageEntity();
                 }
                 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(DBServer::TERMINATE_REASON_TEMPORARY_SERVER_ROLE_BUILDER);
                             $BundleTask->Log("Termination request has been sent");
                         }
                     } catch (Exception $e) {
                         $BundleTask->Log("Warning: {$e->getMessage()}");
                     }
                 }
                 $BundleTask->Save();
                 $BundleTask->createImageEntity();
             } catch (Exception $e) {
                 $this->Logger->error($e->getMessage());
             }
             break;
     }
 }
コード例 #29
0
ファイル: class.DBServer.php プロジェクト: mheydt/scalr
 /**
  * @return Scalr_Net_Ssh2_Client
  * Enter description here ...
  */
 public function GetSsh2Client()
 {
     $ssh2Client = new Scalr_Net_Ssh2_Client();
     switch ($this->platform) {
         case SERVER_PLATFORMS::RACKSPACENG_UK:
         case SERVER_PLATFORMS::RACKSPACENG_US:
             $ssh2Client->addPassword('root', $this->GetProperty(OPENSTACK_SERVER_PROPERTIES::ADMIN_PASS));
             break;
         case SERVER_PLATFORMS::RACKSPACE:
             $ssh2Client->addPassword('root', $this->GetProperty(RACKSPACE_SERVER_PROPERTIES::ADMIN_PASS));
             break;
         case SERVER_PLATFORMS::GCE:
             $userName = '******';
             if ($this->status == SERVER_STATUS::TEMPORARY) {
                 $keyName = 'SCALR-ROLESBUILDER-' . SCALR_ID;
             } else {
                 $keyName = "FARM-{$this->farmId}-" . SCALR_ID;
             }
             try {
                 $key = (new SshKey())->loadGlobalByName($this->envId, SERVER_PLATFORMS::GCE, "", $keyName);
                 if (!$key) {
                     throw new Exception(_("There is no SSH key for server: {$this->serverId}"));
                 }
             } catch (Exception $e) {
                 throw new Exception("Cannot init SshKey object: {$e->getMessage()}");
             }
             $priv_key_file = tempnam("/tmp", "GCEPK");
             @file_put_contents($priv_key_file, $key->privateKey);
             $this->tmpFiles[] = $priv_key_file;
             $pub_key_file = tempnam("/tmp", "GCEK");
             @file_put_contents($pub_key_file, $key->publicKey);
             $this->tmpFiles[] = $pub_key_file;
             $ssh2Client->addPubkey($userName, $pub_key_file, $priv_key_file);
             break;
         case SERVER_PLATFORMS::IDCF:
         case SERVER_PLATFORMS::EC2:
             $userName = '******';
             $skipKeyValidation = false;
             // Temporary server for role builder
             $sshKey = new SshKey();
             if ($this->status == SERVER_STATUS::TEMPORARY) {
                 $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID . "-{$this->envId}";
                 if (!$sshKey->loadGlobalByName($this->envId, $this->platform, $this->GetCloudLocation(), $keyName)) {
                     $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID;
                 }
                 try {
                     $bundleTaskId = $this->GetProperty(\SERVER_PROPERTIES::SZR_IMPORTING_BUNDLE_TASK_ID);
                     $bundleTask = BundleTask::LoadById($bundleTaskId);
                     if ($bundleTask->osFamily == 'amazon') {
                         $userName = '******';
                     }
                 } catch (Exception $e) {
                 }
             } else {
                 $keyName = "FARM-{$this->farmId}-" . SCALR_ID;
                 $oldKeyName = "FARM-{$this->farmId}";
                 $key = $sshKey->loadGlobalByName($this->envId, $this->platform, $this->GetCloudLocation(), $oldKeyName);
                 if ($key) {
                     $keyName = $oldKeyName;
                     $skipKeyValidation = true;
                 }
             }
             if (!$skipKeyValidation) {
                 try {
                     $key = $sshKey->loadGlobalByName($this->envId, $this->platform, $this->GetCloudLocation(), $keyName);
                     if (!$key) {
                         throw new Exception(sprintf('Could not find SSH Key for server "%s" with name:"%s", cloud-location:"%s", platform:"%s", environment:"%d".', $this->serverId, $keyName, $this->GetCloudLocation(), $this->platform, $this->envId));
                     }
                 } catch (Exception $e) {
                     throw new Exception("Cannot init SshKey object: {$e->getMessage()}");
                 }
             }
             $priv_key_file = tempnam("/tmp", "AWSK");
             @file_put_contents($priv_key_file, $key->privateKey);
             $this->tmpFiles[] = $priv_key_file;
             $pub_key_file = tempnam("/tmp", "AWSK");
             $this->tmpFiles[] = $pub_key_file;
             $pubKey = $key->publicKey;
             if (!stristr($pubKey, $keyName)) {
                 $pubKey .= " {$keyName}";
             }
             @file_put_contents($pub_key_file, $pubKey);
             $ssh2Client->addPubkey($userName, $pub_key_file, $priv_key_file);
             break;
     }
     return $ssh2Client;
 }
コード例 #30
0
ファイル: Openstack.php プロジェクト: recipe/scalr
 public function CreateServerSnapshot(BundleTask $BundleTask)
 {
     $DBServer = DBServer::LoadByID($BundleTask->serverId);
     if ($BundleTask->osFamily == 'windows' || $DBServer->osType == 'windows') {
         if ($BundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PENDING) {
             $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::OSTACK_WINDOWS;
             $BundleTask->Log(sprintf(_("Selected platfrom snapshoting type: %s"), $BundleTask->bundleType));
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::PREPARING;
             $BundleTask->Save();
             try {
                 $msg = $DBServer->SendMessage(new Scalr_Messaging_Msg_Win_PrepareBundle($BundleTask->id), false, true);
                 if ($msg) {
                     $BundleTask->Log(sprintf(_("PrepareBundle message sent. MessageID: %s. Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
                 } else {
                     throw new Exception("Cannot send message");
                 }
             } catch (Exception $e) {
                 $BundleTask->SnapshotCreationFailed("Cannot send PrepareBundle message to server.");
                 return false;
             }
         } elseif ($BundleTask->status == SERVER_SNAPSHOT_CREATION_STATUS::PREPARING) {
             $BundleTask->Log(sprintf(_("Selected platform snapshot type: %s"), $BundleTask->bundleType));
             $createImage = true;
         }
     } else {
         $BundleTask->bundleType = SERVER_SNAPSHOT_CREATION_TYPE::OSTACK_LINUX;
         $createImage = false;
         $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
         $msg = new Scalr_Messaging_Msg_Rebundle($BundleTask->id, $BundleTask->roleName, array());
         if (!$DBServer->SendMessage($msg)) {
             $BundleTask->SnapshotCreationFailed("Cannot send rebundle message to server. Please check event log for more details.");
             return;
         } else {
             $BundleTask->Log(sprintf(_("Snapshot creating initialized (MessageID: %s). Bundle task status changed to: %s"), $msg->messageId, $BundleTask->status));
         }
         $BundleTask->setDate('started');
         $BundleTask->Save();
     }
     if ($createImage) {
         try {
             $client = $this->getOsClient($DBServer->GetEnvironmentObject(), $DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::CLOUD_LOCATION));
             $imageId = $client->servers->createImage($DBServer->GetProperty(OPENSTACK_SERVER_PROPERTIES::SERVER_ID), $BundleTask->roleName . "-" . date("YmdHi"));
             $BundleTask->status = SERVER_SNAPSHOT_CREATION_STATUS::IN_PROGRESS;
             $BundleTask->snapshotId = $imageId;
             $BundleTask->Log(sprintf(_("Snapshot creating initialized (ImageID: %s). Bundle task status changed to: %s"), $BundleTask->snapshotId, $BundleTask->status));
             $BundleTask->setDate('started');
             $BundleTask->Save();
         } catch (Exception $e) {
             $BundleTask->SnapshotCreationFailed($e->getMessage());
             return;
         }
     }
     return true;
 }