GenerateUID() public static method

public static GenerateUID ( $short = false, $startWithLetter = false )
Beispiel #1
0
 /**
  * {@inheritdoc}
  * @see Scalr_Model::save()
  */
 public function save($forceInsert = false)
 {
     if (!$this->id) {
         $forceInsert = true;
         $this->id = Scalr::GenerateUID(true);
     }
     parent::save($forceInsert);
 }
Beispiel #2
0
 protected function run1($stage)
 {
     $envIds = $this->db->Execute("SELECT `id` FROM `client_environments`");
     $platformVariables = static::getCloudsCredentialProperties();
     foreach ($envIds as $row) {
         $environment = \Scalr_Environment::init()->loadById($row['id']);
         $platforms = [];
         foreach (array_keys(SERVER_PLATFORMS::getList()) as $platform) {
             if ($environment->getPlatformConfigValue($platform . '.is_enabled', false)) {
                 $platforms[] = $platform;
             }
         }
         foreach ($platforms as $platform) {
             try {
                 switch ($platform) {
                     case SERVER_PLATFORMS::RACKSPACE:
                         foreach (['rs-ORD1', 'rs-LONx'] as $location) {
                             $cloudCredentials = new Entity\CloudCredentials();
                             $cloudCredentials->accountId = $environment->getAccountId();
                             $cloudCredentials->envId = $environment->id;
                             $cloudCredentials->cloud = "{$location}.{$platform}";
                             $cloudCredentials->name = "{$environment->id}-{$environment->getAccountId()}-{$cloudCredentials->cloud}-" . \Scalr::GenerateUID(true);
                             foreach ($platformVariables[$platform] as $name => $newName) {
                                 $value = $environment->getPlatformConfigValue($name, true, $location);
                                 if ($value === null) {
                                     $value = false;
                                 }
                                 $cloudCredentials->properties[$newName] = $value;
                             }
                             $cloudCredentials->save();
                             $cloudCredentials->bindToEnvironment($environment);
                         }
                         break;
                     default:
                         $cloudCredentials = new Entity\CloudCredentials();
                         $cloudCredentials->accountId = $environment->getAccountId();
                         $cloudCredentials->envId = $environment->id;
                         $cloudCredentials->cloud = $platform;
                         $cloudCredentials->name = "{$environment->id}-{$environment->getAccountId()}-{$platform}-" . \Scalr::GenerateUID(true);
                         $cloudCredentials->status = Entity\CloudCredentials::STATUS_ENABLED;
                         foreach ($platformVariables[$platform] as $name => $newName) {
                             $value = $environment->getPlatformConfigValue($name);
                             if ($value === null) {
                                 $value = false;
                             }
                             $cloudCredentials->properties[$newName] = $value;
                         }
                         $cloudCredentials->save();
                         $cloudCredentials->bindToEnvironment($environment);
                         break;
                 }
             } catch (Exception $e) {
                 $this->console->error(get_class($e) . " in {$e->getFile()} on line {$e->getLine()}: " . $e->getMessage());
                 error_log(get_class($e) . " in {$e->getFile()} at line {$e->getLine()}: {$e->getMessage()}\n{$e->getTraceAsString()}");
             }
         }
     }
 }
Beispiel #3
0
    $options->uuid = strtolower(str_replace('-', '', $opt['r']));
}
$options->verbosity = isset($opt['v']);
$options->interactive = isset($opt['i']);
if (isset($opt['help']) || isset($opt['h'])) {
    $showusage();
}
if (isset($opt['n']) || isset($opt['new'])) {
    $template = UpgradeHandler::getPathToUpdates() . '/Template.php';
    if (!is_readable($template)) {
        $console->error('Could not open template file for reading ' . $template);
        exit;
    }
    $released = gmdate('YmdHis');
    $pathname = UpgradeHandler::getPathToUpdates() . '/Update' . $released . '.php';
    $tpl = PhpTemplate::load($template, array('upd_released' => $released, 'upd_uuid' => \Scalr::GenerateUID()));
    if ($console->confirm("Are you sure you want to create a new upgrade class?")) {
        if (file_put_contents($pathname, $tpl) === false) {
            $console->error('Could not write to file "%s"', $pathname);
            exit;
        }
        $console->success('Upgrade class "%s" has been successfully created.', realpath($pathname));
    }
    exit;
}
if (isset($opt['force'])) {
    UpgradeHandler::removePid();
}
$upgrade = new UpgradeHandler($options);
if (!$upgrade->run()) {
    exit(1);
Beispiel #4
0
 public function __construct()
 {
     $this->messageId = Scalr::GenerateUID();
     $this->meta[Scalr_Messaging_MsgMeta::SCALR_VERSION] = SCALR_VERSION;
 }
Beispiel #5
0
 public static function prepareScript($scriptSettings, DBServer $targetServer, AbstractServerEvent $event = null)
 {
     $template = ['type' => isset($scriptSettings['type']) ? $scriptSettings['type'] : null, 'timeout' => isset($scriptSettings['timeout']) ? $scriptSettings['timeout'] : null, 'issync' => isset($scriptSettings['issync']) ? $scriptSettings['issync'] : null, 'run_as' => isset($scriptSettings['run_as']) ? $scriptSettings['run_as'] : null, 'execution_id' => Scalr::GenerateUID()];
     if ($scriptSettings['type'] == self::ORCHESTRATION_SCRIPT_TYPE_SCALR) {
         /* @var $script Script */
         $script = Script::findPk($scriptSettings['scriptid']);
         if (!$script) {
             return false;
         }
         // TODO: validate permission to access script ?
         if ($script->os && $targetServer->osType && $script->os != $targetServer->osType) {
             return false;
         }
         if ($scriptSettings['version'] == 'latest' || (int) $scriptSettings['version'] == -1) {
             $version = $script->getLatestVersion();
         } else {
             $version = $script->getVersion((int) $scriptSettings['version']);
         }
         if (empty($version)) {
             return false;
         }
         $template['name'] = $script->name;
         $template['id'] = $script->id;
         $template['body'] = $version->content;
         $template['scriptVersion'] = $version->version;
         // variables could be null
         $scriptParams = $script->allowScriptParameters ? (array) $version->variables : [];
         foreach ($scriptParams as &$val) {
             $val = "";
         }
         $params = array_merge($scriptParams, $targetServer->GetScriptingVars(), (array) unserialize($scriptSettings['params']));
         if ($event) {
             $eventServer = $event->DBServer;
             foreach ($eventServer->GetScriptingVars() as $k => $v) {
                 $params["event_{$k}"] = $v;
             }
             foreach ($event->GetScriptingVars() as $k => $v) {
                 $params[$k] = $event->{$v};
             }
             if (isset($event->params) && is_array($event->params)) {
                 foreach ($event->params as $k => $v) {
                     $params[$k] = $v;
                 }
             }
             $params['event_name'] = $event->GetName();
         }
         if ($event instanceof CustomEvent && count($event->params) > 0) {
             $params = array_merge($params, $event->params);
         }
         // Prepare keys array and array with values for replacement in script
         $keys = array_keys($params);
         $keys = array_map(function ($item) {
             return '%' . $item . '%';
         }, $keys);
         $values = array_values($params);
         $script_contents = str_replace($keys, $values, $template['body']);
         $template['body'] = str_replace('\\%', "%", $script_contents);
         // Generate script contents
         $template['name'] = preg_replace("/[^A-Za-z0-9]+/", "_", $template['name']);
     } elseif ($scriptSettings['type'] == self::ORCHESTRATION_SCRIPT_TYPE_LOCAL) {
         $template['path'] = $targetServer->applyGlobalVarsToValue($scriptSettings['script_path']);
     } elseif ($scriptSettings['type'] == self::ORCHESTRATION_SCRIPT_TYPE_CHEF) {
         $chef = new stdClass();
         $chefSettings = (array) unserialize($scriptSettings['params']);
         if ($chefSettings['chef.cookbook_url']) {
             $chef->cookbookUrl = $chefSettings['chef.cookbook_url'];
         }
         if ($chefSettings['chef.cookbook_url_type']) {
             $chef->cookbookUrlType = $chefSettings['chef.cookbook_url_type'];
         }
         if ($chefSettings['chef.relative_path']) {
             $chef->relativePath = $chefSettings['chef.relative_path'];
         }
         if ($chefSettings['chef.ssh_private_key']) {
             $chef->sshPrivateKey = $chefSettings['chef.ssh_private_key'];
         }
         if ($chefSettings['chef.role_name']) {
             $chef->role = $chefSettings['chef.role_name'];
         } else {
             $chef->runList = $chefSettings['chef.runlist'];
         }
         $chef->jsonAttributes = $chefSettings['chef.attributes'];
         $template['chef'] = $chef;
     }
     return $template;
 }
Beispiel #6
0
 /**
  *
  * @param ServerCreateInfo $serverCreateInfo
  * @param bool $isImport
  * @return DBServer
  */
 public static function Create(ServerCreateInfo $creInfo, $isImport = false, $setPendingStatus = false)
 {
     $db = \Scalr::getDb();
     $startWithLetter = in_array($creInfo->platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::UCLOUD, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::GCE));
     if ($isImport) {
         $startWithLetter = true;
     }
     $server_id = Scalr::GenerateUID(false, $startWithLetter);
     $status = !$isImport ? SERVER_STATUS::PENDING_LAUNCH : SERVER_STATUS::IMPORTING;
     if ($setPendingStatus) {
         $status = SERVER_STATUS::PENDING;
     }
     // IF no index defined
     if (!$creInfo->index && !$isImport) {
         $indexes = $db->GetAll("SELECT `index` FROM servers WHERE farm_roleid=? AND status NOT IN (?,?,?)", array($creInfo->dbFarmRole->ID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TROUBLESHOOTING));
         $used_indexes = array();
         if (count($indexes) > 0) {
             foreach ($indexes as $index) {
                 $used_indexes[$index['index']] = true;
             }
         }
         for ($i = 1;; $i++) {
             if (!$used_indexes[$i]) {
                 $creInfo->index = $i;
                 break;
             }
         }
     } elseif ($isImport) {
         $creInfo->index = 0;
     }
     $client_id = $creInfo->clientId ? $creInfo->clientId : $creInfo->dbFarmRole->GetFarmObject()->ClientID;
     $db->Execute("INSERT INTO servers SET\n            `server_id`\t\t= ?,\n            `farm_id`\t\t= ?,\n            `role_id`\t\t= ?,\n            `env_id`\t\t= ?,\n            `farm_roleid`\t= ?,\n            `client_id`\t\t= ?,\n            `platform`\t\t= ?,\n            `status`\t\t= ?,\n            `remote_ip`\t\t= ?,\n            `local_ip`\t\t= ?,\n            `dtadded`\t\t= NOW(),\n            `index`\t\t\t= ?\n        ", array($server_id, $creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, $creInfo->roleId, $creInfo->envId, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->ID : 0, $client_id, $creInfo->platform, $status, $creInfo->remoteIp, $creInfo->localIp, $creInfo->index));
     $DBServer = DBServer::LoadByID($server_id);
     $DBServer->SetProperties($creInfo->GetProperties());
     return $DBServer;
 }
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Pcntl\ProcessInterface::OnStartForking()
  */
 public function OnStartForking()
 {
     if (!\Scalr::getContainer()->analytics->enabled) {
         die("Terminating the process as Cost analytics is disabled in the config.\n");
     }
     if (SettingEntity::getValue(SettingEntity::ID_FORBID_AUTOMATIC_UPDATE_AWS_PRICES)) {
         die("Terminating the process because of overriding AWS prices has been forbidden by financial admin.\n");
     }
     $now = new DateTime('now', new DateTimeZone('UTC'));
     $urls = array('https://a0.awsstatic.com/pricing/1/ec2/linux-od.min.js', 'https://a0.awsstatic.com/pricing/1/ec2/mswin-od.min.js');
     $mapping = array('us-east' => 'us-east-1', 'us-west' => 'us-west-1', 'us-west-2' => 'us-west-2', 'eu-ireland' => 'eu-west-1', 'sa-east-1' => 'sa-east-1', 'apac-sin' => 'ap-southeast-1', 'apac-tokyo' => 'ap-northeast-1', 'apac-syd' => 'ap-southeast-2');
     $availableLocations = Aws::getCloudLocations();
     foreach ($urls as $link) {
         $json = trim(preg_replace('/^.+?callback\\((.+?)\\);\\s*$/sU', '\\1', file_get_contents($link)));
         $data = json_decode(preg_replace('/(\\w+):/', '"\\1":', $json));
         if (!empty($data->config->regions)) {
             $cadb = Scalr::getContainer()->cadb;
             foreach ($data->config->regions as $rd) {
                 foreach ($rd->instanceTypes as $it) {
                     if (!isset($mapping[$rd->region])) {
                         throw new Exception(sprintf("Region %s does not exist in the mapping.", $rd->region));
                     }
                     $region = $mapping[$rd->region];
                     $latest = array();
                     //Gets latest prices for all instance types from current region.
                     $res = $cadb->Execute("\n                            SELECT p.instance_type, ph.applied, p.os, p.name, HEX(p.price_id) `price_id`, p.cost\n                            FROM price_history ph\n                            JOIN prices p ON p.price_id = ph.price_id\n                            LEFT JOIN price_history ph2 ON ph2.platform = ph.platform\n                                AND ph2.cloud_location = ph.cloud_location\n                                AND ph2.account_id = ph.account_id\n                                AND ph2.url = ph.url\n                                AND ph2.applied > ph.applied AND ph2.applied <= ?\n                            LEFT JOIN prices p2 ON p2.price_id = ph2.price_id\n                                AND p2.instance_type = p.instance_type\n                                AND p2.os = p.os\n                            WHERE ph.account_id = 0 AND p2.price_id IS NULL\n                            AND ph.platform = 'ec2'\n                            AND ph.cloud_location = ?\n                            AND ph.url = ''\n                            AND ph.applied <= ?\n                        ", array($now->format('Y-m-d'), $region, $now->format('Y-m-d')));
                     while ($rec = $res->FetchRow()) {
                         $latest[$rec['instance_type']][$rec['os']] = array('applied' => $rec['applied'], 'price_id' => $rec['price_id'], 'cost' => $rec['cost']);
                     }
                     $upd = array();
                     $needUpdate = false;
                     foreach ($it->sizes as $sz) {
                         foreach ($sz->valueColumns as $v) {
                             $os = $v->name == 'linux' ? PriceEntity::OS_LINUX : PriceEntity::OS_WINDOWS;
                             if (!isset($latest[$sz->size][$os])) {
                                 $needUpdate = true;
                             } else {
                                 if (abs(($latest[$sz->size][$os]['cost'] - $v->prices->USD) / $v->prices->USD) > 1.0E-6) {
                                     $needUpdate = true;
                                     $latest[$sz->size][$os]['cost'] = $v->prices->USD;
                                 } else {
                                     continue;
                                 }
                             }
                             $latest[$sz->size][$os] = array('cost' => $v->prices->USD);
                         }
                     }
                     if ($needUpdate) {
                         $priceid = $cadb->GetOne("\n                                SELECT HEX(`price_id`) AS `price_id`\n                                FROM price_history\n                                WHERE platform = 'ec2'\n                                AND url = ''\n                                AND cloud_location = ?\n                                AND applied = ?\n                                AND account_id = 0\n                                LIMIT 1\n                            ", array($region, $now->format('Y-m-d')));
                         if (!$priceid) {
                             $priceid = str_replace('-', '', Scalr::GenerateUID());
                             $cadb->Execute("\n                                    INSERT price_history\n                                    SET price_id = UNHEX(?),\n                                        platform = 'ec2',\n                                        url = '',\n                                        cloud_location = ?,\n                                        account_id = 0,\n                                        applied = ?,\n                                        deny_override = 0\n                                ", array($priceid, $region, $now->format('Y-m-d')));
                         }
                         foreach ($latest as $instanceType => $ld) {
                             foreach ($ld as $os => $v) {
                                 $cadb->Execute("\n                                        REPLACE prices\n                                        SET price_id = UNHEX(?),\n                                            instance_type = ?,\n                                            name = ?,\n                                            os = ?,\n                                            cost = ?\n                                    ", array($priceid, $instanceType, $instanceType, $os, $v['cost']));
                             }
                         }
                     }
                 }
             }
         }
     }
     exit;
 }
