isEnabled() public method

Returns policy status.
public isEnabled ( string $category, string $name ) : boolean
$category string Governance category name
$name string Governance policy name
return boolean Returns true if policy is enabled
Esempio n. 1
1
 public function xSaveAction()
 {
     $this->request->defineParams(array('category' => array('type' => 'string'), 'name' => array('type' => 'string'), 'value' => array('type' => 'json')));
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $category = $this->getParam('category');
     $name = $this->getParam('name');
     $value = $this->getParam('value');
     if ($category == Scalr_Governance::CATEGORY_GENERAL && $name == Scalr_Governance::GENERAL_LEASE) {
         $enabled = (bool) $value['limits']['enableDefaultLeaseDuration'];
         unset($value['limits']['enableDefaultLeaseDuration']);
         if (!$governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE) && $value['enabled'] == 1 && $enabled) {
             $dt = new DateTime();
             $dt->add(new DateInterval('P' . $value['limits']['defaultLifePeriod'] . 'D'));
             $farms = $this->db->GetCol('SELECT id FROM farms WHERE env_id = ? AND status = ?', array($this->getEnvironmentId(), FARM_STATUS::RUNNING));
             foreach ($farms as $farmId) {
                 $farm = DBFarm::LoadByID($farmId);
                 $farm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'));
                 $farm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, '');
                 $farm->SetSetting(DBFarm::SETTING_LEASE_EXTEND_CNT, 0);
             }
         }
     }
     $governance->setValue($category, $name, $value);
     $this->response->success('Successfully saved');
 }
Esempio n. 2
0
 public function xListFarmsAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_FARMS);
     $this->request->defineParams(array('clientId' => array('type' => 'int'), 'farmId' => array('type' => 'int'), 'sort' => array('type' => 'json'), 'expirePeriod' => array('type' => 'int')));
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $leaseStatus = $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE);
     $sql = 'SELECT f.clientid, f.id, f.name, f.status, f.dtadded, f.created_by_id, f.created_by_email FROM farms f WHERE env_id = ? AND :FILTER:';
     $args = array($this->getEnvironmentId());
     if ($leaseStatus && $this->getParam('expirePeriod')) {
         $dt = new DateTime();
         $dt->add(new DateInterval('P' . $this->getParam('expirePeriod') . 'D'));
         $sql = str_replace('FROM farms f', 'FROM farms f LEFT JOIN farm_settings fs ON f.id = fs.farmid', $sql);
         $sql = str_replace('WHERE', 'WHERE fs.name = ? AND fs.value < ? AND f.status = ? AND', $sql);
         array_unshift($args, DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'), FARM_STATUS::RUNNING);
     }
     if ($this->getParam('farmId')) {
         $sql .= ' AND id = ?';
         $args[] = $this->getParam('farmId');
     }
     if ($this->getParam('clientId')) {
         $sql .= ' AND clientid = ?';
         $args[] = $this->getParam('clientId');
     }
     if ($this->getParam('status') != '') {
         $sql .= ' AND status = ?';
         $args[] = $this->getParam('status');
     }
     if ($this->getParam('showOnlyMy') || !$this->request->isAllowed(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_NOT_OWNED_FARMS)) {
         $sql .= ' AND created_by_id = ?';
         $args[] = $this->user->getId();
     }
     $response = $this->buildResponseFromSql2($sql, array('id', 'name', 'dtadded', 'created_by_email', 'status'), array('name', 'id', 'comments'), $args);
     foreach ($response["data"] as &$row) {
         $row["running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id='{$row['id']}' AND status IN ('Pending', 'Initializing', 'Running', 'Temporary','Resuming')");
         $row["suspended_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id='{$row['id']}' AND status IN ('Suspended', 'Pending suspend')");
         $row["non_running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_id='{$row['id']}' AND status NOT IN ('Suspended', 'Pending suspend', 'Resuming', 'Pending', 'Initializing', 'Running', 'Temporary', 'Pending launch')");
         $row["roles"] = $this->db->GetOne("SELECT COUNT(*) FROM farm_roles WHERE farmid='{$row['id']}'");
         $row["zones"] = $this->db->GetOne("SELECT COUNT(*) FROM dns_zones WHERE farm_id='{$row['id']}'");
         //TODO: Use Alerts class
         $row['alerts'] = $this->db->GetOne("SELECT COUNT(*) FROM server_alerts WHERE farm_id='{$row['id']}' AND status='failed'");
         $row['dtadded'] = Scalr_Util_DateTime::convertTz($row["dtadded"]);
         $dbFarm = DBFarm::LoadByID($row['id']);
         $row['lock'] = $dbFarm->GetSetting(DBFarm::SETTING_LOCK);
         if ($row['lock']) {
             $row['lock_comment'] = $dbFarm->isLocked(false);
         }
         if ($leaseStatus && $dbFarm->GetSetting(DBFarm::SETTING_LEASE_STATUS)) {
             $row['lease'] = $dbFarm->GetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND) ? 'Expire' : $dbFarm->GetSetting(DBFarm::SETTING_LEASE_STATUS);
             if ($row['lease'] == 'Expire') {
                 $dt = new DateTime();
                 $td = new DateTime($dbFarm->GetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE));
                 $days = 0;
                 $hours = 1;
                 $interval = $dt->diff($td);
                 if ($interval) {
                     $days = $interval->days;
                     $hours = $interval->h ? $interval->h : 1;
                 }
                 $row['leaseMessage'] = sprintf('Your farm lease is about to expire in %d %s, after which this farm will be terminated', $days ? $days : $hours, $days ? $days > 1 ? 'days' : 'day' : ($hours > 1 ? 'hours' : 'hour'));
             }
         }
         $b = (array) $this->db->GetAll("SELECT DISTINCT(behavior) FROM farm_roles\n                INNER JOIN role_behaviors ON role_behaviors.role_id = farm_roles.role_id WHERE farmid = ?", array($row['id']));
         $behaviors = array();
         foreach ($b as $behavior) {
             $behaviors[] = $behavior['behavior'];
         }
         $row["havemysqlrole"] = in_array(ROLE_BEHAVIORS::MYSQL, $behaviors);
         $row["havemysql2role"] = in_array(ROLE_BEHAVIORS::MYSQL2, $behaviors);
         $row["havepgrole"] = in_array(ROLE_BEHAVIORS::POSTGRESQL, $behaviors);
         $row["haveredisrole"] = in_array(ROLE_BEHAVIORS::REDIS, $behaviors);
         $row["haverabbitmqrole"] = in_array(ROLE_BEHAVIORS::RABBITMQ, $behaviors);
         $row["havemongodbrole"] = in_array(ROLE_BEHAVIORS::MONGODB, $behaviors);
         $row["haveperconarole"] = in_array(ROLE_BEHAVIORS::PERCONA, $behaviors);
         $row["havemariadbrole"] = in_array(ROLE_BEHAVIORS::MARIADB, $behaviors);
         $row['status_txt'] = FARM_STATUS::GetStatusName($row['status']);
         if ($row['status'] == FARM_STATUS::RUNNING) {
             $row['shortcuts'] = [];
             foreach (\Scalr\Model\Entity\ScriptShortcut::find(array(array('farmId' => $row['id']), array('farmRoleId' => NULL))) as $shortcut) {
                 /* @var \Scalr\Model\Entity\ScriptShortcut $shortcut */
                 $row['shortcuts'][] = array('id' => $shortcut->id, 'name' => $shortcut->getScriptName());
             }
         }
     }
     $this->response->data($response);
 }
Esempio n. 3
0
 public function FarmCreate($Name, $Description = "", $ProjectID = "")
 {
     $this->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE);
     $ProjectID = strtolower($ProjectID);
     $response = $this->CreateInitialResponse();
     $Name = $this->stripValue($Name);
     $Description = $this->stripValue($Description);
     if (!$Name || strlen($Name) < 5) {
         throw new Exception('Name should be at least 5 characters');
     }
     $dbFarm = new DBFarm();
     $dbFarm->ClientID = $this->user->getAccountId();
     $dbFarm->EnvID = $this->Environment->id;
     $dbFarm->Status = FARM_STATUS::TERMINATED;
     $dbFarm->createdByUserId = $this->user->getId();
     $dbFarm->createdByUserEmail = $this->user->getEmail();
     $dbFarm->changedByUserId = $this->user->getId();
     $dbFarm->changedTime = microtime();
     $dbFarm->Name = $Name;
     $dbFarm->RolesLaunchOrder = 0;
     $dbFarm->Comments = $Description;
     $dbFarm->save();
     //Associates cost analytics project with the farm.
     $dbFarm->setProject(!empty($ProjectID) ? $ProjectID : null);
     $governance = new Scalr_Governance($this->Environment->id);
     if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
         // for created farm
     }
     $response->FarmID = $dbFarm->ID;
     return $response;
 }