Beispiel #8
0
 /**
  *
  * @param ServerCreateInfo $serverCreateInfo
  * @param bool $isImport
  * @return DBServer
  */
 public static function Create(ServerCreateInfo $creInfo, $isImport = false, $setPendingStatus = false)
 {
     $db = \Scalr::getDb();
     $startWithLetter = in_array($creInfo->platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::GCE));
     if ($isImport) {
         $startWithLetter = true;
     }
     $server_id = Scalr::GenerateUID(false, $startWithLetter);
     $status = !$isImport ? SERVER_STATUS::PENDING_LAUNCH : SERVER_STATUS::IMPORTING;
     if ($setPendingStatus) {
         $status = SERVER_STATUS::PENDING;
     }
     // Assigns Farm index to the server
     if (!$isImport) {
         // This query select the least lower vacant Farm index from the available.
         // If there are no available indexes the query returns NULL so we need cast result to integer
         // to make sure it will use Farm index equal to 1 in this case.
         // We ingore terminated and pending terminating instances to release their indexes.
         $farmIndex = 1 + intval($db->GetOne("\n                SELECT s.farm_index\n                FROM servers s\n                WHERE s.farm_id = ? AND s.status NOT IN (?, ?)\n                AND NOT EXISTS (SELECT 1 FROM servers WHERE farm_id = s.farm_id AND farm_index = s.farm_index + 1 AND status NOT IN (?, ?))\n                ORDER BY s.farm_index\n                LIMIT 1\n            ", [$creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE]));
     } else {
         // Default Farm index value is considered to equal 1
         $farmIndex = 1;
     }
     // IF no index defined
     if (!$creInfo->index && !$isImport) {
         $indexes = $db->GetAll("SELECT `index` FROM servers WHERE farm_roleid = ? AND status NOT IN (?, ?)", [$creInfo->dbFarmRole->ID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE]);
         $usedIndexes = [];
         if (!empty($indexes)) {
             foreach ($indexes as $index) {
                 $usedIndexes[$index['index']] = true;
             }
         }
         for ($i = 1;; $i++) {
             if (!isset($usedIndexes[$i])) {
                 $creInfo->index = $i;
                 break;
             }
         }
     } elseif ($isImport) {
         $creInfo->index = 0;
     }
     $client_id = $creInfo->clientId ? $creInfo->clientId : $creInfo->dbFarmRole->GetFarmObject()->ClientID;
     $instanceTypeName = null;
     $instanceTypeId = $creInfo->dbFarmRole ? $creInfo->dbFarmRole->getInstanceType() : null;
     if (in_array($creInfo->platform, [SERVER_PLATFORMS::EC2, SERVER_PLATFORMS::GCE])) {
         $instanceTypeName = $instanceTypeId;
     }
     $db->Execute("\n            INSERT INTO servers\n            SET `server_id` = ?,\n                `farm_id` = ?,\n                `env_id` = ?,\n                `farm_roleid` = ?,\n                `client_id` = ?,\n                `platform` = ?,\n                `status` = ?,\n                `remote_ip` = ?,\n                `local_ip` = ?,\n                `dtadded` = NOW(),\n                `index` = ?,\n                `farm_index` = ?,\n                `cloud_location` = ?,\n                `type` = ?,\n                `instance_type_name`= ?\n        ", [$server_id, $creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, $creInfo->envId, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->ID : 0, $client_id, $creInfo->platform, $status, $creInfo->remoteIp, $creInfo->localIp, $creInfo->index, $farmIndex, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->CloudLocation : null, $instanceTypeId, $instanceTypeName]);
     $DBServer = DBServer::LoadByID($server_id);
     $DBServer->SetProperties($creInfo->GetProperties());
     $DBServer->setOsType($DBServer->osType);
     try {
         if ($DBServer->farmRoleId) {
             $db->Execute("\n                    INSERT INTO servers_launch_timelog\n                    SET `server_id` = ?,\n                        `os_family` = ?,\n                        `os_version` = ?,\n                        `cloud` = ?,\n                        `cloud_location` = ?,\n                        `server_type` = ?,\n                        `behaviors` = ?,\n                        `ts_created` = ?\n                ", [$server_id, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->family, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->version, $DBServer->platform, $DBServer->cloudLocation, $DBServer->getType(), implode(",", $DBServer->GetFarmRoleObject()->GetRoleObject()->getBehaviors()), time()]);
         }
     } catch (Exception $e) {
     }
     return $DBServer;
 }