Esempio n. 4
0
 public function LaunchServer(DBServer $DBServer, \Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $environment = $DBServer->GetEnvironmentObject();
     $ccProps = $environment->keychain(SERVER_PLATFORMS::GCE)->properties;
     $governance = new \Scalr_Governance($environment->id);
     $rootDeviceSettings = null;
     $ssdDisks = array();
     $scopes = ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/devstorage.full_control"];
     if (!$launchOptions) {
         $launchOptions = new \Scalr_Server_LaunchOptions();
         $DBRole = $DBServer->GetFarmRoleObject()->GetRoleObject();
         $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage(\SERVER_PLATFORMS::GCE, $DBServer->GetProperty(\GCE_SERVER_PROPERTIES::CLOUD_LOCATION))->imageId;
         $launchOptions->serverType = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::INSTANCE_TYPE);
         $launchOptions->cloudLocation = $DBServer->GetFarmRoleObject()->CloudLocation;
         $userData = $DBServer->GetCloudUserData();
         $launchOptions->architecture = 'x86_64';
         $networkName = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_NETWORK);
         $subnet = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_SUBNET);
         $onHostMaintenance = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_ON_HOST_MAINTENANCE);
         $osType = $DBRole->getOs()->family == 'windows' ? 'windows' : 'linux';
         $rootDevice = json_decode($DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_BASE_ROOT_DEVICE_CONFIG), true);
         if ($rootDevice && $rootDevice['settings']) {
             $rootDeviceSettings = $rootDevice['settings'];
         }
         $storage = new FarmRoleStorage($DBServer->GetFarmRoleObject());
         $volumes = $storage->getVolumesConfigs($DBServer);
         if (!empty($volumes)) {
             foreach ($volumes as $volume) {
                 if ($volume->type == FarmRoleStorageConfig::TYPE_GCE_EPHEMERAL) {
                     array_push($ssdDisks, $volume);
                 }
             }
         }
         if ($governance->isEnabled(\Scalr_Governance::CATEGORY_GENERAL, \Scalr_Governance::GENERAL_HOSTNAME_FORMAT)) {
             $hostNameFormat = $governance->getValue(\Scalr_Governance::CATEGORY_GENERAL, \Scalr_Governance::GENERAL_HOSTNAME_FORMAT);
         } else {
             $hostNameFormat = $DBServer->GetFarmRoleObject()->GetSetting(\Scalr_Role_Behavior::ROLE_BASE_HOSTNAME_FORMAT);
         }
         $hostname = !empty($hostNameFormat) ? $DBServer->applyGlobalVarsToValue($hostNameFormat) : '';
         if ($hostname != '') {
             $DBServer->SetProperty(\Scalr_Role_Behavior::SERVER_BASE_HOSTNAME, $hostname);
         }
         $userScopes = json_decode($DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_INSTANCE_PERMISSIONS));
         if (!empty($userScopes) && is_array($userScopes)) {
             $scopes = array_merge($scopes, $userScopes);
         }
     } else {
         $userData = array();
         $networkName = 'default';
         $osType = 'linux';
         $hostname = '';
     }
     if (!$onHostMaintenance) {
         $onHostMaintenance = 'MIGRATE';
     }
     if ($DBServer->status == \SERVER_STATUS::TEMPORARY) {
         $keyName = "SCALR-ROLESBUILDER-" . SCALR_ID;
     } else {
         $keyName = "FARM-{$DBServer->farmId}-" . SCALR_ID;
     }
     $sshKey = (new SshKey())->loadGlobalByName($DBServer->envId, \SERVER_PLATFORMS::GCE, "", $keyName);
     if (!$sshKey) {
         $sshKey = new SshKey();
         $keys = $sshKey->generateKeypair();
         if ($keys['public']) {
             $sshKey->farmId = $DBServer->farmId;
             $sshKey->envId = $DBServer->envId;
             $sshKey->type = SshKey::TYPE_GLOBAL;
             $sshKey->platform = \SERVER_PLATFORMS::GCE;
             $sshKey->cloudLocation = "";
             $sshKey->cloudKeyName = $keyName;
             $sshKey->save();
             $publicKey = $keys['public'];
         } else {
             throw new Exception("Scalr unable to generate ssh keypair");
         }
     } else {
         $publicKey = $sshKey->publicKey;
     }
     $gce = $this->getClient($environment);
     $projectId = $ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID];
     // Check firewall
     $firewalls = $gce->firewalls->listFirewalls($projectId);
     $firewallFound = false;
     foreach ($firewalls->getItems() as $f) {
         if ($f->getName() == 'scalr-system') {
             $firewallFound = true;
             break;
         }
     }
     // Create scalr firewall
     if (!$firewallFound) {
         $firewall = new \Google_Service_Compute_Firewall();
         $firewall->setName('scalr-system');
         $firewall->setNetwork($this->getObjectUrl($networkName, 'networks', $projectId));
         //Get scalr IP-pool IP list and set source ranges
         $firewall->setSourceRanges(\Scalr::config('scalr.aws.ip_pool'));
         // Set ports
         $tcp = new \Google_Service_Compute_FirewallAllowed();
         $tcp->setIPProtocol('tcp');
         $tcp->setPorts(array('1-65535'));
         $udp = new \Google_Service_Compute_FirewallAllowed();
         $udp->setIPProtocol('udp');
         $udp->setPorts(array('1-65535'));
         $firewall->setAllowed(array($tcp, $udp));
         // Set target tags
         $firewall->setTargetTags(array('scalr'));
         $gce->firewalls->insert($projectId, $firewall);
     }
     $instance = new \Google_Service_Compute_Instance();
     $instance->setKind("compute#instance");
     // Set scheduling
     $scheduling = new \Google_Service_Compute_Scheduling();
     $scheduling->setAutomaticRestart(true);
     $scheduling->setOnHostMaintenance($onHostMaintenance);
     $instance->setScheduling($scheduling);
     $accessConfig = new \Google_Service_Compute_AccessConfig();
     $accessConfig->setName("External NAT");
     $accessConfig->setType("ONE_TO_ONE_NAT");
     $network = new \Google_Service_Compute_NetworkInterface();
     $network->setNetwork($this->getObjectUrl($networkName, 'networks', $projectId));
     if (!empty($subnet)) {
         $network->setSubnetwork($this->getObjectUrl($subnet, 'subnetworks', $projectId, $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_REGION)));
     }
     $network->setAccessConfigs(array($accessConfig));
     $instance->setNetworkInterfaces(array($network));
     $serviceAccount = new \Google_Service_Compute_ServiceAccount();
     $serviceAccount->setEmail("default");
     $serviceAccount->setScopes($scopes);
     $instance->setServiceAccounts(array($serviceAccount));
     if ($launchOptions->cloudLocation != 'x-scalr-custom') {
         $availZone = $launchOptions->cloudLocation;
     } else {
         $location = $DBServer->GetFarmRoleObject()->GetSetting(Entity\FarmRoleSetting::GCE_CLOUD_LOCATION);
         $availZones = array();
         if (stristr($location, "x-scalr-custom")) {
             $zones = explode("=", $location);
             foreach (explode(":", $zones[1]) as $zone) {
                 if ($zone != "") {
                     array_push($availZones, $zone);
                 }
             }
         }
         sort($availZones);
         $availZones = array_reverse($availZones);
         $servers = $DBServer->GetFarmRoleObject()->GetServersByFilter(array("status" => array(\SERVER_STATUS::RUNNING, \SERVER_STATUS::INIT, \SERVER_STATUS::PENDING)));
         $availZoneDistribution = array();
         foreach ($servers as $cDbServer) {
             if ($cDbServer->serverId != $DBServer->serverId) {
                 $availZoneDistribution[$cDbServer->GetProperty(\GCE_SERVER_PROPERTIES::CLOUD_LOCATION)]++;
             }
         }
         $sCount = 1000000;
         foreach ($availZones as $zone) {
             if ((int) $availZoneDistribution[$zone] <= $sCount) {
                 $sCount = (int) $availZoneDistribution[$zone];
                 $availZone = $zone;
             }
         }
         $aZones = implode(",", $availZones);
         // Available zones
         $dZones = "";
         // Zones distribution
         foreach ($availZoneDistribution as $zone => $num) {
             $dZones .= "({$zone}:{$num})";
         }
     }
     $instance->setZone($this->getObjectUrl($availZone, 'zones', $projectId));
     $instance->setMachineType($this->getObjectUrl($launchOptions->serverType, 'machineTypes', $projectId, $availZone));
     //Create root disk
     $image = $this->getObjectUrl($launchOptions->imageId, 'images', $projectId);
     $disks = array();
     $diskName = "root-{$DBServer->serverId}";
     $initializeParams = new \Google_Service_Compute_AttachedDiskInitializeParams();
     $initializeParams->sourceImage = $image;
     $initializeParams->diskName = $diskName;
     if ($rootDeviceSettings) {
         $initializeParams->diskType = $this->getObjectUrl($rootDeviceSettings[FarmRoleStorageConfig::SETTING_GCE_PD_TYPE] ? $rootDeviceSettings[FarmRoleStorageConfig::SETTING_GCE_PD_TYPE] : 'pd-standard', 'diskTypes', $projectId, $availZone);
         $initializeParams->diskSizeGb = $rootDeviceSettings[FarmRoleStorageConfig::SETTING_GCE_PD_SIZE];
     }
     $attachedDisk = new \Google_Service_Compute_AttachedDisk();
     $attachedDisk->setKind("compute#attachedDisk");
     $attachedDisk->setBoot(true);
     $attachedDisk->setMode("READ_WRITE");
     $attachedDisk->setType("PERSISTENT");
     $attachedDisk->setDeviceName("root");
     $attachedDisk->setAutoDelete(true);
     $attachedDisk->setInitializeParams($initializeParams);
     array_push($disks, $attachedDisk);
     if (count($ssdDisks) > 0) {
         foreach ($ssdDisks as $disk) {
             $attachedDisk = new \Google_Service_Compute_AttachedDisk();
             $attachedDisk->setKind("compute#attachedDisk");
             $attachedDisk->setBoot(false);
             $attachedDisk->setMode("READ_WRITE");
             $attachedDisk->setType("SCRATCH");
             $attachedDisk->setDeviceName(str_replace("google-", "", $disk->name));
             $attachedDisk->setInterface('SCSI');
             $attachedDisk->setAutoDelete(true);
             $initializeParams = new \Google_Service_Compute_AttachedDiskInitializeParams();
             $initializeParams->diskType = $this->getObjectUrl('local-ssd', 'diskTypes', $projectId, $availZone);
             $attachedDisk->setInitializeParams($initializeParams);
             array_push($disks, $attachedDisk);
         }
     }
     $instance->setDisks($disks);
     $instance->setName($DBServer->serverId);
     $tags = array('scalr', "env-{$DBServer->envId}");
     if ($DBServer->farmId) {
         $tags[] = "farm-{$DBServer->farmId}";
     }
     if ($DBServer->farmRoleId) {
         $tags[] = "farmrole-{$DBServer->farmRoleId}";
     }
     $gTags = new \Google_Service_Compute_Tags();
     $gTags->setItems($tags);
     $instance->setTags($gTags);
     $metadata = new \Google_Service_Compute_Metadata();
     $items = array();
     // Set user data
     $uData = '';
     foreach ($userData as $k => $v) {
         $uData .= "{$k}={$v};";
     }
     $uData = trim($uData, ";");
     if ($uData) {
         $item = new \Google_Service_Compute_MetadataItems();
         $item->setKey('scalr');
         $item->setValue($uData);
         $items[] = $item;
     }
     if ($osType == 'windows') {
         // Add Windows credentials
         $item = new \Google_Service_Compute_MetadataItems();
         $item->setKey("gce-initial-windows-user");
         $item->setValue("scalr");
         $items[] = $item;
         $item = new \Google_Service_Compute_MetadataItems();
         $item->setKey("gce-initial-windows-password");
         $item->setValue(\Scalr::GenerateRandomKey(16) . rand(0, 9));
         $items[] = $item;
     } else {
         // Add SSH Key
         $item = new \Google_Service_Compute_MetadataItems();
         $item->setKey("sshKeys");
         $item->setValue("scalr:{$publicKey}");
         $items[] = $item;
     }
     //Set hostname
     if ($hostname != '') {
         $item = new \Google_Service_Compute_MetadataItems();
         $item->setKey("hostname");
         $item->setValue($hostname);
         $items[] = $item;
     }
     $metadata->setItems($items);
     $instance->setMetadata($metadata);
     try {
         $result = $gce->instances->insert($projectId, $availZone, $instance);
     } catch (Exception $e) {
         $json = json_decode($e->getMessage());
         if (!empty($json->error->message)) {
             $message = $json->error->message;
         } else {
             $message = $e->getMessage();
         }
         throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), $message, $image, $launchOptions->serverType));
     }
     if ($result->id) {
         $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $availZone);
         /* @var $instanceTypeInfo CloudInstanceType */
         $DBServer->SetProperties([\GCE_SERVER_PROPERTIES::PROVISIONING_OP_ID => $result->name, \GCE_SERVER_PROPERTIES::SERVER_NAME => $DBServer->serverId, \GCE_SERVER_PROPERTIES::CLOUD_LOCATION => $availZone, \GCE_SERVER_PROPERTIES::CLOUD_LOCATION_ZONE => $availZone, \SERVER_PROPERTIES::ARCHITECTURE => $launchOptions->architecture, 'debug.region' => $result->region, 'debug.zone' => $result->zone, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]);
         $DBServer->setOsType($osType);
         $DBServer->cloudLocation = $availZone;
         $DBServer->cloudLocationZone = $availZone;
         $DBServer->imageId = $launchOptions->imageId;
         $DBServer->update(['type' => $launchOptions->serverType, 'instanceTypeName' => $launchOptions->serverType]);
         // we set server history here
         $DBServer->getServerHistory()->update(['cloudServerId' => $DBServer->serverId]);
         return $DBServer;
     } else {
         throw new Exception(sprintf(_("Cannot launch new instance. %s (%s, %s)"), serialize($result), $launchOptions->imageId, $launchOptions->serverType));
     }
 }
Esempio n. 5
0
 public function getBaseConfiguration(DBServer $dbServer, $isHostInit = false, $onlyBase = false)
 {
     $configuration = new stdClass();
     $dbFarmRole = $dbServer->GetFarmRoleObject();
     //Storage
     if (!$onlyBase) {
         try {
             if ($dbFarmRole) {
                 $storage = new FarmRoleStorage($dbFarmRole);
                 $volumes = $storage->getVolumesConfigs($dbServer, $isHostInit);
                 if (!empty($volumes)) {
                     $configuration->volumes = $volumes;
                 }
             }
         } catch (Exception $e) {
             $this->logger->error(new FarmLogMessage($dbServer->farmId, "Cannot init storage: {$e->getMessage()}"));
         }
     }
     // Base
     try {
         if ($dbFarmRole) {
             $scriptingLogTimeout = $dbFarmRole->GetSetting(self::ROLE_BASE_KEEP_SCRIPTING_LOGS_TIME);
             if (!$scriptingLogTimeout) {
                 $scriptingLogTimeout = 3600;
             }
             $configuration->base = new stdClass();
             $configuration->base->keepScriptingLogsTime = $scriptingLogTimeout;
             $configuration->base->abortInitOnScriptFail = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_ABORT_INIT_ON_SCRIPT_FAIL);
             $configuration->base->disableFirewallManagement = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_DISABLE_FIREWALL_MANAGEMENT);
             $configuration->base->rebootAfterHostinitPhase = (int) $dbFarmRole->GetSetting(self::ROLE_BASE_REBOOT_AFTER_HOSTINIT_PHASE);
             $configuration->base->resumeStrategy = PlatformFactory::NewPlatform($dbFarmRole->Platform)->getResumeStrategy();
             //Dev falgs for our
             if (Scalr::isHostedScalr() && $dbServer->envId == 3414) {
                 $configuration->base->unionScriptExecutor = 1;
             }
             $governance = new Scalr_Governance($dbFarmRole->GetFarmObject()->EnvID);
             if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT)) {
                 $hostNameFormat = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT);
             } else {
                 $hostNameFormat = $dbFarmRole->GetSetting(self::ROLE_BASE_HOSTNAME_FORMAT);
             }
             $configuration->base->hostname = !empty($hostNameFormat) ? $dbServer->applyGlobalVarsToValue($hostNameFormat) : '';
             if ($configuration->base->hostname != '') {
                 $dbServer->SetProperty(self::SERVER_BASE_HOSTNAME, $configuration->base->hostname);
             }
             $apiPort = null;
             $messagingPort = null;
             if (!PlatformFactory::isCloudstack($dbFarmRole->Platform)) {
                 $apiPort = $dbFarmRole->GetSetting(self::ROLE_BASE_API_PORT);
                 $messagingPort = $dbFarmRole->GetSetting(self::ROLE_BASE_MESSAGING_PORT);
             }
             $configuration->base->apiPort = $apiPort ? $apiPort : 8010;
             $configuration->base->messagingPort = $messagingPort ? $messagingPort : 8013;
         }
         //Update settings
         $updateSettings = $dbServer->getScalarizrRepository();
         $configuration->base->update = new stdClass();
         foreach ($updateSettings as $k => $v) {
             $configuration->base->update->{$k} = $v;
         }
     } catch (Exception $e) {
     }
     return $configuration;
 }
Esempio n. 6
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Modules\PlatformModuleInterface::LaunchServer()
  */
 public function LaunchServer(DBServer $DBServer, Scalr_Server_LaunchOptions $launchOptions = null)
 {
     $environment = $DBServer->GetEnvironmentObject();
     $governance = new \Scalr_Governance($DBServer->envId);
     $azure = $environment->azure();
     $subscriptionId = $environment->keychain(SERVER_PLATFORMS::AZURE)->properties[CloudCredentialsProperty::AZURE_SUBSCRIPTION_ID];
     if (!$launchOptions) {
         $dbFarmRole = $DBServer->GetFarmRoleObject();
         $DBRole = $dbFarmRole->GetRoleObject();
         $launchOptions = new \Scalr_Server_LaunchOptions();
         $launchOptions->cloudLocation = $dbFarmRole->CloudLocation;
         $launchOptions->serverType = $dbFarmRole->GetSetting(FarmRoleSetting::INSTANCE_TYPE);
         $launchOptions->availZone = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_AVAIL_SET);
         $launchOptions->imageId = $DBRole->__getNewRoleObject()->getImage(\SERVER_PLATFORMS::AZURE, "")->imageId;
         $isWindows = $DBRole->getOs()->family == 'windows';
         // Set User Data
         $u_data = "";
         foreach ($DBServer->GetCloudUserData() as $k => $v) {
             $u_data .= "{$k}={$v};";
         }
         $launchOptions->userData = trim($u_data, ";");
         $launchOptions->azureResourceGroup = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_RESOURCE_GROUP);
         $launchOptions->azureStorageAccount = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_STORAGE_ACCOUNT);
         //Create NIC
         try {
             $ipConfigProperties = new IpConfigurationProperties(["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s", $subscriptionId, $launchOptions->azureResourceGroup, $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_VIRTUAL_NETWORK), $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_SUBNET))], "Dynamic");
             $publicIpName = null;
             if ($governance->isEnabled(\SERVER_PLATFORMS::AZURE, \Scalr_Governance::AZURE_NETWORK)) {
                 $usePublicIp = $governance->getValue(\SERVER_PLATFORMS::AZURE, \Scalr_Governance::AZURE_NETWORK, 'use_public_ips');
             }
             if (!isset($usePublicIp)) {
                 $usePublicIp = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_USE_PUBLIC_IPS);
             }
             if ($usePublicIp) {
                 //Create Public IP object
                 $publicIpName = "scalr-{$DBServer->serverId}";
                 $createPublicIpAddressRequest = new CreatePublicIpAddress($launchOptions->cloudLocation, new PublicIpAddressProperties('Dynamic'));
                 $ipCreateResult = $azure->network->publicIPAddress->create($subscriptionId, $launchOptions->azureResourceGroup, $publicIpName, $createPublicIpAddressRequest);
             }
             if ($publicIpName) {
                 $ipConfigProperties->publicIPAddress = ["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", $subscriptionId, $launchOptions->azureResourceGroup, $publicIpName)];
             }
             $nicProperties = new InterfaceProperties([new InterfaceIpConfigurationsData('public1', $ipConfigProperties)]);
             //Security group
             $sg = $dbFarmRole->GetSetting(FarmRoleSetting::SETTING_AZURE_SECURITY_GROUPS_LIST);
             if ($sg) {
                 $sgName = json_decode($sg);
                 if ($sgName) {
                     $sgroup = new SecurityGroupData();
                     $sgroup->id = sprintf('/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s', $subscriptionId, $launchOptions->azureResourceGroup, $sgName[0]);
                     $nicProperties->setNetworkSecurityGroup($sgroup);
                 }
             }
             $createNicData = new CreateInterface($launchOptions->cloudLocation, $nicProperties);
             $nicResponse = $azure->network->interface->create($subscriptionId, $launchOptions->azureResourceGroup, "scalr-{$DBServer->serverId}", $createNicData);
         } catch (\Exception $e) {
             throw new \Exception("Scalr is unable to create NetworkInterface: {$e->getMessage()}");
         }
         $launchOptions->azureNicName = "scalr-{$DBServer->serverId}";
         $launchOptions->azurePublicIpName = $publicIpName;
     }
     // Configure OS Profile
     // Make sure that password always have 1 special character.
     $adminPassword = \Scalr::GenerateSecurePassword(16, ['D' => '.']);
     $osProfile = new OsProfile('scalr', $adminPassword);
     $osProfile->computerName = \Scalr::GenerateUID(true);
     $osProfile->customData = base64_encode(trim($launchOptions->userData));
     // Configure Network Profile
     $networkProfile = ["networkInterfaces" => [["id" => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkInterfaces/%s", $subscriptionId, $launchOptions->azureResourceGroup, $launchOptions->azureNicName)]]];
     // Configure Storage Profile
     $osDiskName = "scalr-{$DBServer->serverId}";
     $vhd = ['uri' => sprintf("https://%s.blob.core.windows.net/vhds/%s.vhd", $launchOptions->azureStorageAccount, $osDiskName)];
     $storageProfile = new StorageProfile(new OsDisk($osDiskName, $vhd, 'FromImage'));
     if (preg_match("/^([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)\\/([^\\/]+)(\\/(1))?\$/", rtrim($launchOptions->imageId, '/'), $imageChunks)) {
         $publisher = $imageChunks[1];
         $offer = $imageChunks[2];
         $sku = $imageChunks[3];
         $version = $imageChunks[4];
         $isMarketPlaceImage = isset($imageChunks[5]) ? true : false;
         if ($isMarketPlaceImage) {
             $plan = new PlanProperties($sku, $publisher, $offer);
         }
         $storageProfile->setImageReference(['publisher' => $publisher, 'offer' => $offer, 'sku' => $sku, 'version' => $version]);
     } else {
         throw new \Exception("Image definition '{$launchOptions->imageId}' is not supported");
     }
     $vmProps = new VirtualMachineProperties(["vmSize" => $launchOptions->serverType], $networkProfile, $storageProfile, $osProfile);
     // Set availability set if configured.
     if ($launchOptions->availZone) {
         $vmProps->availabilitySet = ['id' => sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/availabilitySets/%s", $subscriptionId, $launchOptions->azureResourceGroup, $launchOptions->availZone)];
     }
     $vmData = new CreateVirtualMachine($DBServer->serverId, $launchOptions->cloudLocation, $vmProps);
     $vmData->tags = $DBServer->getAzureTags();
     if (isset($plan)) {
         $vmData->setPlan($plan);
     }
     $azure->compute->virtualMachine->create($subscriptionId, $launchOptions->azureResourceGroup, $vmData);
     $DBServer->setOsType($isWindows ? 'windows' : 'linux');
     $instanceTypeInfo = $this->getInstanceType($launchOptions->serverType, $environment, $launchOptions->cloudLocation);
     /* @var $instanceTypeInfo CloudInstanceType */
     $DBServer->SetProperties([\AZURE_SERVER_PROPERTIES::SERVER_NAME => $DBServer->serverId, \AZURE_SERVER_PROPERTIES::ADMIN_PASSWORD => $adminPassword, \AZURE_SERVER_PROPERTIES::RESOURCE_GROUP => $launchOptions->azureResourceGroup, \AZURE_SERVER_PROPERTIES::CLOUD_LOCATION => $launchOptions->cloudLocation, \AZURE_SERVER_PROPERTIES::AVAIL_SET => $launchOptions->availZone, \AZURE_SERVER_PROPERTIES::NETWORK_INTERFACE => $launchOptions->azureNicName, \AZURE_SERVER_PROPERTIES::PUBLIC_IP_NAME => $launchOptions->azurePublicIpName, \SERVER_PROPERTIES::INFO_INSTANCE_VCPUS => $instanceTypeInfo ? $instanceTypeInfo->vcpus : null]);
     $params = ['type' => $launchOptions->serverType];
     if ($instanceTypeInfo) {
         $params['instanceTypeName'] = $instanceTypeInfo->name;
     }
     $DBServer->imageId = $launchOptions->imageId;
     $DBServer->update($params);
     $DBServer->cloudLocation = $launchOptions->cloudLocation;
     $DBServer->cloudLocationZone = $launchOptions->availZone;
     // we set server history here
     $DBServer->getServerHistory()->update(['cloudServerId' => $DBServer->serverId]);
     return $DBServer;
 }
 public function FarmCreate($Name, $Description = "", $ProjectID = "", array $Configuration = array())
 {
     $this->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE);
     $governance = new Scalr_Governance($this->Environment->id);
     $ProjectID = strtolower($ProjectID);
     $response = $this->CreateInitialResponse();
     $Name = $this->stripValue($Name);
     $Description = $this->stripValue($Description);
     if (!$Name || strlen($Name) < 5) {
         throw new Exception('Name should be at least 5 characters');
     }
     if ($Configuration['vpc_region'] && !$Configuration['vpc_id']) {
         throw new Exception("VPC ID is required if VPC region was specified");
     }
     if (!$Configuration['vpc_region'] && $Configuration['vpc_id']) {
         throw new Exception("VPC Region is required if VPC ID was specified");
     }
     // VPC Governance validation
     $vpcGovernance = $governance->getValue('ec2', 'aws.vpc');
     if ($vpcGovernance) {
         $vpcGovernanceRegions = $governance->getValue('ec2', 'aws.vpc', 'regions');
         if (!$Configuration['vpc_region']) {
             throw new Exception("VPC configuration is required according to governance settings");
         }
         if (!in_array($Configuration['vpc_region'], array_keys($vpcGovernanceRegions))) {
             throw new Exception(sprintf("Only %s region(s) allowed according to governance settings", implode(', ', array_keys($vpcGovernanceRegions))));
         }
         if (!in_array($Configuration['vpc_id'], $vpcGovernanceRegions[$Configuration['vpc_region']]['ids'])) {
             throw new Exception(sprintf("Only %s VPC(s) allowed according to governance settings", implode(', ', $vpcGovernanceRegions[$Configuration['vpc_region']]['ids'])));
         }
     }
     $dbFarm = new DBFarm();
     $dbFarm->ClientID = $this->user->getAccountId();
     $dbFarm->EnvID = $this->Environment->id;
     $dbFarm->Status = FARM_STATUS::TERMINATED;
     $dbFarm->createdByUserId = $this->user->getId();
     $dbFarm->createdByUserEmail = $this->user->getEmail();
     $dbFarm->changedByUserId = $this->user->getId();
     $dbFarm->changedTime = microtime();
     $dbFarm->Name = $Name;
     $dbFarm->RolesLaunchOrder = 0;
     $dbFarm->Comments = $Description;
     $dbFarm->save();
     //Associates cost analytics project with the farm.
     $dbFarm->setProject(!empty($ProjectID) ? $ProjectID : null);
     if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
         // for created farm
     }
     if (!$Configuration['timezone']) {
         $Configuration['timezone'] = date_default_timezone_get();
     }
     $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $Configuration['timezone']);
     if ($Configuration['vpc_region']) {
         $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $Configuration['vpc_id']);
         $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $Configuration['vpc_region']);
     }
     $response->FarmID = $dbFarm->ID;
     return $response;
 }