Beispiel #9
0
 /**
  * Saves current entity to database
  *
  * @throws  ModelException
  */
 public function save()
 {
     $iterator = $this->getIterator();
     $pk = $iterator->getPrimaryKey();
     if (empty($pk)) {
         throw new ModelException(sprintf("Primary key has not been defined with @Id tag for %s", get_class($this)));
     }
     $stmtFields = '';
     $stmtUpdate = '';
     $arguments1 = array();
     $arguments2 = array();
     foreach ($iterator->fields() as $field) {
         if ($this->{$field->name} === null && isset($field->generatedValue)) {
             if ($field->type instanceof UuidType || $field->type instanceof UuidStringType || $field->generatedValue->strategy == 'UUID') {
                 $this->{$field->name} = \Scalr::GenerateUID();
             } else {
                 if ($field->generatedValue->strategy == 'AUTO') {
                     //Generated automatically by mysql
                     if (isset($field->id)) {
                         $postInsertField = $field;
                     }
                     continue;
                 } else {
                     throw new ModelException(sprintf("Type %s has not been implemented for GeneratedValue behaviour.", get_class($field->type)));
                 }
             }
         }
         if (isset($field->id)) {
             if (!isset($this->{$field->name}) && $field->column->nullable) {
                 $stmtFields .= ', ' . $field->getColumnName() . ' = NULL';
             } else {
                 $stmtFields .= ', ' . $field->getColumnName() . ' = ' . $field->type->wh();
                 $arguments1[] = $field->type->toDb($this->{$field->name});
             }
         } else {
             if (!isset($this->{$field->name}) && $field->column->nullable) {
                 $stmtFields .= ', ' . $field->getColumnName() . ' = NULL';
                 $stmtUpdate .= ', ' . $field->getColumnName() . ' = NULL';
             } else {
                 $stmtFields .= ', ' . $field->getColumnName() . ' = ' . $field->type->wh();
                 $arguments1[] = $field->type->toDb($this->{$field->name});
                 $stmtUpdate .= ', ' . $field->getColumnName() . ' = ' . $field->type->wh();
                 $arguments2[] = $field->type->toDb($this->{$field->name});
             }
         }
     }
     $stmtFields = substr($stmtFields, 1);
     if ($stmtUpdate != '') {
         $stmtUpdate = substr($stmtUpdate, 1);
     }
     $this->db()->Execute("\n            INSERT " . ($stmtUpdate == '' ? 'IGNORE' : '') . " {$this->table()} SET " . $stmtFields . "\n            " . ($stmtUpdate != '' ? "ON DUPLICATE KEY UPDATE " . $stmtUpdate : '') . "\n        ", array_merge($arguments1, $arguments2));
     if (isset($postInsertField)) {
         $this->{$postInsertField->name} = $postInsertField->type->toPhp($this->db()->Insert_ID());
     }
 }
Beispiel #10
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('domainId' => array('type' => 'int'), 'domainName', 'domainType', 'domainFarm' => array('type' => 'int'), 'domainFarmRole' => array('type' => 'int'), 'soaRefresh' => array('type' => 'int'), 'soaExpire' => array('type' => 'int'), 'soaRetry' => array('type' => 'int'), 'records' => array('type' => 'json')));
     $errors = array();
     // validate farmId, farmRoleId
     $farmId = 0;
     $farmRoleId = 0;
     if ($this->getParam('domainFarm')) {
         $DBFarm = DBFarm::LoadByID($this->getParam('domainFarm'));
         if (!$this->user->getPermissions()->check($DBFarm)) {
             $errors['domainFarm'] = _('Farm not found');
         } else {
             $farmId = $DBFarm->ID;
             if ($this->getParam('domainFarmRole')) {
                 $DBFarmRole = DBFarmRole::LoadByID($this->getParam('domainFarmRole'));
                 if ($DBFarmRole->FarmID != $DBFarm->ID) {
                     $errors['domainFarmRole'] = _('Role not found');
                 } else {
                     $farmRoleId = $DBFarmRole->ID;
                 }
             }
         }
     }
     // validate domain name
     $domainName = '';
     if (!$this->getParam('domainId')) {
         if ($this->getParam('domainType') == 'own') {
             $Validator = new Validator();
             if (!$Validator->IsDomain($this->getParam('domainName'))) {
                 $errors['domainName'] = _("Invalid domain name");
             } else {
                 $domainChunks = explode(".", $this->getParam('domainName'));
                 $chkDmn = '';
                 while (count($domainChunks) > 0) {
                     $chkDmn = trim(array_pop($domainChunks) . ".{$chkDmn}", ".");
                     $chkDomainId = $this->db->GetOne("SELECT id FROM dns_zones WHERE zone_name=? AND client_id != ?", array($chkDmn, $this->user->getAccountId()));
                     if ($chkDomainId) {
                         if ($chkDmn == $this->getParam('domainName')) {
                             $errors['domainName'] = sprintf(_("%s already exists on scalr nameservers"), $this->getParam('domainName'));
                         } else {
                             $chkDnsZone = DBDNSZone::loadById($chkDomainId);
                             $access = false;
                             foreach (explode(";", $chkDnsZone->allowedAccounts) as $email) {
                                 if ($email == $this->user->getEmail()) {
                                     $access = true;
                                 }
                             }
                             if (!$access) {
                                 $errors['domainName'] = sprintf(_("You cannot use %s domain name because top level domain %s does not belong to you"), $this->getParam('domainName'), $chkDmn);
                             }
                         }
                     }
                 }
                 //if (! $errors['domainName'])
                 $domainName = $this->getParam('domainName');
             }
         } else {
             $domainName = Scalr::GenerateUID() . '.' . CONFIG::$DNS_TEST_DOMAIN_NAME;
         }
         // check in DB
         $rez = $this->db->GetOne("SELECT id FROM dns_zones WHERE zone_name = ?", array($domainName));
         if ($rez) {
             $errors['domainName'] = 'Domain name already exist in database';
         }
     }
     $records = array();
     foreach ($this->getParam('records') as $key => $r) {
         if (($r['name'] || $r['value']) && $r['issystem'] == 0) {
             $r['name'] = str_replace("%hostname%", "{$domainName}", $r['name']);
             $r['value'] = str_replace("%hostname%", "{$domainName}", $r['value']);
             $records[$key] = $r;
         }
     }
     $recordsValidation = Scalr_Net_Dns_Zone::validateRecords($records);
     if ($recordsValidation !== true) {
         $errors = array_merge($errors, $recordsValidation);
     }
     if (count($errors) == 0) {
         if ($this->getParam('domainId')) {
             $DBDNSZone = DBDNSZone::loadById($this->getParam('domainId'));
             $this->user->getPermissions()->validate($DBDNSZone);
             $DBDNSZone->soaRefresh = $this->getParam('soaRefresh');
             $DBDNSZone->soaExpire = $this->getParam('soaExpire');
             $DBDNSZone->soaRetry = $this->getParam('soaRetry');
             $this->response->success("DNS zone successfully updated. It could take up to 5 minutes to update it on NS servers.");
         } else {
             $DBDNSZone = DBDNSZone::create($domainName, $this->getParam('soaRefresh'), $this->getParam('soaExpire'), str_replace('@', '.', $this->user->getEmail()), $this->getParam('soaRetry'));
             $DBDNSZone->clientId = $this->user->getAccountId();
             $DBDNSZone->envId = $this->getEnvironmentId();
             $this->response->success("DNS zone successfully added to database. It could take up to 5 minutes to setup it on NS servers.");
         }
         if ($DBDNSZone->farmRoleId != $farmRoleId || $DBDNSZone->farmId != $farmId) {
             $DBDNSZone->farmId = 0;
             $DBDNSZone->updateSystemRecords();
         }
         $DBDNSZone->farmRoleId = $farmRoleId;
         $DBDNSZone->farmId = $farmId;
         $DBDNSZone->setRecords($records);
         $DBDNSZone->save(true);
     } else {
         $this->response->failure();
         $this->response->data(array('errors' => $errors));
     }
 }
Beispiel #11
0
 /**
  * constructor
  * @return void
  */
 public function __construct()
 {
     $this->EventID = Scalr::GenerateUID();
 }
Beispiel #12
0
 /**
  * Creates default Cost Center for the Hosted Scalr new account
  *
  * @param    Scalr_Account      $account  The account object
  * @param    Scalr_Account_User $user     optional The account owner user
  * @return   CostCentreEntity   Returns a new Cost Center
  */
 public function createHostedScalrAccountCostCenter(Scalr_Account $account, Scalr_Account_User $user = null)
 {
     if (!$user instanceof Scalr_Account_User) {
         $user = $account->getOwner();
     }
     //New Cost Center should be created in account share mode
     $cc = new CostCentreEntity();
     $cc->ccId = \Scalr::GenerateUID();
     $cc->accountId = $account->id;
     $cc->createdByEmail = $user->getEmail();
     $cc->name = "Cost Center " . $account->name . " (" . $account->id . ")";
     $cc->createdById = $user->id;
     $cc->save();
     $cc->saveProperty(CostCentrePropertyEntity::NAME_BILLING_CODE, "CC-" . $account->name);
     $cc->saveProperty(CostCentrePropertyEntity::NAME_DESCRIPTION, "This Cost Center was added automatically.");
     $cc->saveProperty(CostCentrePropertyEntity::NAME_LEAD_EMAIL, $user->getEmail());
     $cc->saveProperty(CostCentrePropertyEntity::NAME_LOCKED, false);
     //A new Project which corresponds to Cost Center (in account share mode as well)
     $project = new ProjectEntity();
     $project->projectId = \Scalr::GenerateUID();
     $project->ccId = $cc->ccId;
     $project->name = "Project " . $account->name . " (" . $account->id . ")";
     $project->accountId = $account->id;
     $project->createdByEmail = $user->getEmail();
     $project->shared = ProjectEntity::SHARED_WITHIN_ACCOUNT;
     $project->createdById = $user->id;
     $project->save();
     $project->saveProperty(ProjectPropertyEntity::NAME_BILLING_CODE, "PR-" . $account->name);
     $project->saveProperty(ProjectPropertyEntity::NAME_DESCRIPTION, "This Project was added automatically.");
     $project->saveProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL, $user->getEmail());
     if (\Scalr::getContainer()->analytics->enabled) {
         \Scalr::getContainer()->analytics->tags->syncValue($account->id, TagEntity::TAG_ID_COST_CENTRE, $cc->ccId, $cc->name);
         \Scalr::getContainer()->analytics->tags->syncValue($account->id, TagEntity::TAG_ID_PROJECT, $project->projectId, $project->name);
     }
     return $cc;
 }
Beispiel #13
0
 /**
  * {@inheritdoc}
  * @see Scalr_Role_Behavior::extendMessage()
  */
 public function extendMessage(Scalr_Messaging_Msg $message, DBServer $dbServer)
 {
     $message = parent::extendMessage($message, $dbServer);
     switch (get_class($message)) {
         case 'Scalr_Messaging_Msg_HostInitResponse':
             $config = $this->getConfiguration($dbServer);
             if (!empty($config->serverUrl) || !empty($config->cookbookUrl)) {
                 $message->chef = $config;
                 $message->chef->scriptName = '[Scalr built-in] Chef bootstrap';
                 $message->chef->executionId = Scalr::GenerateUID();
                 $message->chef->eventName = 'HostInit';
             }
             break;
     }
     return $message;
 }
Beispiel #14
0
 /**
  * Create new FarmRoleStorageConfig based on input config
  *
  * @param   FarmRoleStorageConfig   $config
  */
 public function create(FarmRoleStorageConfig $config)
 {
     $deleteFlag = false;
     if ($config->id) {
         $this->loadById($config->id);
         if ($this->status == self::STATE_PENDING_CREATE) {
             if ($config->status == self::STATE_PENDING_DELETE) {
                 // mark for delete on save
                 $deleteFlag = true;
             } else {
                 $this->type = $config->type;
                 $this->fs = $config->fs;
                 $this->reUse = $config->reUse;
                 $this->rebuild = $config->rebuild;
                 $this->mount = $config->mount;
                 $this->mountPoint = $config->mountPoint;
                 $this->mountOptions = $config->mountOptions;
                 $this->label = $config->label;
             }
         } elseif ($config->status == self::STATE_PENDING_DELETE) {
             $this->status = self::STATE_PENDING_DELETE;
         }
     } else {
         $this->id = \Scalr::GenerateUID();
         $this->type = $config->type;
         $this->fs = $config->fs;
         $this->reUse = $config->reUse;
         $this->rebuild = $config->rebuild;
         $this->mount = $config->mount;
         $this->mountPoint = $config->mountPoint;
         $this->mountOptions = $config->mountOptions;
         $this->label = $config->label;
         $this->status = self::STATE_PENDING_CREATE;
     }
     if ($deleteFlag) {
         $this->delete();
         return;
     }
     $this->settings = $config->settings;
     $this->save();
 }
Beispiel #15
0
 /**
  * Constuctor
  */
 public function __construct()
 {
     $this->requestId = \Scalr::GenerateUID();
 }
Beispiel #16
0
 /**
  * Saves price
  *
  * @param  PriceHistoryEntity $price The PriceHistoryEntity with details set.
  * @throws \InvalidArgumentException
  * @throws \ADODB_Exception
  */
 public function save(PriceHistoryEntity $price)
 {
     if (!isset($price->platform) || !isset($price->cloudLocation)) {
         throw new \InvalidArgumentException(sprintf("Both platform and cloudLocation properties must be set"));
     }
     if (!isset($price->applied)) {
         $price->applied = new \DateTime('now', new \DateTimeZone('UTC'));
     } else {
         if (!$price->applied instanceof \DateTime) {
             $price->applied = new \DateTime($price->applied, new \DateTimeZone('UTC'));
         }
     }
     if (!$price->priceId) {
         //Trying to find if the price already exists on this day
         $found = PriceHistoryEntity::findOne([['platform' => $price->platform], ['url' => $price->url ?: ''], ['cloudLocation' => $price->cloudLocation], ['accountId' => $price->accountId ?: 0], ['applied' => $price->applied->format('Y-m-d')]]);
         if ($found) {
             $price->priceId = $found->priceId;
         }
     }
     if (!$price->priceId) {
         $bNew = true;
         $price->priceId = \Scalr::GenerateUID();
     } else {
         $bNew = false;
     }
     $sId = "`price_id` = " . $price->qstr('priceId');
     $this->cadb->BeginTrans();
     try {
         $this->cadb->Execute("\n                " . ($bNew ? "INSERT" : "UPDATE") . " " . $price->table() . "\n                SET " . ($bNew ? $sId . "," : "") . "\n                    platform = ?,\n                    url = ?,\n                    cloud_location = ?,\n                    account_id = ?,\n                    applied = ?,\n                    deny_override = ?\n                " . ($bNew ? "" : "WHERE " . $sId . " LIMIT 1") . "\n            ", [$price->platform, $price->url ?: '', $price->cloudLocation, $price->accountId ?: 0, $price->applied->format('Y-m-d'), $price->denyOverride ? 1 : 0]);
         //Removes previous values
         if (!$bNew) {
             $this->cadb->Execute("DELETE FROM `prices` WHERE price_id = " . $price->qstr('priceId'));
         }
         $stmt = "";
         foreach ($price->getDetails() as $priceEntity) {
             if ($priceEntity instanceof PriceEntity) {
                 $stmt .= ", (" . $price->qstr('priceId') . ", " . $priceEntity->qstr('instanceType') . ", " . $priceEntity->qstr('os') . ", " . $priceEntity->qstr('name') . ", " . $priceEntity->qstr('cost') . ")";
             } else {
                 throw new \InvalidArgumentException(sprintf("Details should contain collection of the PriceEntity objects. %s given.", gettype($priceEntity)));
             }
         }
         if ($stmt !== '') {
             $this->cadb->Execute("REPLACE `prices` (`price_id`,`instance_type`, `os`, `name`, `cost`) VALUES " . ltrim($stmt, ','));
         }
         $this->cadb->CommitTrans();
     } catch (\Exception $e) {
         $this->cadb->RollbackTrans();
         throw $e;
     }
 }
Beispiel #17
0
 protected function CreateInitialResponse()
 {
     $response = new stdClass();
     $response->{"TransactionID"} = Scalr::GenerateUID();
     return $response;
 }
Beispiel #18
0
 public function xCloneAction()
 {
     if (!$this->user->isAccountSuperAdmin() && !$this->request->isAllowed(Acl::RESOURCE_ENV_CLOUDS_ENVIRONMENT)) {
         throw new Scalr_Exception_InsufficientPermissions();
     }
     $params = array('envId' => array('type' => 'int'), 'name' => array('type' => 'string', 'validator' => array(Scalr_Validator::REQUIRED => true, Scalr_Validator::NOHTML => true)));
     $this->request->defineParams($params);
     $this->request->validate();
     $oldEnv = Scalr_Environment::init()->loadById($this->getParam('envId'));
     $this->user->getPermissions()->validate($oldEnv);
     if ($this->request->isValid()) {
         if (!$this->user->isAccountOwner() && !$this->user->isAccountSuperAdmin()) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
         $this->user->getAccount()->validateLimit(Scalr_Limits::ACCOUNT_ENVIRONMENTS, 1);
         $env = $this->user->getAccount()->createEnvironment($this->getParam('name'));
         $env->status = Scalr_Environment::STATUS_ACTIVE;
         //Copy cloud credentials
         $cloudConfig = $oldEnv->getFullConfiguration();
         foreach ($cloudConfig as $group => $props) {
             $env->setPlatformConfig($props, null, $group);
         }
         //Copy teams & ACLs
         $teams = $oldEnv->getTeams();
         foreach ($teams as $teamId) {
             $env->addTeam($teamId);
         }
         //Copy Env level global variables
         $oldGv = new Scalr_Scripting_GlobalVariables($oldEnv->clientId, $oldEnv->id, ScopeInterface::SCOPE_ENVIRONMENT);
         $variables = $oldGv->getValues();
         $newGv = new Scalr_Scripting_GlobalVariables($env->clientId, $env->id, ScopeInterface::SCOPE_ENVIRONMENT);
         $newGv->setValues($variables, 0, 0, 0, '', false, true);
         //Copy governance rules
         $oldGov = new Scalr_Governance($oldEnv->id);
         $govRules = $oldGov->getValues();
         $newGov = new Scalr_Governance($env->id);
         foreach ($govRules as $category => $rules) {
             foreach ($rules as $name => $data) {
                 $newGov->setValue($category, $name, $data['enabled'], $data['limits']);
             }
         }
         $oldCloudCredsList = $oldEnv->cloudCredentialsList();
         foreach ($oldCloudCredsList as $oldCloudCreds) {
             if ($oldCloudCreds->getScope() == ScopeInterface::SCOPE_ENVIRONMENT) {
                 $cloudCreds = clone $oldCloudCreds;
                 $cloudCreds->envId = $env->id;
                 $cloudCreds->name = "{$env->id}-{$cloudCreds->accountId}-{$cloudCreds->cloud}-" . \Scalr::GenerateUID(true);
                 $cloudCreds->save();
                 $cloudCreds->bindToEnvironment($env);
             } else {
                 $envCloudCreds = new \Scalr\Model\Entity\EnvironmentCloudCredentials();
                 $envCloudCreds->envId = $env->id;
                 $envCloudCreds->cloud = $oldCloudCreds->cloud;
                 $envCloudCreds->cloudCredentialsId = $oldCloudCreds->id;
                 $envCloudCreds->save();
             }
         }
         $this->response->success("Environment successfully cloned");
         $this->response->data(array('env' => array('id' => $env->id, 'name' => $env->name, 'status' => $env->status, 'platforms' => $env->getEnabledPlatforms(), 'teams' => $teams, 'ccId' => $env->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID))));
     } else {
         $this->response->failure($this->request->getValidationErrorsMessage(), true);
     }
 }