Esempio n. 8
0
 /**
  * @param   int         $farmId
  * @param   int         $expirePeriod
  * @param   bool        $manageable
  * @param   string      $owner
  * @param   int         $chefServerId
  * @param   string      $projectId
  * @param   int         $status
  * @throws  Exception
  * @throws  Scalr_Exception_Core
  * @throws  Scalr_Exception_InsufficientPermissions
  */
 public function xListFarmsAction($farmId = null, $expirePeriod = null, $manageable = false, $owner = null, $chefServerId = null, $projectId = null, $status = null)
 {
     $this->request->restrictAccess([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS]);
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $leaseStatus = $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE);
     $f = new Entity\Farm();
     $sql = "\n            SELECT {$f->fields('f')}, au.email AS ownerEmail,\n                (SELECT " . Entity\Farm::getUserTeamOwnershipSql($this->getUser()->id) . ") AS farmTeamIdPerm,\n                GROUP_CONCAT(DISTINCT at.name SEPARATOR ', ') AS farmTeams,\n                GROUP_CONCAT(DISTINCT behavior) AS behaviors,\n                (SELECT COUNT(*) FROM farm_roles WHERE farmid = f.id) AS rolesCnt,\n                (SELECT COUNT(*) FROM dns_zones WHERE farm_id = f.id) AS zonesCnt,\n                (SELECT COUNT(*) FROM server_alerts WHERE farm_id= f.id AND status = ?) AS alertsCnt,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?,?,?,?)) AS runningServers,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?)) AS suspendedServers,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?)) AS nonRunningServers\n            FROM {$f->table('f')}\n            LEFT JOIN account_users au ON au.id = f.created_by_id\n            LEFT JOIN farm_teams ft ON ft.farm_id = {$f->columnId('f')}\n            LEFT JOIN account_teams at ON at.id = ft.team_id\n            LEFT JOIN farm_roles fr ON fr.farmid = {$f->columnId('f')}\n            LEFT JOIN role_behaviors rb ON rb.role_id = fr.role_id\n            WHERE {$f->columnEnvId('f')} = ?\n            AND :FILTER:\n            AND " . $this->request->getFarmSqlQuery($manageable ? Acl::PERM_FARMS_UPDATE : null);
     $args = [Entity\Server\Alert::STATUS_FAILED, Entity\Server::STATUS_PENDING, Entity\Server::STATUS_INIT, Entity\Server::STATUS_RUNNING, Entity\Server::STATUS_TEMPORARY, Entity\Server::STATUS_RESUMING, Entity\Server::STATUS_SUSPENDED, Entity\Server::STATUS_PENDING_SUSPEND, Entity\Server::STATUS_TERMINATED, Entity\Server::STATUS_PENDING_TERMINATE, $this->getEnvironmentId()];
     if ($leaseStatus && $expirePeriod) {
         $dt = new DateTime();
         $dt->add(new DateInterval('P' . $expirePeriod . 'D'));
         $sql .= " AND EXISTS (\n                        SELECT 1 FROM farm_settings\n                        WHERE farm_settings.farmid = f.id\n                        AND farm_settings.name = ?\n                        AND farm_settings.value != ''\n                        AND farm_settings.value < ?\n                    ) AND f.status = ?";
         $args[] = Entity\FarmSetting::LEASE_TERMINATE_DATE;
         $args[] = $dt->format('Y-m-d H:i:s');
         $args[] = Entity\Farm::STATUS_RUNNING;
     }
     if ($farmId) {
         $sql .= ' AND f.id = ?';
         $args[] = $farmId;
     }
     if ($owner) {
         if ($owner == 'me') {
             $sql .= " AND {$f->columnOwnerId('f')} = ?";
             $args[] = $this->getUser()->id;
         } else {
             if ($owner == 'team') {
                 $sql .= " AND " . Entity\Farm::getUserTeamOwnershipSql($this->getUser()->id);
             }
         }
     }
     if ($chefServerId) {
         $sql .= " AND f.id IN (\n                SELECT fr.farmid\n                FROM farm_roles fr\n                INNER JOIN farm_role_settings frs1 ON fr.id = frs1.farm_roleid AND frs1.name = ? AND frs1.value = ?\n                INNER JOIN farm_role_settings frs2 ON fr.id = frs2.farm_roleid AND frs2.name = ? AND frs2.value = ?\n            )";
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_SERVER_ID;
         $args[] = $chefServerId;
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_BOOTSTRAP;
         $args[] = 1;
     }
     if ($this->getContainer()->analytics->enabled && $projectId) {
         $sql .= " AND EXISTS (\n                SELECT 1 FROM farm_settings\n                WHERE farm_settings.farmid = f.id\n                AND farm_settings.name = " . $this->db->qstr(Entity\FarmSetting::PROJECT_ID) . "\n                AND farm_settings.value = ?) ";
         $args[] = $projectId;
     }
     $sql .= " GROUP BY {$f->columnId('f')}";
     $response = $this->buildResponseFromSql2($sql, array('id', 'name', 'dtadded', 'ownerEmail', 'status'), array('f.name', 'f.id', 'f.comments'), $args);
     foreach ($response["data"] as &$r) {
         $farm = new Entity\Farm();
         $farm->load($r);
         $row = get_object_vars($farm);
         $row['ownerEmail'] = $r['ownerEmail'];
         $row['farmTeams'] = $r['farmTeams'];
         $row['behaviors'] = $r['behaviors'];
         $row['rolesCnt'] = $r['rolesCnt'];
         $row['zonesCnt'] = $r['zonesCnt'];
         $row['alertsCnt'] = $r['alertsCnt'];
         $row['runningServers'] = $r['runningServers'];
         $row['suspendedServers'] = $r['suspendedServers'];
         $row['nonRunningServers'] = $r['nonRunningServers'];
         $row['added'] = Scalr_Util_DateTime::convertTz($farm->added);
         $row['lock'] = $farm->settings[Entity\FarmSetting::LOCK];
         if ($row['lock']) {
             try {
                 $farm->checkLocked();
             } catch (\Scalr\Exception\LockedException $e) {
                 $row['lockComment'] = $e->getMessage();
             }
         }
         if ($leaseStatus && $farm->settings[Entity\FarmSetting::LEASE_STATUS]) {
             $row['lease'] = $farm->settings[Entity\FarmSetting::LEASE_NOTIFICATION_SEND] ? 'Expire' : $farm->settings[Entity\FarmSetting::LEASE_STATUS];
             if ($row['lease'] == 'Expire') {
                 $dt = new DateTime();
                 $td = new DateTime($farm->settings[Entity\FarmSetting::LEASE_TERMINATE_DATE]);
                 $days = 0;
                 $hours = 1;
                 $interval = $dt->diff($td);
                 if ($interval) {
                     $days = $interval->days;
                     $hours = $interval->h ? $interval->h : 1;
                 }
                 $row['leaseMessage'] = sprintf('Your farm lease is about to expire in %d %s, after which this farm will be terminated', $days ? $days : $hours, $days ? $days > 1 ? 'days' : 'day' : ($hours > 1 ? 'hours' : 'hour'));
             }
         }
         $behaviors = explode(',', $row['behaviors']);
         $row["havemysqlrole"] = in_array(ROLE_BEHAVIORS::MYSQL, $behaviors);
         $row["havemysql2role"] = in_array(ROLE_BEHAVIORS::MYSQL2, $behaviors);
         $row["havepgrole"] = in_array(ROLE_BEHAVIORS::POSTGRESQL, $behaviors);
         $row["haveredisrole"] = in_array(ROLE_BEHAVIORS::REDIS, $behaviors);
         $row["haverabbitmqrole"] = in_array(ROLE_BEHAVIORS::RABBITMQ, $behaviors);
         $row["havemongodbrole"] = in_array(ROLE_BEHAVIORS::MONGODB, $behaviors);
         $row["haveperconarole"] = in_array(ROLE_BEHAVIORS::PERCONA, $behaviors);
         $row["havemariadbrole"] = in_array(ROLE_BEHAVIORS::MARIADB, $behaviors);
         $row['statusTxt'] = Entity\Farm::getStatusName($farm->status);
         if ($row['status'] == Entity\Farm::STATUS_RUNNING) {
             $row['shortcuts'] = [];
             foreach (\Scalr\Model\Entity\ScriptShortcut::find([['farmId' => $farm->id], ['farmRoleId' => null]]) as $shortcut) {
                 /* @var $shortcut \Scalr\Model\Entity\ScriptShortcut */
                 $row['shortcuts'][] = array('id' => $shortcut->id, 'name' => $shortcut->getScriptName());
             }
         }
         $row['farmOwnerIdPerm'] = $farm->ownerId && $this->getUser()->id == $farm->ownerId;
         $row['farmTeamIdPerm'] = !!$r['farmTeamIdPerm'];
         $r = $row;
     }
     $this->response->data($response);
 }