Beispiel #19
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::worker()
  */
 public function worker($request)
 {
     if (!\Scalr::getContainer()->analytics->enabled) {
         $this->log("WARN", "Cannot process the request. Cloud cost analytics is disabled in config.");
         return false;
     }
     $this->log("INFO", "Processing region: %s", $request->region);
     $now = new DateTime('now', new DateTimeZone('UTC'));
     $cadb = \Scalr::getContainer()->cadb;
     $os = strpos($request->url, 'linux') !== false ? PriceEntity::OS_LINUX : PriceEntity::OS_WINDOWS;
     foreach ($request->instanceTypes as $it) {
         if (!isset(self::$mapping[$request->region])) {
             throw new Exception(sprintf("Region %s does not exist in the mapping.", $request->region));
         }
         $region = self::$mapping[$request->region];
         $latest = [];
         //Gets latest prices for all instance types from current region.
         $res = $cadb->Execute("\n                SELECT p.instance_type, ph.applied, p.os, p.name, HEX(p.price_id) `price_id`, p.cost\n                FROM price_history ph\n                JOIN prices p ON p.price_id = ph.price_id\n                LEFT JOIN price_history ph2 ON ph2.platform = ph.platform\n                    AND ph2.cloud_location = ph.cloud_location\n                    AND ph2.account_id = ph.account_id\n                    AND ph2.url = ph.url\n                    AND ph2.applied > ph.applied AND ph2.applied <= ?\n                LEFT JOIN prices p2 ON p2.price_id = ph2.price_id\n                    AND p2.instance_type = p.instance_type\n                    AND p2.os = p.os\n                WHERE ph.account_id = 0 AND p2.price_id IS NULL\n                AND ph.platform = 'ec2'\n                AND ph.cloud_location = ?\n                AND ph.url = ''\n                AND ph.applied <= ?\n            ", [$now->format('Y-m-d'), $region, $now->format('Y-m-d')]);
         while ($rec = $res->FetchRow()) {
             $latest[$rec['instance_type']][$rec['os']] = ['applied' => $rec['applied'], 'price_id' => $rec['price_id'], 'cost' => $rec['cost']];
         }
         $needUpdate = false;
         foreach ($it->sizes as $sz) {
             foreach ($sz->valueColumns as $v) {
                 if (!is_numeric($v->prices->USD) || $v->prices->USD < 1.0E-6) {
                     continue;
                 }
                 if (!isset($latest[$sz->size][$os])) {
                     $needUpdate = true;
                 } else {
                     if (abs(($latest[$sz->size][$os]['cost'] - $v->prices->USD) / $v->prices->USD) > 1.0E-6) {
                         $needUpdate = true;
                         $latest[$sz->size][$os]['cost'] = $v->prices->USD;
                     } else {
                         continue;
                     }
                 }
                 $latest[$sz->size][$os] = ['cost' => $v->prices->USD];
             }
         }
         if ($needUpdate) {
             $priceid = $cadb->GetOne("\n                    SELECT HEX(`price_id`) AS `price_id`\n                    FROM price_history\n                    WHERE platform = 'ec2'\n                    AND url = ''\n                    AND cloud_location = ?\n                    AND applied = ?\n                    AND account_id = 0\n                    LIMIT 1\n                ", [$region, $now->format('Y-m-d')]);
             if (!$priceid) {
                 $priceid = str_replace('-', '', \Scalr::GenerateUID());
                 $cadb->Execute("\n                        INSERT price_history\n                        SET price_id = UNHEX(?),\n                            platform = 'ec2',\n                            url = '',\n                            cloud_location = ?,\n                            account_id = 0,\n                            applied = ?,\n                            deny_override = 0\n                    ", [$priceid, $region, $now->format('Y-m-d')]);
             }
             foreach ($latest as $instanceType => $ld) {
                 foreach ($ld as $os => $v) {
                     $cadb->Execute("\n                            REPLACE prices\n                            SET price_id = UNHEX(?),\n                                instance_type = ?,\n                                name = ?,\n                                os = ?,\n                                cost = ?\n                        ", [$priceid, $instanceType, $instanceType, $os, $v['cost']]);
                 }
             }
         }
     }
     $ret = new stdClass();
     $ret->url = $request->url;
     $ret->region = $request->region;
     return $ret;
 }