Esempio n. 9
0
 public function xBuildAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int'), 'launch' => array('type' => 'bool')));
     if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) {
         if ($this->errors['error_count'] != 0) {
             $this->response->failure();
             $this->response->data(array('errors' => $this->errors));
             return;
         }
     }
     $farm = $this->getParam('farm');
     $client = Client::Load($this->user->getAccountId());
     if ($this->getParam('farmId')) {
         $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
         $this->user->getPermissions()->validate($dbFarm);
         $this->request->restrictFarmAccess($dbFarm, Acl::PERM_FARMS_MANAGE);
         $dbFarm->isLocked();
         if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) {
             $userName = '******';
             $changed = explode(' ', $this->getParam('changed'));
             $changedTime = intval($changed[1]);
             try {
                 $user = new Scalr_Account_User();
                 $user->loadById($dbFarm->changedByUserId);
                 $userName = $user->getEmail();
             } catch (Exception $e) {
             }
             $this->response->failure();
             $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime))));
             return;
         }
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
         $bNew = false;
     } else {
         $this->request->restrictFarmAccess(null, Acl::PERM_FARMS_MANAGE);
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
         $dbFarm = new DBFarm();
         $dbFarm->ClientID = $this->user->getAccountId();
         $dbFarm->EnvID = $this->getEnvironmentId();
         $dbFarm->Status = FARM_STATUS::TERMINATED;
         $dbFarm->createdByUserId = $this->user->getId();
         $dbFarm->createdByUserEmail = $this->user->getEmail();
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
         $bNew = true;
     }
     if ($this->getParam('farm')) {
         $dbFarm->Name = $this->request->stripValue($farm['name']);
         $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder'];
         $dbFarm->Comments = $this->request->stripValue($farm['description']);
     }
     if (empty($dbFarm->Name)) {
         throw new Exception(_("Farm name required"));
     }
     if ($bNew) {
         $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL;
     } else {
         if ($dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP)) {
             if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->createdByUserId) {
                 $user = (new Scalr_Account_User())->loadById($farm['owner']);
                 $dbFarm->createdByUserId = $user->getId();
                 $dbFarm->createdByUserEmail = $user->getEmail();
                 // TODO: move to subclass \Farm\Setting\OwnerHistory
                 $history = unserialize($dbFarm->GetSetting(DBFarm::SETTING_OWNER_HISTORY));
                 if (!is_array($history)) {
                     $history = [];
                 }
                 $history[] = ['newId' => $user->getId(), 'newEmail' => $user->getEmail(), 'changedById' => $this->user->getId(), 'changedByEmail' => $this->user->getEmail(), 'dt' => date('Y-m-d H:i:s')];
                 $dbFarm->SetSetting(DBFarm::SETTING_OWNER_HISTORY, serialize($history));
             }
             $dbFarm->teamId = is_numeric($farm['teamOwner']) && $farm['teamOwner'] > 0 ? $farm['teamOwner'] : NULL;
         }
     }
     $dbFarm->save();
     $governance = new Scalr_Governance($this->getEnvironmentId());
     if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
         // for created farm
     }
     if (isset($farm['variables'])) {
         $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true);
     }
     if (!$farm['timezone']) {
         $farm['timezone'] = date_default_timezone_get();
     }
     $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']);
     $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY, $farm[DBFarm::SETTING_SZR_UPD_REPOSITORY]);
     $dbFarm->SetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE, $farm[DBFarm::SETTING_SZR_UPD_SCHEDULE]);
     if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) {
         $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     }
     if ($this->getContainer()->analytics->enabled) {
         //Cost analytics project must be set for the Farm object
         $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null);
     }
     $virtualFarmRoles = array();
     $roles = $this->getParam('roles');
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if (strpos($role['farm_role_id'], "virtual_") !== false) {
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']);
                 $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID;
             }
         }
     }
     $usedPlatforms = array();
     $dbFarmRolesList = array();
     $newFarmRolesList = array();
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if ($role['farm_role_id']) {
                 if ($virtualFarmRoles[$role['farm_role_id']]) {
                     $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']];
                 }
                 $update = true;
                 $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']);
                 $dbRole = DBRole::loadById($dbFarmRole->RoleID);
                 $role['role_id'] = $dbFarmRole->RoleID;
                 if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) {
                     $dbFarmRole->CloudLocation = $role['cloud_location'];
                 }
             } else {
                 $update = false;
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']);
             }
             if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                 $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES];
             }
             if ($dbFarmRole->NewRoleID) {
                 continue;
             }
             if ($update) {
                 $dbFarmRole->LaunchIndex = (int) $role['launch_index'];
                 $dbFarmRole->Alias = $role['alias'];
                 $dbFarmRole->Save();
             }
             $usedPlatforms[$role['platform']] = 1;
             $oldRoleSettings = $dbFarmRole->GetAllSettings();
             // Update virtual farm_role_id with actual value
             $scripts = (array) $role['scripting'];
             if (count($virtualFarmRoles) > 0) {
                 array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
                 array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
             }
             $dbFarmRole->ClearSettings("chef.");
             if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) {
                 foreach ($role['scaling_settings'] as $k => $v) {
                     $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG);
                 }
             }
             foreach ($role['settings'] as $k => $v) {
                 $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG);
             }
             /****** Scaling settings ******/
             $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
             $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array());
             //TODO: optimize this code...
             $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID));
             // 5 = Time based scaling -> move to constants
             if ($role['scaling'][5]) {
                 foreach ($role['scaling'][5] as $scal_period) {
                     $chunks = explode(":", $scal_period['id']);
                     $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n                            farm_roleid\t\t= ?,\n                            start_time\t\t= ?,\n                            end_time\t\t= ?,\n                            days_of_week\t= ?,\n                            instances_count\t= ?\n                        ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3]));
                 }
             }
             /*****************/
             /* Update role params */
             $dbFarmRole->SetParameters((array) $role['params']);
             /* End of role params management */
             /* Add script options to databse */
             $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']);
             /* End of scripting section */
             /* Add services configuration */
             $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']);
             /* End of scripting section */
             /* Add storage configuration */
             if (isset($role['storages'])) {
                 if (isset($role['storages']['configs'])) {
                     $dbFarmRole->getStorage()->setConfigs($role['storages']['configs']);
                 }
             }
             $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true);
             foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                 $behavior->onFarmSave($dbFarm, $dbFarmRole);
             }
             /**
              * Platform specified updates
              */
             if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
                 \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
             if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) {
                 Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
             $dbFarmRolesList[] = $dbFarmRole;
             $newFarmRolesList[] = $dbFarmRole->ID;
         }
     }
     if (!$this->getParam('roleUpdate')) {
         foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
             if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) {
                 $dbFarmRole->Delete();
             }
         }
     }
     $dbFarm->save();
     if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) {
         $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time());
     }
     if ($this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) {
         $this->user->getPermissions()->validate($dbFarm);
         $dbFarm->isLocked();
         Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id));
         $this->response->success('Farm successfully saved and launched');
     } else {
         $this->response->success('Farm successfully saved');
     }
     $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew));
 }