Beispiel #20
0
$ADODB_CACHE_DIR = CACHEPATH . "/adodb";
define("SCALR_TEMPLATES_PATH", APPPATH . "/templates/en_US");
// Require autoload definition
$classpath[] = $base;
$classpath[] = $base . "/externals/ZF-1.10.8";
$classpath[] = $base . "/externals/google-api-php-client-git-03102014/src";
set_include_path(get_include_path() . PATH_SEPARATOR . join(PATH_SEPARATOR, $classpath));
require_once SRCPATH . "/autoload.inc.php";
spl_autoload_register("__autoload");
set_error_handler("Scalr::errorHandler");
//Container witn adodb service needs to be defined in the first turn, as much depends on it.
Scalr::initializeContainer();
$idFilePath = APPPATH . '/etc/id';
$id = trim(@file_get_contents($idFilePath));
if (!$id) {
    $uuid = Scalr::GenerateUID();
    $id = dechex(abs(crc32($uuid)));
    $res = @file_put_contents($idFilePath, $id);
    if (!$res) {
        exit("ERROR: Unable to write ID file ({$idFilePath}).");
    }
}
define("SCALR_ID", $id);
// Define log4php contants
define("LOG4PHP_DIR", SRCPATH . '/externals/apache-log4php-2.0.0-incubating/src/main/php');
require_once LOG4PHP_DIR . '/Logger.php';
require_once SRCPATH . '/externals/adodb5-18/adodb-exceptions.inc.php';
require_once SRCPATH . '/externals/adodb5-18/adodb.inc.php';
$cfg = Scalr::getContainer()->config;
try {
    $db = Scalr::getDb();
Beispiel #21
0
 /**
  * {@inheritdoc}
  * @see ServerImportInterface::import()
  */
 public function import($instanceId, $tags = [])
 {
     $instances = PlatformFactory::NewPlatform($this->farmRole->platform)->getOrphanedServers($this->farmRole->getFarm()->getEnvironment(), $this->farmRole->cloudLocation, [$instanceId]);
     if (count($instances) != 1) {
         throw new ValidationErrorException("Instance was not found");
     }
     $this->orphaned = $instances[0];
     $this->tags = $tags;
     $this->validate();
     $farm = $this->farmRole->getFarm();
     $server = $this->server = new Entity\Server();
     try {
         $server->serverId = \Scalr::GenerateUID(false);
         // DBServer::Create, startWithLetter
         $server->platform = $this->farmRole->platform;
         $server->cloudLocation = $this->farmRole->cloudLocation;
         $server->accountId = $farm->accountId;
         $server->envId = $farm->envId;
         $server->farmId = $farm->id;
         $server->farmRoleId = $this->farmRole->id;
         $server->imageId = $this->orphaned->imageId;
         $server->status = Entity\Server::STATUS_RUNNING;
         $server->type = $this->orphaned->instanceType;
         $server->remoteIp = $this->orphaned->publicIp;
         $server->localIp = $this->orphaned->privateIp;
         $server->added = new DateTime();
         $server->initialized = new DateTime();
         // initialized is used in billing, so we set current time as start point
         $server->scalarized = 0;
         $server->setFreeFarmIndex();
         $server->setFreeFarmRoleIndex();
         $server->properties[Entity\Server::SZR_KEY] = \Scalr::GenerateRandomKey(40);
         $server->properties[Entity\Server::SZR_KEY_TYPE] = SZR_KEY_TYPE::ONE_TIME;
         $server->properties[Entity\Server::SZR_VESION] = '';
         $server->properties[Entity\Server::LAUNCHED_BY_ID] = $this->user->id;
         $server->properties[Entity\Server::LAUNCHED_BY_EMAIL] = $this->user->email;
         $server->properties[Entity\Server::LAUNCH_REASON_ID] = DBServer::LAUNCH_REASON_IMPORT;
         $server->properties[Entity\Server::LAUNCH_REASON] = DBServer::getLaunchReason(DBServer::LAUNCH_REASON_IMPORT);
         $server->properties[Entity\Server::FARM_ROLE_ID] = $this->farmRole->id;
         $server->properties[Entity\Server::ROLE_ID] = $this->farmRole->roleId;
         $server->properties[Entity\Server::FARM_CREATED_BY_ID] = $farm->ownerId ?: $farm->settings[Entity\FarmSetting::CREATED_BY_ID];
         $server->properties[Entity\Server::FARM_CREATED_BY_EMAIL] = $farm->ownerId ? Entity\Account\User::findPk($farm->ownerId)->email : $farm->settings[Entity\FarmSetting::CREATED_BY_EMAIL];
         // projectId, ccId
         $projectId = $farm->settings[Entity\FarmSetting::PROJECT_ID];
         $ccId = null;
         if (!empty($projectId)) {
             try {
                 $projectEntity = ProjectEntity::findPk($projectId);
                 if ($projectEntity instanceof ProjectEntity) {
                     /* @var $projectEntity ProjectEntity */
                     $ccId = $projectEntity->ccId;
                 } else {
                     $projectId = null;
                 }
             } catch (Exception $e) {
                 $projectId = null;
             }
         }
         $server->properties[Entity\Server::FARM_PROJECT_ID] = $projectId;
         if (empty($ccId)) {
             $ccId = Entity\Account\Environment::findPk($farm->envId)->getProperty(Entity\Account\EnvironmentProperty::SETTING_CC_ID);
         }
         $server->properties[Entity\Server::ENV_CC_ID] = $ccId;
         if (!empty($server->getImage())) {
             $server->getImage()->update(['dtLastUsed' => new DateTime()]);
         }
         if (!empty($this->farmRole->getRole())) {
             $this->farmRole->getRole()->update(['lastUsed' => new DateTime()]);
         }
         $this->importServer();
         $server->save();
         $server->setTimeLog('ts_created');
         $server->setTimeLog('ts_launched', time());
         $history = $server->getHistory();
         $history->markAsLaunched($server->properties[Entity\Server::LAUNCH_REASON], $server->properties[Entity\Server::LAUNCH_REASON_ID]);
         $history->update(['cloudServerId' => $this->orphaned->cloudServerId, 'scuCollecting' => 1]);
         $this->applyTags();
         return $server;
     } catch (Exception $e) {
         if (!empty($server->serverId)) {
             // cleanup
             $server->deleteBy([['serverId' => $server->serverId]]);
             Entity\ServerProperty::deleteBy([['serverId' => $server->serverId]]);
             Entity\Server\History::deletePk($server->serverId);
             $this->db->Execute("DELETE FROM `servers_launch_timelog` WHERE server_id = ?", [$server->serverId]);
         }
         throw new ServerImportException(sprintf("Server create was failed with error: %s", $e->getMessage()), $e->getCode(), $e);
     }
 }
Beispiel #22
0
 /**
  *
  * @param ServerCreateInfo $serverCreateInfo
  * @param bool $isImport
  * @return DBServer
  */
 public static function Create(ServerCreateInfo $creInfo, $isImport = false, $setPendingStatus = false)
 {
     $db = \Scalr::getDb();
     $startWithLetter = in_array($creInfo->platform, array(SERVER_PLATFORMS::CLOUDSTACK, SERVER_PLATFORMS::IDCF, SERVER_PLATFORMS::GCE));
     if ($isImport) {
         $startWithLetter = true;
     }
     $server_id = Scalr::GenerateUID(false, $startWithLetter);
     $status = !$isImport ? SERVER_STATUS::PENDING_LAUNCH : SERVER_STATUS::IMPORTING;
     if ($setPendingStatus) {
         $status = SERVER_STATUS::PENDING;
     }
     // IF no index defined
     if (!$creInfo->index && !$isImport) {
         $indexes = $db->GetAll("\n                SELECT `index` FROM servers\n                WHERE farm_roleid=?\n                AND status NOT IN (?,?,?)\n            ", array($creInfo->dbFarmRole->ID, SERVER_STATUS::TERMINATED, SERVER_STATUS::PENDING_TERMINATE, SERVER_STATUS::TROUBLESHOOTING));
         $used_indexes = array();
         if (count($indexes) > 0) {
             foreach ($indexes as $index) {
                 $used_indexes[$index['index']] = true;
             }
         }
         for ($i = 1;; $i++) {
             if (!$used_indexes[$i]) {
                 $creInfo->index = $i;
                 break;
             }
         }
     } elseif ($isImport) {
         $creInfo->index = 0;
     }
     $client_id = $creInfo->clientId ? $creInfo->clientId : $creInfo->dbFarmRole->GetFarmObject()->ClientID;
     $db->Execute("\n            INSERT INTO servers SET\n            `server_id`     = ?,\n            `farm_id`       = ?,\n            `env_id`        = ?,\n            `farm_roleid`   = ?,\n            `client_id`     = ?,\n            `platform`      = ?,\n            `status`        = ?,\n            `remote_ip`     = ?,\n            `local_ip`      = ?,\n            `dtadded`       = NOW(),\n            `index`         = ?\n        ", array($server_id, $creInfo->farmId ? $creInfo->farmId : $creInfo->dbFarmRole->FarmID, $creInfo->envId, $creInfo->dbFarmRole ? $creInfo->dbFarmRole->ID : 0, $client_id, $creInfo->platform, $status, $creInfo->remoteIp, $creInfo->localIp, $creInfo->index));
     $DBServer = DBServer::LoadByID($server_id);
     $DBServer->SetProperties($creInfo->GetProperties());
     $DBServer->setOsType($DBServer->osType);
     try {
         if ($DBServer->farmRoleId) {
             $db->Execute("INSERT INTO servers_launch_timelog SET\n                    `server_id`     = ?,\n                    `os_family`     = ?,\n                    `os_version`    = ?,\n                    `cloud`         = ?,\n                    `cloud_location`    = ?,\n                    `server_type`       = ?,\n                    `behaviors`     = ?,\n                    `ts_created`    = ?\n                ", array($server_id, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->family, $DBServer->GetFarmRoleObject()->GetRoleObject()->getOs()->version, $DBServer->platform, $DBServer->cloudLocation, $DBServer->GetFlavor(), implode(",", $DBServer->GetFarmRoleObject()->GetRoleObject()->getBehaviors()), time()));
         }
     } catch (Exception $e) {
     }
     return $DBServer;
 }
Beispiel #23
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\Type\GeneratedValueTypeInterface::generateValue()
  */
 public function generateValue($entity = null)
 {
     return \Scalr::GenerateUID(true);
 }
 public function create(array $config)
 {
     $deleteFlag = false;
     $type = $config['type'];
     $settings = array();
     if (!in_array($type, array(self::TYPE_RAID_EBS, self::TYPE_RAID_CSVOL, self::TYPE_RAID_CINDER, self::TYPE_EBS, self::TYPE_CSVOL, self::TYPE_CINDER, self::TYPE_GCE_PD, self::TYPE_RAID_GCE_PD))) {
         throw new FarmRoleStorageException('[Storage] Invalid type');
     }
     if ($type == self::TYPE_CSVOL || $type == self::TYPE_RAID_CSVOL) {
         $volSize = intval($config['settings'][self::SETTING_CSVOL_SIZE]);
         $settings[self::SETTING_CSVOL_SNAPSHOT] = $config['settings'][self::SETTING_CSVOL_SNAPSHOT];
         $settings[self::SETTING_CSVOL_SIZE] = $volSize;
         $settings[self::SETTING_CSVOL_DISK_OFFERING] = $config['settings'][self::SETTING_CSVOL_DISK_OFFERING];
         $settings[self::SETTING_CSVOL_DISK_OFFERING_TYPE] = $config['settings'][self::SETTING_CSVOL_DISK_OFFERING_TYPE];
     } elseif ($type == self::TYPE_CINDER || $type == self::TYPE_RAID_CINDER) {
         $volSize = intval($config['settings'][self::SETTING_CINDER_SIZE]);
         if ($volSize < 1 || $volSize > 1024) {
             throw new FarmRoleStorageException('Volume size should be from 1 to 1024 GB');
         }
         $settings[self::SETTING_CINDER_SNAPSHOT] = $config['settings'][self::SETTING_CINDER_SNAPSHOT];
         $settings[self::SETTING_CINDER_VOLUME_TYPE] = $config['settings'][self::SETTING_CINDER_VOLUME_TYPE];
         $settings[self::SETTING_CINDER_SIZE] = $volSize;
     } elseif ($type == self::TYPE_GCE_PD || $type == self::TYPE_RAID_GCE_PD) {
         $volSize = intval($config['settings'][self::SETTING_GCE_PD_SIZE]);
         $settings[self::SETTING_GCE_PD_SNAPSHOT] = $config['settings'][self::SETTING_GCE_PD_SNAPSHOT];
         $settings[self::SETTING_GCE_PD_SIZE] = $volSize;
         if (isset($config['settings'][self::SETTING_GCE_PD_TYPE])) {
             if (!in_array($config['settings'][self::SETTING_GCE_PD_TYPE], array('pd-standard', 'pd-ssd'))) {
                 throw new FarmRoleStorageException('Invalid GCE disk type');
             }
             $settings[self::SETTING_GCE_PD_TYPE] = $config['settings'][self::SETTING_GCE_PD_TYPE];
         }
     } elseif ($type == self::TYPE_EBS || $type == self::TYPE_RAID_EBS) {
         $ebsSize = intval($config['settings'][self::SETTING_EBS_SIZE]);
         $ebsType = $config['settings'][self::SETTING_EBS_TYPE];
         $ebsIops = intval($config['settings'][self::SETTING_EBS_IOPS]);
         $ebsSnapshot = $config['settings'][self::SETTING_EBS_SNAPSHOT];
         if (!in_array($ebsType, array('standard', 'io1', 'gp2'))) {
             throw new FarmRoleStorageException('EBS type should be standard, gp2 or io1');
         }
         if ($ebsSize < 1 || $ebsSize > 1024) {
             throw new FarmRoleStorageException('EBS size should be from 1 to 1024 GB');
         }
         $settings[self::SETTING_EBS_SIZE] = $ebsSize;
         $settings[self::SETTING_EBS_TYPE] = $ebsType;
         if ($ebsType == 'io1') {
             if ($ebsIops < 100 || $ebsIops > 2000) {
                 throw new FarmRoleStorageException('EBS iops should be from 100 to 2000');
             }
             if ($ebsIops / $ebsSize > 10) {
                 throw new FarmRoleStorageException(sprintf('Invalid ratio. You should increase volume size to %d GB or decrease volume iops to %d', (int) $ebsIops / 10, $ebsSize * 10));
             }
             $settings[self::SETTING_EBS_IOPS] = $ebsIops;
         }
         $settings[self::SETTING_EBS_SNAPSHOT] = $ebsSnapshot;
         if ($type == self::TYPE_EBS) {
             $settings[self::SETTING_EBS_ENCRYPTED] = !empty($config['settings'][self::SETTING_EBS_ENCRYPTED]) ? 1 : 0;
             if ($settings[self::SETTING_EBS_ENCRYPTED] && !empty($config['settings'][self::SETTING_EBS_KMS_KEY_ID])) {
                 $settings[self::SETTING_EBS_KMS_KEY_ID] = $config['settings'][self::SETTING_EBS_KMS_KEY_ID];
             }
         }
     }
     // TODO: validate raid, cvsol
     $settings[self::SETTING_RAID_LEVEL] = $config['settings'][self::SETTING_RAID_LEVEL];
     $settings[self::SETTING_RAID_VOLUMES_COUNT] = $config['settings'][self::SETTING_RAID_VOLUMES_COUNT];
     if ($config['id']) {
         $this->loadById($config['id']);
         if ($this->status == self::STATE_PENDING_CREATE) {
             if ($config['status'] == self::STATE_PENDING_DELETE) {
                 // mark for delete on save
                 $deleteFlag = true;
             } else {
                 $this->type = $config['type'];
                 $this->fs = $config['fs'];
                 $this->reUse = !empty($config['reUse']) ? 1 : NULL;
                 $this->rebuild = !empty($config['rebuild']) ? 1 : NULL;
                 $this->mount = !empty($config['mount']) ? 1 : NULL;
                 $this->mountPoint = $config['mountPoint'];
             }
         } elseif ($config['status'] == self::STATE_PENDING_DELETE) {
             $this->status = self::STATE_PENDING_DELETE;
         }
     } else {
         $this->id = \Scalr::GenerateUID();
         $this->type = $config['type'];
         $this->fs = $config['fs'];
         $this->reUse = !empty($config['reUse']) ? 1 : NULL;
         $this->rebuild = !empty($config['rebuild']) ? 1 : NULL;
         $this->mount = !empty($config['mount']) ? 1 : NULL;
         $this->mountPoint = $config['mountPoint'];
         $this->status = self::STATE_PENDING_CREATE;
     }
     if ($deleteFlag) {
         $this->delete();
         return;
     }
     $this->settings = $settings;
     $this->save();
 }
Beispiel #25
0
 /**
  * Reset cloud credentials id on clone
  */
 public function __clone()
 {
     $this->_properties = clone $this->properties;
     $unref = null;
     $this->id =& $unref;
     $this->name = "{$this->envId}-{$this->accountId}-{$this->cloud}-" . \Scalr::GenerateUID(true);
     $this->_properties->setCriteria([['cloudCredentialsId' => &$this->id]]);
     $this->_properties->setDefaultProperties(['cloudCredentialsId' => &$this->id]);
 }
Beispiel #26
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\AbstractTask::enqueue
  */
 public function enqueue()
 {
     $logger = $this->getLogger();
     if (!\Scalr::getContainer()->analytics->enabled) {
         $logger->info("CA has not been enabled in config!\n");
     }
     $db = \Scalr::getDb();
     $cadb = \Scalr::getContainer()->cadb;
     $pricing = new stdPricing();
     $quarters = new Quarters(SettingEntity::getQuarters());
     $logger->info('Started AnalyticsDemo process');
     $tzUtc = new DateTimeZone('UTC');
     /* @var $projects stdProject[] */
     $projects = [];
     /* @var $ccs stdCc[] */
     $ccs = [];
     /* @var $farms stdFarm[] */
     $farms = [];
     /* @var $environments stdEnv[] */
     $environments = [];
     /* @var $farmRoles stdFarmRole[] */
     //$farmRoles = [];
     //Analytics container
     $analytics = \Scalr::getContainer()->analytics;
     $logger->debug('CC & PROJECTS ---');
     foreach ($analytics->ccs->all(true) as $cc) {
         /* @var $cc \Scalr\Stats\CostAnalytics\Entity\CostCentreEntity */
         $co = new stdCc();
         $co->cc = $cc;
         $ccs[$cc->ccId] = $co;
         $logger->debug("Cost center: '%s'", $cc->name);
         foreach ($cc->getProjects() as $project) {
             /* @var $project \Scalr\Stats\CostAnalytics\Entity\ProjectEntity */
             $project->loadProperties();
             $po = new stdProject();
             $po->project = $project;
             $po->cc = $co;
             $projects[$project->projectId] = $po;
             $logger->debug("-- Project: '%s'", $project->name);
         }
     }
     //Ordering cost centers
     $number = 0;
     foreach ($ccs as $obj) {
         $obj->number = $number++;
     }
     //Ordering projects
     $number = 0;
     foreach ($projects as $obj) {
         $obj->number = $number++;
     }
     $logger->debug("FARMS ---");
     $pastIterations = static::PAST_HOURS_INIT;
     //Current time
     $start = new DateTime('now', $tzUtc);
     $dt = clone $start;
     do {
         $timestamp = $dt->format('Y-m-d H:00:00');
         $period = $quarters->getPeriodForDate($dt->format('Y-m-d'));
         $logger->info("Processing time:%s, year:%d, quarter:%d", $timestamp, $period->year, $period->quarter);
         //Gets farms for each project
         foreach ($projects as $po) {
             foreach ($analytics->projects->getFarmsList($po->project->projectId) as $farmId => $farmName) {
                 if (!isset($farms[$farmId])) {
                     $fo = new stdFarm();
                     $fo->farm = \DBFarm::LoadByID($farmId);
                     $fo->project = $po;
                     $fo->cc = $po->cc;
                     //$po->farms[] = $fo;
                     $farms[$farmId] = $fo;
                     if (!isset($environments[$fo->farm->EnvID])) {
                         $eo = new stdEnv();
                         $eo->env = $fo->farm->getEnvironmentObject();
                         //$eo->farms = [$farmId => $fo];
                         $environments[$fo->farm->EnvID] = $eo;
                         $fo->env = $eo;
                     } else {
                         //$environments[$fo->farm->EnvID]->farms[$farmId] = $fo;
                         $fo->env = $environments[$fo->farm->EnvID];
                     }
                     $fo->farmRoles = [];
                     foreach ($fo->farm->GetFarmRoles() as $farmRole) {
                         $fro = new stdFarmRole();
                         $fro->farmRole = $farmRole;
                         $fro->farm = $fo;
                         $fro->min = $farmRole->GetSetting(\DBFarmRole::SETTING_SCALING_MIN_INSTANCES);
                         $fro->max = $farmRole->GetSetting(\DBFarmRole::SETTING_SCALING_MAX_INSTANCES);
                         $fo->farmRoles[$farmRole->ID] = $fro;
                         //$farmRoles[$farmRole->ID] = $fro;
                     }
                 } else {
                     $fo = $farms[$farmId];
                 }
                 $logger->debug("Farm:'%s':%d from Env:'%s':%d corresponds to Project:'%s' -> CC:'%s'", $fo->farm->Name, $fo->farm->ID, $fo->farm->getEnvironmentObject()->name, $fo->farm->EnvID, $po->project->name, $po->cc->cc->name);
                 foreach ($fo->farmRoles as $fro) {
                     /* @var $fro stdFarmRole */
                     $countInstances = rand(max(1, floor($fro->max * 0.7)), min((int) $fro->max, 2));
                     $cost = $pricing->getPrice($dt, $fro->farmRole->Platform, $fro->farmRole->CloudLocation, $fro->getInstanceType(), $fo->env->getUrl($fro->farmRole->Platform), PriceEntity::OS_LINUX);
                     $type = UsageTypeEntity::NAME_COMPUTE_BOX_USAGE;
                     $costDistType = UsageTypeEntity::COST_DISTR_TYPE_COMPUTE;
                     $usageTypeEntity = UsageTypeEntity::findOne([['costDistrType' => $costDistType], ['name' => $type]]);
                     /* @var $usageTypeEntity UsageTypeEntity */
                     if ($usageTypeEntity === null) {
                         $usageTypeEntity = new UsageTypeEntity();
                         $usageTypeEntity->costDistrType = $costDistType;
                         $usageTypeEntity->name = $type;
                         $usageTypeEntity->displayName = 'Compute instances';
                         $usageTypeEntity->save();
                     }
                     $item = $fro->getInstanceType();
                     $usageItemEntity = UsageItemEntity::findOne([['usageType' => $usageTypeEntity->id], ['name' => $item]]);
                     /* @var $usageItemEntity UsageItemEntity */
                     if ($usageItemEntity === null) {
                         $usageItemEntity = new UsageItemEntity();
                         $usageItemEntity->usageType = $usageTypeEntity->id;
                         $usageItemEntity->name = $item;
                         $usageItemEntity->save();
                     }
                     //Hourly usage
                     $rec = new UsageHourlyEntity();
                     $rec->usageId = \Scalr::GenerateUID();
                     $rec->accountId = $fro->farm->farm->ClientID;
                     $rec->ccId = $po->cc->cc->ccId;
                     $rec->projectId = $po->project->projectId;
                     $rec->cloudLocation = $fro->farmRole->CloudLocation;
                     $rec->dtime = new DateTime($timestamp, $tzUtc);
                     $rec->envId = $fo->farm->EnvID;
                     $rec->farmId = $fo->farm->ID;
                     $rec->farmRoleId = $fro->farmRole->ID;
                     $rec->usageItem = $usageItemEntity->id;
                     $rec->platform = $fro->farmRole->Platform;
                     $rec->url = $fo->env->getUrl($fro->farmRole->Platform);
                     $rec->os = PriceEntity::OS_LINUX;
                     $rec->num = $countInstances;
                     $rec->cost = $cost * $countInstances;
                     $rec->save();
                     $logger->log(static::PAST_HOURS_INIT > 0 ? 'DEBUG' : 'INFO', "-- role:'%s':%d platform:%s, min:%d - max:%d, cloudLocation:'%s', usageItem:'%s', " . "cost:%0.4f * %d = %0.3f", $fro->farmRole->Alias, $fro->farmRole->ID, $fro->farmRole->Platform, $fro->min, $fro->max, $fro->farmRole->CloudLocation, $usageItemEntity->id, $cost, $countInstances, $rec->cost);
                     //Update Daily table
                     $cadb->Execute("\n                                INSERT usage_d\n                                SET date = ?,\n                                    platform = ?,\n                                    cc_id = UNHEX(?),\n                                    project_id = UNHEX(?),\n                                    farm_id = ?,\n                                    env_id = ?,\n                                    cost = ?\n                                ON DUPLICATE KEY UPDATE cost = cost + ?\n                            ", [$rec->dtime->format('Y-m-d'), $rec->platform, $rec->ccId ? str_replace('-', '', $rec->ccId) : '00000000-0000-0000-0000-000000000000', $rec->projectId ? str_replace('-', '', $rec->projectId) : '00000000-0000-0000-0000-000000000000', $rec->farmId ? $rec->farmId : 0, $rec->envId ? $rec->envId : 0, $rec->cost, $rec->cost]);
                     //Updates Quarterly Budget
                     if ($rec->ccId) {
                         $cadb->Execute("\n                                    INSERT quarterly_budget\n                                    SET year = ?,\n                                        subject_type = ?,\n                                        subject_id = UNHEX(?),\n                                        quarter = ?,\n                                        budget = 1000,\n                                        cumulativespend = ?\n                                    ON DUPLICATE KEY UPDATE cumulativespend = cumulativespend + ?\n                                ", [$period->year, QuarterlyBudgetEntity::SUBJECT_TYPE_CC, str_replace('-', '', $rec->ccId), $period->quarter, $rec->cost, $rec->cost]);
                     }
                     if ($rec->projectId) {
                         $cadb->Execute("\n                                    INSERT quarterly_budget\n                                    SET year = ?,\n                                        subject_type = ?,\n                                        subject_id = UNHEX(?),\n                                        quarter = ?,\n                                        budget = 1000,\n                                        cumulativespend = ?\n                                    ON DUPLICATE KEY UPDATE cumulativespend = cumulativespend + ?\n                                ", [$period->year, QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT, str_replace('-', '', $rec->projectId), $period->quarter, $rec->cost, $rec->cost]);
                     }
                 }
                 unset($fo);
             }
         }
         $dt->modify('-1 hour');
     } while ($pastIterations-- > 0);
     $dt = clone $start;
     $start->modify(sprintf("-%d hour", static::PAST_HOURS_INIT));
     $start->setTime(0, 0, 0);
     $date = $dt->format('Y-m-d');
     $hours = (int) $dt->format('H');
     do {
         $cadb->Execute("\n                    INSERT INTO `farm_usage_d` (\n                        `account_id`,\n                        `farm_role_id`,\n                        `usage_item`,\n                        `cc_id`,\n                        `project_id`,\n                        `date`,\n                        `platform`,\n                        `cloud_location`,\n                        `env_id`,\n                        `farm_id`,\n                        `role_id`,\n                        `cost`,\n                        `min_usage`,\n                        `max_usage`,\n                        `usage_hours`,\n                        `working_hours`)\n                    SELECT\n                        `account_id`,\n                        IFNULL(`farm_role_id`, 0) `farm_role_id`,\n                        `usage_item`,\n                        IFNULL(`cc_id`, '') `cc_id`,\n                        IFNULL(`project_id`, '') `project_id`,\n                        ? `date`,\n                        `platform`,\n                        `cloud_location`,\n                        IFNULL(`env_id`, 0) `env_id`,\n                        IFNULL(`farm_id`, 0) `farm_id`,\n                        IFNULL(`role_id`, 0) `role_id`,\n                        SUM(`cost`) `cost`,\n                        (CASE WHEN COUNT(`dtime`) >= ? THEN MIN(`num`) ELSE 0 END) `min_usage`,\n                        MAX(`num`) `max_usage`,\n                        SUM(`num`) `usage_hours`,\n                        COUNT(`dtime`) `working_hours`\n                    FROM `usage_h` `uh`\n                    WHERE `uh`.`dtime` BETWEEN ? AND ?\n                    AND `uh`.`farm_id` > 0\n                    AND `uh`.`farm_role_id` > 0\n                    GROUP BY `uh`.`account_id` , `uh`.`farm_role_id` , `uh`.`usage_item`\n                    ON DUPLICATE KEY UPDATE\n                        `cost` = VALUES(`cost`),\n                        `min_usage` = VALUES(`min_usage`),\n                        `max_usage` = VALUES(`max_usage`),\n                        `usage_hours` = VALUES(`usage_hours`),\n                        `working_hours` = VALUES(`working_hours`)\n                ", ["{$date} 00:00:00", $hours, "{$date} 00:00:00", "{$date} 23:00:00"]);
         $dt->modify('-1 day');
         $date = $dt->format('Y-m-d');
         $hours = 24;
     } while ($dt >= $start);
     $logger->info("Finished AnalyticsDemo process");
     $logger->info("Memory usage: %0.3f Mb", memory_get_usage() / 1024 / 1024);
     return new ArrayObject();
 }
Beispiel #27
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;
 }