Esempio n. 10
0
 public function xListFarmsAction()
 {
     $this->request->restrictFarmAccess();
     $this->request->defineParams(array('clientId' => array('type' => 'int'), 'farmId' => array('type' => 'int'), 'sort' => array('type' => 'json'), 'expirePeriod' => array('type' => 'int')));
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $leaseStatus = $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE);
     $sql = 'SELECT f.clientid, f.id, f.name, f.status, f.dtadded, f.created_by_id, f.created_by_email, ats.name AS team_name, ats.description AS team_description, ats.id as team_id FROM farms f LEFT JOIN account_teams ats ON ats.id = f.team_id WHERE env_id = ? AND :FILTER:';
     $args = array($this->getEnvironmentId());
     if ($leaseStatus && $this->getParam('expirePeriod')) {
         $dt = new DateTime();
         $dt->add(new DateInterval('P' . $this->getParam('expirePeriod') . 'D'));
         $sql = str_replace('FROM farms f', 'FROM farms f LEFT JOIN farm_settings fs ON f.id = fs.farmid', $sql);
         $sql = str_replace('WHERE', 'WHERE fs.name = ? AND fs.value < ? AND fs.value != "" AND f.status = ? AND', $sql);
         array_unshift($args, Entity\FarmSetting::LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'), FARM_STATUS::RUNNING);
     }
     if ($this->getParam('farmId')) {
         $sql .= ' AND f.id = ?';
         $args[] = $this->getParam('farmId');
     }
     if ($this->getParam('clientId')) {
         $sql .= ' AND clientid = ?';
         $args[] = $this->getParam('clientId');
     }
     if ($this->getParam('status') != '') {
         $sql .= ' AND status = ?';
         $args[] = $this->getParam('status');
     }
     $owner = $this->getParam('owner');
     $permission = $this->getParam('manageable') ? Acl::PERM_FARMS_MANAGE : null;
     $allowedResourceFarms = $this->request->isAllowed(Acl::RESOURCE_FARMS, $permission);
     if (!$allowedResourceFarms || $owner) {
         $q = [];
         if (($this->request->isAllowed(Acl::RESOURCE_TEAM_FARMS, $permission) || $allowedResourceFarms) && ($owner == '' || $owner == 'team')) {
             $t = array_map(function ($t) {
                 return $t['id'];
             }, $this->user->getTeams());
             if (count($t)) {
                 $q[] = 'team_id IN(' . join(',', $t) . ')';
             }
         }
         if (($this->request->isAllowed(Acl::RESOURCE_OWN_FARMS, $permission) || $allowedResourceFarms) && ($owner == '' || $owner == 'me')) {
             $q[] = 'created_by_id = ?';
             $args[] = $this->request->getUser()->getId();
         }
         if (count($q)) {
             $sql .= ' AND (' . join(' OR ', $q) . ')';
         } else {
             $sql .= ' AND false';
             // no permissions
         }
     }
     if ($this->getParam('chefServerId')) {
         $sql .= ' AND f.id IN (
             SELECT fr.farmid
             FROM farm_roles fr
             INNER JOIN farm_role_settings frs1 ON fr.id = frs1.farm_roleid AND frs1.name = ? AND frs1.value = ?
             INNER JOIN farm_role_settings frs2 ON fr.id = frs2.farm_roleid AND frs2.name = ? AND frs2.value = ?
         )';
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_SERVER_ID;
         $args[] = (int) $this->getParam('chefServerId');
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_BOOTSTRAP;
         $args[] = 1;
     }
     if ($this->getContainer()->analytics->enabled) {
         if ($this->getParam('projectId')) {
             $sql .= " AND EXISTS (\n                    SELECT 1 FROM farm_settings\n                    WHERE farm_settings.farmid = f.id\n                    AND farm_settings.name = " . $this->db->qstr(Entity\FarmSetting::PROJECT_ID) . "\n                    AND farm_settings.value = ?) ";
             $args[] = $this->getParam('projectId');
         }
     }
     $response = $this->buildResponseFromSql2($sql, array('id', 'name', 'dtadded', 'created_by_email', 'status', 'team_name'), array('f.name', 'f.id', 'f.comments'), $args);
     foreach ($response["data"] as &$row) {
         $servers = $this->db->GetRow("\n                SELECT SUM(IF(`status` IN (?,?,?,?,?),1,0)) AS running_servers,\n                    SUM(IF(`status` IN (?,?),1,0)) AS suspended_servers,\n                    SUM(IF(`status` IN (?,?),1,0)) AS non_running_servers\n                FROM `servers` WHERE `farm_id` = ?\n            ", [Entity\Server::STATUS_PENDING, Entity\Server::STATUS_INIT, Entity\Server::STATUS_RUNNING, Entity\Server::STATUS_TEMPORARY, Entity\Server::STATUS_RESUMING, Entity\Server::STATUS_SUSPENDED, Entity\Server::STATUS_PENDING_SUSPEND, Entity\Server::STATUS_TERMINATED, Entity\Server::STATUS_PENDING_TERMINATE, $row['id']]);
         if (is_null($servers['running_servers'])) {
             $servers = ['running_servers' => 0, 'suspended_servers' => 0, 'non_running_servers' => 0];
         }
         $row = array_merge($row, $servers);
         $row["roles"] = $this->db->GetOne("SELECT COUNT(*) FROM farm_roles WHERE farmid='{$row['id']}'");
         $row["zones"] = $this->db->GetOne("SELECT COUNT(*) FROM dns_zones WHERE farm_id='{$row['id']}'");
         //TODO: Use Alerts class
         $row['alerts'] = $this->db->GetOne("SELECT COUNT(*) FROM server_alerts WHERE farm_id='{$row['id']}' AND status='failed'");
         $row['dtadded'] = Scalr_Util_DateTime::convertTz($row["dtadded"], 'M j, Y H:i');
         $dbFarm = DBFarm::LoadByID($row['id']);
         $row['lock'] = $dbFarm->GetSetting(Entity\FarmSetting::LOCK);
         if ($row['lock']) {
             $row['lock_comment'] = $dbFarm->isLocked(false);
         }
         if ($leaseStatus && $dbFarm->GetSetting(Entity\FarmSetting::LEASE_STATUS)) {
             $row['lease'] = $dbFarm->GetSetting(Entity\FarmSetting::LEASE_NOTIFICATION_SEND) ? 'Expire' : $dbFarm->GetSetting(Entity\FarmSetting::LEASE_STATUS);
             if ($row['lease'] == 'Expire') {
                 $dt = new DateTime();
                 $td = new DateTime($dbFarm->GetSetting(Entity\FarmSetting::LEASE_TERMINATE_DATE));
                 $days = 0;
                 $hours = 1;
                 $interval = $dt->diff($td);
                 if ($interval) {
                     $days = $interval->days;
                     $hours = $interval->h ? $interval->h : 1;
                 }
                 $row['leaseMessage'] = sprintf('Your farm lease is about to expire in %d %s, after which this farm will be terminated', $days ? $days : $hours, $days ? $days > 1 ? 'days' : 'day' : ($hours > 1 ? 'hours' : 'hour'));
             }
         }
         $b = (array) $this->db->GetAll("SELECT DISTINCT(behavior) FROM farm_roles\n                INNER JOIN role_behaviors ON role_behaviors.role_id = farm_roles.role_id WHERE farmid = ?", array($row['id']));
         $behaviors = array();
         foreach ($b as $behavior) {
             $behaviors[] = $behavior['behavior'];
         }
         $row["havemysqlrole"] = in_array(ROLE_BEHAVIORS::MYSQL, $behaviors);
         $row["havemysql2role"] = in_array(ROLE_BEHAVIORS::MYSQL2, $behaviors);
         $row["havepgrole"] = in_array(ROLE_BEHAVIORS::POSTGRESQL, $behaviors);
         $row["haveredisrole"] = in_array(ROLE_BEHAVIORS::REDIS, $behaviors);
         $row["haverabbitmqrole"] = in_array(ROLE_BEHAVIORS::RABBITMQ, $behaviors);
         $row["havemongodbrole"] = in_array(ROLE_BEHAVIORS::MONGODB, $behaviors);
         $row["haveperconarole"] = in_array(ROLE_BEHAVIORS::PERCONA, $behaviors);
         $row["havemariadbrole"] = in_array(ROLE_BEHAVIORS::MARIADB, $behaviors);
         $row['status_txt'] = FARM_STATUS::GetStatusName($row['status']);
         if ($row['status'] == FARM_STATUS::RUNNING) {
             $row['shortcuts'] = [];
             foreach (\Scalr\Model\Entity\ScriptShortcut::find([['farmId' => $row['id']], ['farmRoleId' => null]]) as $shortcut) {
                 /* @var $shortcut \Scalr\Model\Entity\ScriptShortcut */
                 $row['shortcuts'][] = array('id' => $shortcut->id, 'name' => $shortcut->getScriptName());
             }
         }
         $row['farmTeamIdPerm'] = $row['team_id'] && $this->user->isInTeam($row['team_id']);
         $row['farmOwnerIdPerm'] = $row['created_by_id'] && $this->user->getId() == $row['created_by_id'];
     }
     $this->response->data($response);
 }