Beispiel #28
0
 /**
  * Makes clod credentials entity for specified platform
  *
  * @param   string $platform             Cloud credentials platform
  * @param   array  $parameters           Array of cloud credentials parameters
  * @param   int    $status      optional Cloud credentials status
  *
  * @return Entity\CloudCredentials Returns new cloud credentials entity
  *
  * @throws Exception
  */
 public function makeCloudCredentials($platform, $parameters, $status = Entity\CloudCredentials::STATUS_ENABLED)
 {
     $cloudCredentials = new Entity\CloudCredentials();
     $cloudCredentials->envId = $this->env->id;
     $cloudCredentials->accountId = $this->env->getAccountId();
     $cloudCredentials->cloud = $platform;
     $cloudCredentials->name = "{$this->env->id}-{$this->env->getAccountId()}-{$platform}-" . \Scalr::GenerateUID(true);
     $cloudCredentials->status = $status;
     try {
         $this->db->BeginTrans();
         $cloudCredentials->save();
         $cloudCredentials->properties->saveSettings($parameters);
         $cloudCredentials->bindToEnvironment($this->env);
         $this->db->CommitTrans();
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $cloudCredentials->cache($this->env->getContainer());
     return $cloudCredentials;
 }
Beispiel #29
0
 public static function prepareScript($scriptSettings, DBServer $targetServer, Event $event = null)
 {
     $db = \Scalr::getDb();
     $template = array('timeout' => $scriptSettings['timeout'], 'issync' => $scriptSettings['issync'], 'run_as' => $scriptSettings['run_as'], 'execution_id' => Scalr::GenerateUID());
     if ($scriptSettings['scriptid']) {
         if ($scriptSettings['version'] == 'latest' || (int) $scriptSettings['version'] == -1) {
             $version = (int) $db->GetOne("SELECT MAX(revision) FROM script_revisions WHERE scriptid=?", array($scriptSettings['scriptid']));
         } else {
             $version = (int) $scriptSettings['version'];
         }
         $info = $db->GetRow("SELECT name,id FROM scripts WHERE id=? LIMIT 1", array($scriptSettings['scriptid']));
         $template['name'] = $info['name'];
         $template['id'] = $info['id'];
         $revisionInfo = $db->GetRow("SELECT script, variables FROM script_revisions WHERE scriptid=? AND revision=? LIMIT 1", array($template['id'], $version));
         $template['body'] = $revisionInfo['script'];
         if (!$template['body']) {
             return false;
         }
         $scriptParams = (array) unserialize($revisionInfo['variables']);
         foreach ($scriptParams as &$val) {
             $val = "";
         }
         $params = array_merge($scriptParams, $targetServer->GetScriptingVars(), (array) unserialize($scriptSettings['params']));
         if ($event) {
             $eventServer = $event->DBServer;
             foreach ($eventServer->GetScriptingVars() as $k => $v) {
                 $params["event_{$k}"] = $v;
             }
             foreach ($event->GetScriptingVars() as $k => $v) {
                 $params[$k] = $event->{$v};
             }
             if (isset($event->params) && is_array($event->params)) {
                 foreach ($event->params as $k => $v) {
                     $params[$k] = $v;
                 }
             }
             $params['event_name'] = $event->GetName();
         }
         if ($event instanceof CustomEvent) {
             if (count($event->params) > 0) {
                 $params = array_merge($params, $event->params);
             }
         }
         // Prepare keys array and array with values for replacement in script
         $keys = array_keys($params);
         $f = create_function('$item', 'return "%".$item."%";');
         $keys = array_map($f, $keys);
         $values = array_values($params);
         $script_contents = str_replace($keys, $values, $template['body']);
         $template['body'] = str_replace('\\%', "%", $script_contents);
         // Parse and set variables from data bag
         //TODO: @param_name@
         // Generate script contents
         $template['name'] = preg_replace("/[^A-Za-z0-9]+/", "_", $template['name']);
     } else {
         $template['path'] = $scriptSettings['script_path'];
     }
     return $template;
 }