Esempio n. 11
0
 public function xBuildAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'roleUpdate' => array('type' => 'int')));
     $this->request->restrictAccess(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_MANAGE);
     if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) {
         if ($this->errors['error_count'] != 0) {
             $this->response->failure();
             $this->response->data(array('errors' => $this->errors));
             return;
         }
     }
     $farm = $this->getParam('farm');
     $client = Client::Load($this->user->getAccountId());
     if ($this->getParam('farmId')) {
         $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
         $this->user->getPermissions()->validate($dbFarm);
         $dbFarm->isLocked();
         if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) {
             $userName = '******';
             $changed = explode(' ', $this->getParam('changed'));
             $changedTime = intval($changed[1]);
             try {
                 $user = new Scalr_Account_User();
                 $user->loadById($dbFarm->changedByUserId);
                 $userName = $user->getEmail();
             } catch (Exception $e) {
             }
             $this->response->failure();
             $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime))));
             return;
         }
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
     } else {
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
         $dbFarm = new DBFarm();
         $dbFarm->Status = FARM_STATUS::TERMINATED;
         $dbFarm->createdByUserId = $this->user->getId();
         $dbFarm->createdByUserEmail = $this->user->getEmail();
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
     }
     if ($this->getParam('farm')) {
         $dbFarm->Name = strip_tags($farm['name']);
         $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder'];
         $dbFarm->Comments = trim(strip_tags($farm['description']));
     }
     if (empty($dbFarm->Name)) {
         throw new Exception(_("Farm name required"));
     }
     $dbFarm->save();
     $governance = new Scalr_Governance($this->getEnvironmentId());
     if ($governance->isEnabled(Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(DBFarm::SETTING_LEASE_STATUS, 'Active');
     }
     if (isset($farm['variables'])) {
         $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
         $variables->setValues($farm['variables'], 0, $dbFarm->ID, 0, '', false);
     }
     if (!$farm['timezone']) {
         $farm['timezone'] = date_default_timezone_get();
     }
     $dbFarm->SetSetting(DBFarm::SETTING_TIMEZONE, $farm['timezone']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_ID, $farm['vpc_id']);
     $dbFarm->SetSetting(DBFarm::SETTING_EC2_VPC_REGION, $farm['vpc_region']);
     if (!$dbFarm->GetSetting(DBFarm::SETTING_CRYPTO_KEY)) {
         $dbFarm->SetSetting(DBFarm::SETTING_CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     }
     $virtualFarmRoles = array();
     $roles = $this->getParam('roles');
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if (strpos($role['farm_role_id'], "virtual_") !== false) {
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']);
                 $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID;
             }
         }
     }
     $usedPlatforms = array();
     $dbFarmRolesList = array();
     $newFarmRolesList = array();
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if ($role['farm_role_id']) {
                 if ($virtualFarmRoles[$role['farm_role_id']]) {
                     $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']];
                 }
                 $update = true;
                 $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']);
                 $dbRole = DBRole::loadById($dbFarmRole->RoleID);
                 $role['role_id'] = $dbFarmRole->RoleID;
                 if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) {
                     $dbFarmRole->CloudLocation = $role['cloud_location'];
                 }
             } else {
                 $update = false;
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']);
             }
             if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                 $role['settings'][DBFarmRole::SETTING_SCALING_MAX_INSTANCES] = $role['settings'][DBFarmRole::SETTING_SCALING_MIN_INSTANCES];
             }
             if ($dbFarmRole->NewRoleID) {
                 continue;
             }
             if ($update) {
                 $dbFarmRole->LaunchIndex = (int) $role['launch_index'];
                 $dbFarmRole->Alias = $role['alias'];
                 $dbFarmRole->Save();
             }
             $usedPlatforms[$role['platform']] = 1;
             $oldRoleSettings = $dbFarmRole->GetAllSettings();
             // Update virtual farm_role_id with actual value
             $scripts = (array) $role['scripting'];
             if (count($virtualFarmRoles) > 0) {
                 array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
                 array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
             }
             //Audit log start
             //!TODO Enable Audit log for Farm Builder
             //             $auditLog = $this->getEnvironment()->auditLog;
             //             $docRoleSettingsBefore = new FarmRoleSettingsDocument($oldRoleSettings);
             //             $docRoleSettingsBefore['farmroleid'] = $dbFarmRole->ID;
             //             $docRoleSettings = new FarmRoleSettingsDocument(array_merge((array)$role['scaling_settings'], (array)$role['settings']));
             //             $docRoleSettings['farmroleid'] = $dbFarmRole->ID;
             $dbFarmRole->ClearSettings("chef.");
             if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) {
                 foreach ($role['scaling_settings'] as $k => $v) {
                     $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG);
                 }
             }
             foreach ($role['settings'] as $k => $v) {
                 $dbFarmRole->SetSetting($k, $v, DBFarmRole::TYPE_CFG);
             }
             //             $auditLog->log('Farm has been saved', array(AuditLogTags::TAG_UPDATE), $docRoleSettings, $docRoleSettingsBefore);
             //             unset($docRoleSettings);
             //             unset($docRoleSettingsBefore);
             //Audit log finish
             /****** Scaling settings ******/
             $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
             $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array());
             //TODO: optimize this code...
             $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID));
             // 5 = Time based scaling -> move to constants
             if ($role['scaling'][5]) {
                 foreach ($role['scaling'][5] as $scal_period) {
                     $chunks = explode(":", $scal_period['id']);
                     $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n                            farm_roleid\t\t= ?,\n                            start_time\t\t= ?,\n                            end_time\t\t= ?,\n                            days_of_week\t= ?,\n                            instances_count\t= ?\n                        ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3]));
                 }
             }
             /*****************/
             /* Update role params */
             $dbFarmRole->SetParameters((array) $role['params']);
             /* End of role params management */
             /* Add script options to databse */
             $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']);
             /* End of scripting section */
             /* Add services configuration */
             $dbFarmRole->SetServiceConfigPresets((array) $role['config_presets']);
             /* End of scripting section */
             /* Add storage configuration */
             //try {
             $dbFarmRole->getStorage()->setConfigs((array) $role['storages']['configs']);
             //} catch (FarmRoleStorageException $e) {
             //    $errors[] = array('farm_role_id' => 1, 'tab' => 'storage', 'error' => $e->getMessage());
             //}
             $farmRoleVariables->setValues($role['variables'], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false);
             Scalr_Helpers_Dns::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                 $behavior->onFarmSave($dbFarm, $dbFarmRole);
             }
             /**
              * Platfrom specified updates
              */
             if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
                 Modules_Platforms_Ec2_Helpers_Ebs::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 Modules_Platforms_Ec2_Helpers_Eip::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 Modules_Platforms_Ec2_Helpers_Elb::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
             if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) {
                 Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
             $dbFarmRolesList[] = $dbFarmRole;
             $newFarmRolesList[] = $dbFarmRole->ID;
         }
     }
     if (!$this->getParam('roleUpdate')) {
         foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
             if (!$dbFarmRole->NewRoleID && !in_array($dbFarmRole->ID, $newFarmRolesList)) {
                 $dbFarmRole->Delete();
             }
         }
     }
     if ($usedPlatforms[SERVER_PLATFORMS::CLOUDSTACK]) {
         Modules_Platforms_Cloudstack_Helpers_Cloudstack::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EC2]) {
         Modules_Platforms_Ec2_Helpers_Ec2::farmSave($dbFarm, $dbFarmRolesList);
     }
     if ($usedPlatforms[SERVER_PLATFORMS::EUCALYPTUS]) {
         Modules_Platforms_Eucalyptus_Helpers_Eucalyptus::farmSave($dbFarm, $dbFarmRolesList);
     }
     $dbFarm->save();
     if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) {
         $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time());
     }
     $this->response->success('Farm successfully saved');
     $this->response->data(array('farmId' => $dbFarm->ID));
 }
Esempio n. 12
0
 /**
  * Farm launched
  *
  * @param FarmLaunchedEvent $event
  */
 public function OnFarmLaunched(FarmLaunchedEvent $event)
 {
     $DBFarm = DBFarm::LoadByID($this->FarmID);
     // TODO: Refactoting -> Move to DBFarm class
     $this->DB->Execute("UPDATE farms SET status=?, dtlaunched=NOW() WHERE id=?", array(FARM_STATUS::RUNNING, $this->FarmID));
     $governance = new Scalr_Governance($DBFarm->EnvID);
     if ($governance->isEnabled(Scalr_Governance::GENERAL_LEASE) && $DBFarm->GetSetting(DBFarm::SETTING_LEASE_STATUS)) {
         $dt = new DateTime();
         $dt->add(new DateInterval('P' . intval($governance->getValue(Scalr_Governance::GENERAL_LEASE, 'defaultLifePeriod')) . 'D'));
         $DBFarm->SetSetting(DBFarm::SETTING_LEASE_EXTEND_CNT, 0);
         $DBFarm->SetSetting(DBFarm::SETTING_LEASE_TERMINATE_DATE, $dt->format('Y-m-d H:i:s'));
         $DBFarm->SetSetting(DBFarm::SETTING_LEASE_NOTIFICATION_SEND, '');
     }
     $roles = $DBFarm->GetFarmRoles();
     foreach ($roles as $dbFarmRole) {
         if ($dbFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ENABLED) && !$DBFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
             $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
             $scalingDecision = $scalingManager->makeScalingDecition();
             if ($scalingDecision == Scalr_Scaling_Decision::UPSCALE) {
                 $ServerCreateInfo = new ServerCreateInfo($dbFarmRole->Platform, $dbFarmRole);
                 try {
                     $DBServer = Scalr::LaunchServer($ServerCreateInfo, null, true, "Farm launched", isset($event->userId) ? $event->userId : null);
                     $dbFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_DATETIME, time(), DBFarmRole::TYPE_LCL);
                     Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Farm %s, role %s scaling up. Starting new instance. ServerID = %s.", $DBFarm->Name, $dbFarmRole->GetRoleObject()->name, $DBServer->serverId)));
                 } catch (Exception $e) {
                     Logger::getLogger(LOG_CATEGORY::SCALING)->error($e->getMessage());
                 }
             }
         }
     }
 }
Esempio n. 13
0
 public function getBaseConfiguration(DBServer $dbServer, $isHostInit = false)
 {
     $configuration = new stdClass();
     $dbFarmRole = $dbServer->GetFarmRoleObject();
     //Storage
     try {
         if ($dbFarmRole) {
             $storage = new FarmRoleStorage($dbFarmRole);
             $volumes = $storage->getVolumesConfigs($dbServer->index, $isHostInit);
             if (!empty($volumes)) {
                 $configuration->volumes = $volumes;
             }
         }
     } catch (Exception $e) {
         $this->logger->error(new FarmLogMessage($dbServer->farmId, "Cannot init storage: {$e->getMessage()}"));
     }
     // Base
     try {
         if ($dbFarmRole) {
             $scriptingLogTimeout = $dbFarmRole->GetSetting(self::ROLE_BASE_KEEP_SCRIPTING_LOGS_TIME);
             if (!$scriptingLogTimeout) {
                 $scriptingLogTimeout = 3600;
             }
             $configuration->base = new stdClass();
             $configuration->base->keepScriptingLogsTime = $scriptingLogTimeout;
             $configuration->base->resumeStrategy = PlatformFactory::NewPlatform($dbFarmRole->Platform)->getResumeStrategy();
             $governance = new Scalr_Governance($dbFarmRole->GetFarmObject()->EnvID);
             if ($governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT)) {
                 $hostNameFormat = $governance->getValue(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_HOSTNAME_FORMAT);
             } else {
                 $hostNameFormat = $dbFarmRole->GetSetting(self::ROLE_BASE_HOSTNAME_FORMAT);
             }
             $configuration->base->hostname = !empty($hostNameFormat) ? $dbServer->applyGlobalVarsToValue($hostNameFormat) : '';
             $apiPort = $dbFarmRole->GetSetting(self::ROLE_BASE_API_PORT);
             $messagingPort = $dbFarmRole->GetSetting(self::ROLE_BASE_MESSAGING_PORT);
             $configuration->base->apiPort = $apiPort ? $apiPort : 8010;
             $configuration->base->messagingPort = $messagingPort ? $messagingPort : 8013;
         }
         //Update settings
         $updateSettings = $dbServer->getScalarizrRepository();
         $configuration->base->update = new stdClass();
         foreach ($updateSettings as $k => $v) {
             $configuration->base->update->{$k} = $v;
         }
     } catch (Exception $e) {
     }
     return $configuration;
 }
Esempio n. 14
0
 public function xBuildAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'roles' => array('type' => 'json'), 'rolesToRemove' => array('type' => 'json'), 'farm' => array('type' => 'json'), 'launch' => array('type' => 'bool')));
     if (!$this->isFarmConfigurationValid($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'))) {
         if ($this->errors['error_count'] != 0) {
             $this->response->failure();
             $this->response->data(array('errors' => $this->errors));
             return;
         }
     }
     $farm = $this->getParam('farm');
     $client = Client::Load($this->user->getAccountId());
     if ($this->getParam('farmId')) {
         $dbFarm = DBFarm::LoadByID($this->getParam('farmId'));
         $this->user->getPermissions()->validate($dbFarm);
         $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_UPDATE);
         $dbFarm->isLocked();
         if ($this->getParam('changed') && $dbFarm->changedTime && $this->getParam('changed') != $dbFarm->changedTime) {
             $userName = '******';
             $changed = explode(' ', $this->getParam('changed'));
             $changedTime = intval($changed[1]);
             try {
                 $user = new Scalr_Account_User();
                 $user->loadById($dbFarm->changedByUserId);
                 $userName = $user->getEmail();
             } catch (Exception $e) {
             }
             $this->response->failure();
             $this->response->data(array('changedFailure' => sprintf('%s changed this farm at %s', $userName, Scalr_Util_DateTime::convertTz($changedTime))));
             return;
         } else {
             if ($this->getParam('changed')) {
                 $this->checkFarmConfigurationIntegrity($this->getParam('farmId'), $this->getParam('farm'), (array) $this->getParam('roles'), (array) $this->getParam('rolesToRemove'));
             }
         }
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
         if ($this->getContainer()->analytics->enabled) {
             $projectId = $farm['projectId'];
             if (empty($projectId)) {
                 $ccId = $dbFarm->GetEnvironmentObject()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID);
                 if (!empty($ccId)) {
                     //Assigns Project automatically only if it is the one withing the Cost Center
                     $projects = ProjectEntity::findByCcId($ccId);
                     if (count($projects) == 1) {
                         $projectId = $projects->getArrayCopy()[0]->projectId;
                     }
                 }
             }
             if (!empty($projectId) && $dbFarm->GetSetting(Entity\FarmSetting::PROJECT_ID) != $projectId) {
                 $this->request->checkPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_PROJECTS);
             }
         }
         $bNew = false;
     } else {
         $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE);
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_FARMS, 1);
         $dbFarm = new DBFarm();
         $dbFarm->ClientID = $this->user->getAccountId();
         $dbFarm->EnvID = $this->getEnvironmentId();
         $dbFarm->Status = FARM_STATUS::TERMINATED;
         $dbFarm->ownerId = $this->user->getId();
         $dbFarm->changedByUserId = $this->user->getId();
         $dbFarm->changedTime = microtime();
         $bNew = true;
     }
     if ($this->getParam('farm')) {
         $dbFarm->Name = $this->request->stripValue($farm['name']);
         $dbFarm->RolesLaunchOrder = $farm['rolesLaunchOrder'];
         $dbFarm->Comments = $this->request->stripValue($farm['description']);
     }
     if (empty($dbFarm->Name)) {
         throw new Exception(_("Farm name required"));
     }
     $setFarmTeams = false;
     if ($bNew) {
         $setFarmTeams = true;
     } else {
         if ($dbFarm->ownerId == $this->user->getId() || $this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_CHANGE_OWNERSHIP)) {
             if (is_numeric($farm['owner']) && $farm['owner'] != $dbFarm->ownerId) {
                 $dbFarm->ownerId = $farm['owner'];
                 $f = Entity\Farm::findPk($dbFarm->ID);
                 Entity\FarmSetting::addOwnerHistory($f, User::findPk($farm['owner']), User::findPk($this->user->getId()));
                 $f->save();
             }
             $setFarmTeams = true;
         }
     }
     $dbFarm->save();
     if ($setFarmTeams && is_array($farm['teamOwner'])) {
         /* @var $f Entity\Farm */
         $f = Entity\Farm::findPk($dbFarm->ID);
         $f->setTeams(empty($farm['teamOwner']) ? [] : Entity\Account\Team::find([['name' => ['$in' => $farm['teamOwner']]], ['accountId' => $this->getUser()->accountId]]));
         $f->save();
     }
     if ($bNew) {
         $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_ID, $this->user->getId());
         $dbFarm->SetSetting(Entity\FarmSetting::CREATED_BY_EMAIL, $this->user->getEmail());
     }
     $governance = new Scalr_Governance($this->getEnvironmentId());
     if (!$this->getParam('farmId') && $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE)) {
         $dbFarm->SetSetting(Entity\FarmSetting::LEASE_STATUS, 'Active');
         // for created farm
     }
     if (isset($farm['variables'])) {
         $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARM);
         $variables->setValues(is_array($farm['variables']) ? $farm['variables'] : [], 0, $dbFarm->ID, 0, '', false, true);
     }
     if (!$farm['timezone']) {
         $farm['timezone'] = date_default_timezone_get();
     }
     $dbFarm->SetSetting(Entity\FarmSetting::TIMEZONE, $farm['timezone']);
     $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_ID, isset($farm["vpc_id"]) ? $farm['vpc_id'] : null);
     $dbFarm->SetSetting(Entity\FarmSetting::EC2_VPC_REGION, isset($farm["vpc_id"]) ? $farm['vpc_region'] : null);
     $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_REPOSITORY, $farm[Entity\FarmSetting::SZR_UPD_REPOSITORY]);
     $dbFarm->SetSetting(Entity\FarmSetting::SZR_UPD_SCHEDULE, $farm[Entity\FarmSetting::SZR_UPD_SCHEDULE]);
     if (!$dbFarm->GetSetting(Entity\FarmSetting::CRYPTO_KEY)) {
         $dbFarm->SetSetting(Entity\FarmSetting::CRYPTO_KEY, Scalr::GenerateRandomKey(40));
     }
     if ($this->getContainer()->analytics->enabled) {
         //Cost analytics project must be set for the Farm object
         $dbFarm->setProject(!empty($farm['projectId']) ? $farm['projectId'] : null);
     }
     $virtualFarmRoles = array();
     $roles = $this->getParam('roles');
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if (strpos($role['farm_role_id'], "virtual_") !== false) {
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index'], $role['alias']);
                 $virtualFarmRoles[$role['farm_role_id']] = $dbFarmRole->ID;
             }
         }
     }
     $usedPlatforms = array();
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), ScopeInterface::SCOPE_FARMROLE);
     if (!empty($roles)) {
         foreach ($roles as $role) {
             if ($role['farm_role_id']) {
                 if (isset($virtualFarmRoles[$role['farm_role_id']])) {
                     $role['farm_role_id'] = $virtualFarmRoles[$role['farm_role_id']];
                 }
                 $update = true;
                 $dbFarmRole = DBFarmRole::LoadByID($role['farm_role_id']);
                 $dbRole = DBRole::loadById($dbFarmRole->RoleID);
                 $role['role_id'] = $dbFarmRole->RoleID;
                 if ($dbFarmRole->Platform == SERVER_PLATFORMS::GCE) {
                     $dbFarmRole->CloudLocation = $role['cloud_location'];
                 }
             } else {
                 /** TODO:  Remove because will be handled with virtual_ **/
                 $update = false;
                 $dbRole = DBRole::loadById($role['role_id']);
                 $dbFarmRole = $dbFarm->AddRole($dbRole, $role['platform'], $role['cloud_location'], (int) $role['launch_index']);
             }
             if ($dbRole->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                 $role['settings'][Entity\FarmRoleSetting::SCALING_MAX_INSTANCES] = $role['settings'][Entity\FarmRoleSetting::SCALING_MIN_INSTANCES];
             }
             if ($update) {
                 $dbFarmRole->LaunchIndex = (int) $role['launch_index'];
                 $dbFarmRole->Alias = $role['alias'];
                 $dbFarmRole->Save();
             }
             $usedPlatforms[$role['platform']] = 1;
             $oldRoleSettings = $dbFarmRole->GetAllSettings();
             // Update virtual farm_role_id with actual value
             $scripts = (array) $role['scripting'];
             if (!empty($virtualFarmRoles)) {
                 array_walk_recursive($scripts, function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
                 array_walk_recursive($role['settings'], function (&$v, $k) use($virtualFarmRoles) {
                     if (is_string($v)) {
                         $v = str_replace(array_keys($virtualFarmRoles), array_values($virtualFarmRoles), $v);
                     }
                 });
             }
             $dbFarmRole->ClearSettings("chef.");
             if (!empty($role['scaling_settings']) && is_array($role['scaling_settings'])) {
                 foreach ($role['scaling_settings'] as $k => $v) {
                     $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG);
                 }
             }
             foreach ($role['settings'] as $k => $v) {
                 $dbFarmRole->SetSetting($k, $v, Entity\FarmRoleSetting::TYPE_CFG);
             }
             /****** Scaling settings ******/
             $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
             $scalingManager->setFarmRoleMetrics(is_array($role['scaling']) ? $role['scaling'] : array());
             //TODO: optimize this code...
             $this->db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($dbFarmRole->ID));
             // 5 = Time based scaling -> move to constants
             if (!empty($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID])) {
                 foreach ($role['scaling'][Entity\ScalingMetric::METRIC_DATE_AND_TIME_ID] as $scal_period) {
                     $chunks = explode(":", $scal_period['id']);
                     $this->db->Execute("INSERT INTO farm_role_scaling_times SET\n                            farm_roleid\t\t= ?,\n                            start_time\t\t= ?,\n                            end_time\t\t= ?,\n                            days_of_week\t= ?,\n                            instances_count\t= ?\n                        ", array($dbFarmRole->ID, $chunks[0], $chunks[1], $chunks[2], $chunks[3]));
                 }
             }
             /*****************/
             /* Add script options to databse */
             $dbFarmRole->SetScripts($scripts, (array) $role['scripting_params']);
             /* End of scripting section */
             /* Add storage configuration */
             if (isset($role['storages']['configs'])) {
                 $dbFarmRole->getStorage()->setConfigs($role['storages']['configs'], false);
             }
             $farmRoleVariables->setValues(is_array($role['variables']) ? $role['variables'] : [], $dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID, '', false, true);
             foreach (Scalr_Role_Behavior::getListForFarmRole($dbFarmRole) as $behavior) {
                 $behavior->onFarmSave($dbFarm, $dbFarmRole);
             }
             /**
              * Platform specified updates
              */
             if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
                 \Scalr\Modules\Platforms\Ec2\Helpers\EbsHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 \Scalr\Modules\Platforms\Ec2\Helpers\EipHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
                 if ($role['settings']['aws.elb.remove']) {
                     $this->request->restrictAccess(Acl::RESOURCE_AWS_ELB, Acl::PERM_AWS_ELB_MANAGE);
                 }
                 \Scalr\Modules\Platforms\Ec2\Helpers\ElbHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
             if (in_array($dbFarmRole->Platform, array(SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::CLOUDSTACK))) {
                 Scalr\Modules\Platforms\Cloudstack\Helpers\CloudstackHelper::farmUpdateRoleSettings($dbFarmRole, $oldRoleSettings, $role['settings']);
             }
         }
     }
     $rolesToRemove = $this->getParam('rolesToRemove');
     if (!empty($rolesToRemove)) {
         $currentFarmRoles = Entity\FarmRole::find([['farmId' => $dbFarm->ID], ['id' => ['$in' => $rolesToRemove]]]);
         /* @var $farmRole Entity\FarmRole */
         foreach ($currentFarmRoles as $farmRole) {
             $farmRole->delete();
         }
     }
     $dbFarm->save();
     if (!$client->GetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED)) {
         $client->SetSettingValue(CLIENT_SETTINGS::DATE_FARM_CREATED, time());
     }
     if ($this->request->hasPermissions($dbFarm->__getNewFarmObject(), Acl::PERM_FARMS_LAUNCH_TERMINATE) && $this->getParam('launch')) {
         $this->user->getPermissions()->validate($dbFarm);
         $dbFarm->isLocked();
         Scalr::FireEvent($dbFarm->ID, new FarmLaunchedEvent(true, $this->user->id));
         $this->response->success('Farm successfully saved and launched');
     } else {
         $this->response->success('Farm successfully saved');
     }
     $this->response->data(array('farmId' => $dbFarm->ID, 'isNewFarm' => $bNew));
 }