Beispiel #1
0
 public function applyDefinition($definition, $reset = false)
 {
     $resetSettings = array(Entity\FarmRoleSetting::BALANCING_USE_ELB, Entity\FarmRoleSetting::BALANCING_HOSTNAME, Entity\FarmRoleSetting::BALANCING_NAME, Entity\FarmRoleSetting::BALANCING_HC_TIMEOUT, Entity\FarmRoleSetting::BALANCING_HC_TARGET, Entity\FarmRoleSetting::BALANCING_HC_INTERVAL, Entity\FarmRoleSetting::BALANCING_HC_UTH, Entity\FarmRoleSetting::BALANCING_HC_HTH, Entity\FarmRoleSetting::BALANCING_HC_HASH, Entity\FarmRoleSetting::BALANCING_AZ_HASH, Entity\FarmRoleSetting::CLOUDSTACK_STATIC_NAT_MAP, Entity\FarmRoleSetting::AWS_ELASIC_IPS_MAP, Entity\FarmRoleSetting::AWS_S3_BUCKET, Entity\FarmRoleSetting::MYSQL_PMA_USER, Entity\FarmRoleSetting::MYSQL_PMA_PASS, Entity\FarmRoleSetting::MYSQL_PMA_REQUEST_ERROR, Entity\FarmRoleSetting::MYSQL_PMA_REQUEST_TIME, Entity\FarmRoleSetting::MYSQL_LAST_BCP_TS, Entity\FarmRoleSetting::MYSQL_LAST_BUNDLE_TS, Entity\FarmRoleSetting::MYSQL_IS_BCP_RUNNING, Entity\FarmRoleSetting::MYSQL_IS_BUNDLE_RUNNING, Entity\FarmRoleSetting::MYSQL_BCP_SERVER_ID, Entity\FarmRoleSetting::MYSQL_BUNDLE_SERVER_ID, Entity\FarmRoleSetting::MYSQL_SLAVE_TO_MASTER, Entity\FarmRoleSetting::MYSQL_ROOT_PASSWORD, Entity\FarmRoleSetting::MYSQL_REPL_PASSWORD, Entity\FarmRoleSetting::MYSQL_STAT_PASSWORD, Entity\FarmRoleSetting::MYSQL_LOG_FILE, Entity\FarmRoleSetting::MYSQL_LOG_POS, Entity\FarmRoleSetting::MYSQL_SCALR_SNAPSHOT_ID, Entity\FarmRoleSetting::MYSQL_SCALR_VOLUME_ID, Entity\FarmRoleSetting::MYSQL_SNAPSHOT_ID, Entity\FarmRoleSetting::MYSQL_MASTER_EBS_VOLUME_ID, Entity\FarmRoleSetting::AWS_ELB_ID, Entity\FarmRoleSetting::AWS_ELB_ENABLED, Scalr_Db_Msr::DATA_BACKUP_IS_RUNNING, Scalr_Db_Msr::DATA_BACKUP_LAST_TS, Scalr_Db_Msr::DATA_BACKUP_SERVER_ID, Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, Scalr_Db_Msr::DATA_BUNDLE_LAST_TS, Scalr_Db_Msr::DATA_BUNDLE_SERVER_ID, Scalr_Db_Msr::SLAVE_TO_MASTER, Scalr_Db_Msr::SNAPSHOT_ID, Scalr_Db_Msr::VOLUME_ID, Scalr_Role_Behavior_RabbitMQ::ROLE_COOKIE_NAME, Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_SERVER_ID, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUESTED, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_ERROR_MSG, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_URL, Scalr_Role_Behavior_MongoDB::ROLE_PASSWORD, Scalr_Role_Behavior_MongoDB::ROLE_KEYFILE, Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_STATUS, Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_IS_REMOVING_SHARD_INDEX, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_IS_RUNNING, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_SERVER_ID, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_LAST_TS, Scalr_Role_Behavior_Router::ROLE_VPC_NID, Scalr_Role_Behavior_Router::ROLE_VPC_IP, Scalr_Role_Behavior_Router::ROLE_VPC_AID, Scalr_Role_Behavior_Router::ROLE_VPC_ROUTER_CONFIGURED);
     // Set settings
     foreach ($definition->settings as $key => $value) {
         if ($reset && in_array($key, $resetSettings)) {
             continue;
         }
         $this->SetSetting($key, $value, Entity\FarmRoleSetting::TYPE_CFG);
     }
     //Farm Global Variables
     $variables = new Scalr_Scripting_GlobalVariables($this->GetFarmObject()->ClientID, $this->GetFarmObject()->EnvID, ScopeInterface::SCOPE_FARMROLE);
     $variables->setValues($definition->globalVariables, $this->RoleID, $this->FarmID, $this->ID);
     //Storage
     $this->getStorage()->setConfigs($definition->storage);
     // Scripts
     $scripts = array();
     foreach ($definition->scripts as $script) {
         $scripts[] = array('params' => $script->params, 'target' => $script->target, 'order_index' => $script->orderIndex, 'version' => (int) $script->version, 'isSync' => (int) $script->isSync, 'timeout' => $script->timeout, 'event' => $script->event, 'script_id' => (int) $script->scriptId, 'script_path' => $script->scriptPath, 'script_type' => $script->scriptType, 'run_as' => $script->runAs, 'target_roles' => $script->targetRoles, 'target_farmroles' => $script->targetFarmroles, 'target_behaviors' => $script->targetBehaviors);
     }
     $this->SetScripts($scripts);
     // Scaling times
     $this->DB->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($this->ID));
     foreach ($definition->scalingTimes as $scalingPeriod) {
         $this->DB->Execute("INSERT INTO farm_role_scaling_times SET\n                farm_roleid     = ?,\n                start_time      = ?,\n                end_time        = ?,\n                days_of_week    = ?,\n                instances_count = ?\n            ", array($this->ID, $scalingPeriod->startTime, $scalingPeriod->endTime, $scalingPeriod->daysOfWeek, $scalingPeriod->instanceCount));
     }
     // metrics
     $scalingManager = new Scalr_Scaling_Manager($this);
     $metrics = array();
     foreach ($definition->scalingMetrics as $metric) {
         $metrics[$metric->metricId] = $metric->settings;
     }
     $scalingManager->setFarmRoleMetrics($metrics);
     return true;
 }
 protected function GetScalingMetrics()
 {
     $ResponseDOMDocument = $this->CreateResponse();
     $metricsNode = $ResponseDOMDocument->createElement("metrics");
     $dbFarmRole = $this->DBServer->GetFarmRoleObject();
     $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
     foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleScalingMetric) {
         $scalingMetric = $farmRoleScalingMetric->getMetric();
         if ($scalingMetric->accountId == 0) {
             continue;
         }
         $metric = $ResponseDOMDocument->createElement("metric");
         $metric->setAttribute("id", $scalingMetric->id);
         $metric->setAttribute("name", $scalingMetric->name);
         $metricFilePath = $ResponseDOMDocument->createElement("path", $scalingMetric->filePath);
         $metricRM = $ResponseDOMDocument->createElement("retrieve-method", $scalingMetric->retrieveMethod);
         $metric->appendChild($metricFilePath);
         $metric->appendChild($metricRM);
         $metricsNode->appendChild($metric);
     }
     $ResponseDOMDocument->documentElement->appendChild($metricsNode);
     return $ResponseDOMDocument;
 }
Beispiel #3
0
 public function xListFarmRolesAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'farmRoleId' => array('type' => 'int'), 'roleId' => array('type' => 'int'), 'id' => array('type' => 'int'), 'sort' => array('type' => 'json')));
     $this->request->restrictFarmAccess(DBFarm::LoadByID($this->getParam('farmId')));
     $sql = "\n            SELECT farm_roles.*\n            FROM farm_roles\n            JOIN roles ON farm_roles.role_id = roles.id\n            WHERE farmid = ?\n            AND :FILTER:\n        ";
     $params = array($this->getParam('farmId'));
     if ($this->getParam('roleId')) {
         $sql .= ' AND role_id = ?';
         $params[] = $this->getParam('roleId');
     }
     if ($this->getParam('farmRoleId')) {
         $sql .= ' AND farm_roles.id = ?';
         $params[] = $this->getParam('farmRoleId');
     }
     $response = $this->buildResponseFromSql($sql, array('platform', 'name', 'alias'), array('name'), $params);
     foreach ($response['data'] as &$row) {
         $row["running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid='{$row['id']}' AND status IN ('Pending', 'Initializing', 'Running', 'Temporary')");
         $row["suspended_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid='{$row['id']}' AND status IN ('Suspended', 'Pending suspend')");
         $row["non_running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid='{$row['id']}' AND status NOT IN ('Pending', 'Initializing', 'Running', 'Temporary')");
         $row['farm_status'] = $this->db->GetOne("SELECT status FROM farms WHERE id=? LIMIT 1", array($row['farmid']));
         $row["domains"] = $this->db->GetOne("SELECT COUNT(*) FROM dns_zones WHERE farm_roleid=? AND status != ? AND farm_id=?", array($row["id"], DNS_ZONE_STATUS::PENDING_DELETE, $row['farmid']));
         $DBFarmRole = DBFarmRole::LoadByID($row['id']);
         $row['min_count'] = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MIN_INSTANCES);
         $row['max_count'] = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MAX_INSTANCES);
         $row['allow_launch_instance'] = !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB) && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER);
         $vpcId = $this->environment->getPlatformConfigValue(Ec2PlatformModule::DEFAULT_VPC_ID . ".{$DBFarmRole->CloudLocation}");
         $row['is_vpc'] = $vpcId || $DBFarmRole->GetFarmObject()->GetSetting(DBFarm::SETTING_EC2_VPC_ID) ? true : false;
         $row['location'] = $DBFarmRole->CloudLocation;
         $DBRole = DBRole::loadById($row['role_id']);
         $row["name"] = $DBRole->name;
         $row['image_id'] = $DBRole->__getNewRoleObject()->getImage($DBFarmRole->Platform, $DBFarmRole->CloudLocation)->imageId;
         if ($DBFarmRole->GetFarmObject()->Status == FARM_STATUS::RUNNING) {
             $row['shortcuts'] = [];
             foreach (\Scalr\Model\Entity\ScriptShortcut::find(array(array('farmRoleId' => $row['id']))) as $shortcut) {
                 /* @var $shortcut \Scalr\Model\Entity\ScriptShortcut */
                 $row['shortcuts'][] = array('id' => $shortcut->id, 'name' => $shortcut->getScriptName());
             }
         }
         $scalingManager = new Scalr_Scaling_Manager($DBFarmRole);
         $scaling_algos = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling_algos[] = $farmRoleMetric->getMetric()->name;
         }
         if (count($scaling_algos) == 0) {
             $row['scaling_algos'] = _("Scaling disabled");
         } else {
             $row['scaling_algos'] = implode(', ', $scaling_algos);
         }
     }
     $this->response->data($response);
 }
Beispiel #4
0
 public function xListFarmRolesAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'farmRoleId' => array('type' => 'int'), 'roleId' => array('type' => 'int'), 'id' => array('type' => 'int'), 'sort' => array('type' => 'json')));
     $sql = "\n            SELECT farm_roles.*\n            FROM farm_roles\n            JOIN roles ON farm_roles.role_id = roles.id\n            WHERE farmid = ?\n            AND :FILTER:\n        ";
     $params = array($this->getParam('farmId'));
     if ($this->getParam('roleId')) {
         $sql .= ' AND role_id = ?';
         $params[] = $this->getParam('roleId');
     }
     if ($this->getParam('farmRoleId')) {
         $sql .= ' AND farm_roles.id = ?';
         $params[] = $this->getParam('farmRoleId');
     }
     $response = $this->buildResponseFromSql($sql, array('platform', 'name', 'alias'), array('name'), $params);
     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_roleid` = ?\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['farm_status'] = $this->db->GetOne("SELECT status FROM farms WHERE id=? LIMIT 1", array($row['farmid']));
         $row["domains"] = $this->db->GetOne("SELECT COUNT(*) FROM dns_zones WHERE farm_roleid=? AND status != ? AND farm_id=?", array($row["id"], DNS_ZONE_STATUS::PENDING_DELETE, $row['farmid']));
         $DBFarmRole = DBFarmRole::LoadByID($row['id']);
         $row['allow_launch_instance'] = !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB) && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER);
         $vpcId = $this->environment->getPlatformConfigValue(Ec2PlatformModule::DEFAULT_VPC_ID . ".{$DBFarmRole->CloudLocation}");
         $row['is_vpc'] = $vpcId || $DBFarmRole->GetFarmObject()->GetSetting(Entity\FarmSetting::EC2_VPC_ID) ? true : false;
         $row['location'] = $DBFarmRole->CloudLocation;
         $DBRole = DBRole::loadById($row['role_id']);
         $row["name"] = $DBRole->name;
         $row['image_id'] = $DBRole->__getNewRoleObject()->getImage($DBFarmRole->Platform, $DBFarmRole->CloudLocation)->imageId;
         if ($DBFarmRole->GetFarmObject()->Status == FARM_STATUS::RUNNING) {
             $row['shortcuts'] = [];
             foreach (\Scalr\Model\Entity\ScriptShortcut::find([['farmRoleId' => $row['id']]]) as $shortcut) {
                 /* @var $shortcut \Scalr\Model\Entity\ScriptShortcut */
                 $row['shortcuts'][] = array('id' => $shortcut->id, 'name' => $shortcut->getScriptName());
             }
         }
         $row['scaling_enabled'] = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_ENABLED);
         if ($row['scaling_enabled'] == 1) {
             $row['min_count'] = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_MIN_INSTANCES);
             $row['max_count'] = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_MAX_INSTANCES);
             $scalingManager = new Scalr_Scaling_Manager($DBFarmRole);
             $scaling_algos = [];
             foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
                 $scaling_algos[] = $farmRoleMetric->getMetric()->name;
             }
             $row['scaling_algos'] = implode(', ', $scaling_algos);
         }
         $row['farmOwnerIdPerm'] = $DBFarmRole->GetFarmObject()->createdByUserId == $this->user->getId();
         $row['farmTeamIdPerm'] = $DBFarmRole->GetFarmObject()->teamId ? $this->user->isInTeam($DBFarmRole->GetFarmObject()->teamId) : false;
     }
     $this->response->data($response);
 }
 public function applyDefinition($definition, $reset = false)
 {
     $resetSettings = array(DBFarmRole::SETTING_BALANCING_HOSTNAME, DBFarmRole::SETTING_BALANCING_NAME, DBFarmRole::SETTING_AWS_S3_BUCKET, DBFarmRole::SETTING_MYSQL_PMA_USER, DBFarmRole::SETTING_MYSQL_PMA_PASS, DBFarmRole::SETTING_MYSQL_PMA_REQUEST_ERROR, DBFarmRole::SETTING_MYSQL_PMA_REQUEST_TIME, DBFarmRole::SETTING_MYSQL_LAST_BCP_TS, DBFarmRole::SETTING_MYSQL_LAST_BUNDLE_TS, DBFarmRole::SETTING_MYSQL_IS_BCP_RUNNING, DBFarmRole::SETTING_MYSQL_IS_BUNDLE_RUNNING, DBFarmRole::SETTING_MYSQL_BCP_SERVER_ID, DBFarmRole::SETTING_MYSQL_BUNDLE_SERVER_ID, DBFarmRole::SETTING_MYSQL_SLAVE_TO_MASTER, DBFarmRole::SETTING_MYSQL_ROOT_PASSWORD, DBFarmRole::SETTING_MYSQL_REPL_PASSWORD, DBFarmRole::SETTING_MYSQL_STAT_PASSWORD, DBFarmRole::SETTING_MYSQL_LOG_FILE, DBFarmRole::SETTING_MYSQL_LOG_POS, DBFarmRole::SETTING_MYSQL_SCALR_SNAPSHOT_ID, DBFarmRole::SETTING_MYSQL_SCALR_VOLUME_ID, DBFarmRole::SETTING_MYSQL_SNAPSHOT_ID, DBFarmRole::SETTING_MYSQL_MASTER_EBS_VOLUME_ID, Scalr_Db_Msr::DATA_BACKUP_IS_RUNNING, Scalr_Db_Msr::DATA_BACKUP_LAST_TS, Scalr_Db_Msr::DATA_BACKUP_SERVER_ID, Scalr_Db_Msr::DATA_BUNDLE_IS_RUNNING, Scalr_Db_Msr::DATA_BUNDLE_LAST_TS, Scalr_Db_Msr::DATA_BUNDLE_SERVER_ID, Scalr_Db_Msr::SLAVE_TO_MASTER, Scalr_Db_Msr::SNAPSHOT_ID, Scalr_Db_Msr::VOLUME_ID, Scalr_Role_Behavior_RabbitMQ::ROLE_COOKIE_NAME, Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_SERVER_ID, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUESTED, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_ERROR_MSG, Scalr_Role_Behavior_RabbitMQ::ROLE_CP_URL, Scalr_Role_Behavior_MongoDB::ROLE_PASSWORD, Scalr_Role_Behavior_MongoDB::ROLE_KEYFILE, Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_STATUS, Scalr_Role_Behavior_MongoDB::ROLE_CLUSTER_IS_REMOVING_SHARD_INDEX, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_IS_RUNNING, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_SERVER_ID, Scalr_Role_Behavior_MongoDB::DATA_BUNDLE_LAST_TS);
     // Set settings
     foreach ($definition->settings as $key => $value) {
         if ($reset && in_array($key, $resetSettings)) {
             continue;
         }
         $this->SetSetting($key, $value);
     }
     // Presets
     $presets = array();
     foreach ($definition->presets as $preset) {
         $presets[$preset->behavior] = $preset->presetId;
     }
     $this->SetServiceConfigPresets($presets);
     // Scripts
     $scripts = array();
     foreach ($definition->scripts as $script) {
         $scripts[] = array('params' => $script->params, 'target' => $script->target, 'order_index' => $script->orderIndex, 'version' => $script->version, 'issync' => $script->isSync, 'timeout' => $script->timeout, 'event' => $script->event, 'script_id' => $script->scriptId);
     }
     $this->SetScripts($scripts);
     // Scaling times
     $this->DB->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", array($this->ID));
     foreach ($definition->scalingTimes as $scalingPeriod) {
         $this->DB->Execute("INSERT INTO farm_role_scaling_times SET\r\n\t\t\t\t\tfarm_roleid\t\t= ?,\r\n\t\t\t\t\tstart_time\t\t= ?,\r\n\t\t\t\t\tend_time\t\t= ?,\r\n\t\t\t\t\tdays_of_week\t= ?,\r\n\t\t\t\t\tinstances_count\t= ?\r\n\t\t\t\t", array($this->ID, $scalingPeriod->startTime, $scalingPeriod->endTime, $scalingPeriod->daysOfWeek, $scalingPeriod->instanceCount));
     }
     // metrics
     $scalingManager = new Scalr_Scaling_Manager($this);
     $metrics = array();
     foreach ($definition->scalingMetrics as $metric) {
         $metrics[$metric->metricId] = $metric->settings;
     }
     $scalingManager->setFarmRoleMetrics($metrics);
     // params
     $params = array();
     foreach ($definition->parameters as $param) {
         $params[$param->name] = $param->value;
     }
     $this->SetParameters($params);
     return true;
 }
Beispiel #6
0
 public function xListFarmRolesAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'farmRoleId' => array('type' => 'int'), 'roleId' => array('type' => 'int'), 'id' => array('type' => 'int'), 'sort' => array('type' => 'string', 'default' => 'id'), 'dir' => array('type' => 'string', 'default' => 'ASC')));
     $sql = "SELECT * from farm_roles WHERE farmid=" . $this->db->qstr($this->getParam('farmId'));
     if ($this->getParam('roleId')) {
         $sql .= " AND role_id=" . $this->db->qstr($this->getParam('roleId'));
     }
     if ($this->getParam('farmRoleId')) {
         $sql .= " AND id=" . $this->db->qstr($this->getParam('farmRoleId'));
     }
     $response = $this->buildResponseFromSql($sql, array("role_id", "platform"));
     foreach ($response['data'] as &$row) {
         $row["running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid='{$row['id']}' AND status IN ('Pending', 'Initializing', 'Running', 'Temporary')");
         $row["non_running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid='{$row['id']}' AND status NOT IN ('Pending', 'Initializing', 'Running', 'Temporary')");
         $row['farm_status'] = $this->db->GetOne("SELECT status FROM farms WHERE id=?", array($row['farmid']));
         $row["domains"] = $this->db->GetOne("SELECT COUNT(*) FROM dns_zones WHERE farm_roleid=? AND status != ? AND farm_id=?", array($row["id"], DNS_ZONE_STATUS::PENDING_DELETE, $row['farmid']));
         $DBFarmRole = DBFarmRole::LoadByID($row['id']);
         $row['min_count'] = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MIN_INSTANCES);
         $row['max_count'] = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MAX_INSTANCES);
         $row['location'] = $DBFarmRole->CloudLocation;
         $DBRole = DBRole::loadById($row['role_id']);
         $row["name"] = $DBRole->name;
         $row['image_id'] = $DBRole->getImageId($DBFarmRole->Platform, $DBFarmRole->CloudLocation);
         $row['shortcuts'] = $this->db->GetAll("SELECT * FROM farm_role_scripts WHERE farm_roleid=? AND ismenuitem='1'", array($row['id']));
         foreach ($row['shortcuts'] as &$shortcut) {
             $shortcut['name'] = $this->db->GetOne("SELECT name FROM scripts WHERE id=?", array($shortcut['scriptid']));
         }
         $scalingManager = new Scalr_Scaling_Manager($DBFarmRole);
         $scaling_algos = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling_algos[] = $farmRoleMetric->getMetric()->name;
         }
         if (count($scaling_algos) == 0) {
             $row['scaling_algos'] = _("Scaling disabled");
         } else {
             $row['scaling_algos'] = implode(', ', $scaling_algos);
         }
     }
     $this->response->data($response);
 }
Beispiel #7
0
 public function getFarm2($farmId)
 {
     $dbFarm = DBFarm::LoadByID($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $farmRoles = array();
     $variables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->user->getAccountId(), $this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         $scripts = $this->db->GetAll("\n                SELECT farm_role_scripts.*, scripts.name, scripts.os\n                FROM farm_role_scripts\n                LEFT JOIN scripts ON scripts.id = farm_role_scripts.scriptid\n                WHERE farm_roleid=? AND issystem='1'\n            ", array($dbFarmRole->ID));
         $scriptsObject = array();
         foreach ($scripts as $script) {
             if (!empty($script['scriptid']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_SCALR || !empty($script['script_path']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_LOCAL || !empty($script['params']) && $script['script_type'] == Scalr_Scripting_Manager::ORCHESTRATION_SCRIPT_TYPE_CHEF) {
                 $s = array('script_type' => $script['script_type'], 'script_id' => (int) $script['scriptid'], 'script' => $script['name'], 'os' => $script['os'], 'params' => unserialize($script['params']), 'target' => $script['target'], 'version' => (int) $script['version'], 'timeout' => $script['timeout'], 'isSync' => (int) $script['issync'], 'order_index' => $script['order_index'], 'event' => $script['event_name'], 'script_path' => $script['script_path'], 'run_as' => $script['run_as']);
                 if ($script['target'] == Script::TARGET_BEHAVIORS || $script['target'] == Script::TARGET_ROLES || $script['target'] == Script::TARGET_FARMROLES) {
                     switch ($script['target']) {
                         case $script['target'] == Script::TARGET_ROLES:
                             $varName = 'target_roles';
                             break;
                         case $script['target'] == Script::TARGET_FARMROLES:
                             $varName = 'target_farmroles';
                             break;
                         case $script['target'] == Script::TARGET_BEHAVIORS:
                             $varName = 'target_behaviors';
                             break;
                     }
                     $s[$varName] = array();
                     $r = $this->db->GetAll("SELECT `target` FROM farm_role_scripting_targets WHERE farm_role_script_id = ?", array($script['id']));
                     foreach ($r as $v) {
                         array_push($s[$varName], $v['target']);
                     }
                 }
                 $scriptsObject[] = $s;
             }
         }
         //Scripting params
         $scriptingParams = $this->db->Execute("\n                SELECT * FROM farm_role_scripting_params\n                WHERE farm_role_id = ? AND farm_role_script_id = '0'\n            ", array($dbFarmRole->ID));
         $sParams = array();
         while ($p = $scriptingParams->FetchRow()) {
             $sParams[] = array('hash' => $p['hash'], 'role_script_id' => $p['role_script_id'], 'params' => unserialize($p['params']));
         }
         $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
         $scaling = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling[$farmRoleMetric->metricId] = $farmRoleMetric->getSettings();
         }
         $dbPresets = $this->db->GetAll("SELECT * FROM farm_role_service_config_presets WHERE farm_roleid=?", array($dbFarmRole->ID));
         $presets = array();
         foreach ($dbPresets as $preset) {
             $presets[$preset['behavior']] = $preset['preset_id'];
         }
         if ($dbFarmRole->NewRoleID) {
             $roleName = DBRole::loadById($dbFarmRole->NewRoleID)->name;
             $isBundling = true;
         } else {
             $roleName = $dbFarmRole->GetRoleObject()->name;
             $isBundling = false;
         }
         $storages = array('configs' => $dbFarmRole->getStorage()->getConfigs());
         foreach ($dbFarmRole->getStorage()->getVolumes() as $configKey => $config) {
             $storages['devices'][$configKey] = array();
             foreach ($config as $device) {
                 $info = array('farmRoleId' => $device->farmRoleId, 'placement' => $device->placement, 'serverIndex' => $device->serverIndex, 'storageId' => $device->storageId, 'storageConfigId' => $device->storageConfigId, 'status' => $device->status);
                 try {
                     $server = DBServer::LoadByFarmRoleIDAndIndex($device->farmRoleId, $device->serverIndex);
                     if ($server->status != SERVER_STATUS::TERMINATED && $server->status != SERVER_STATUS::TROUBLESHOOTING) {
                         $info['serverId'] = $server->serverId;
                         $info['serverInstanceId'] = $server->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID);
                     }
                 } catch (Exception $e) {
                     $this->response->debugException($e);
                 }
                 $storages['devices'][$configKey][] = $info;
             }
         }
         $image = $dbFarmRole->GetRoleObject()->__getNewRoleObject()->getImage($dbFarmRole->Platform, $dbFarmRole->CloudLocation);
         $securityGroups = $this->getInitialSecurityGroupsList($dbFarmRole);
         $farmRoles[] = array('farm_role_id' => $dbFarmRole->ID, 'alias' => $dbFarmRole->Alias ? $dbFarmRole->Alias : $dbFarmRole->GetRoleObject()->name, 'role_id' => $dbFarmRole->RoleID, 'platform' => $dbFarmRole->Platform, 'os' => $dbFarmRole->GetRoleObject()->getOs()->name, 'os_family' => $dbFarmRole->GetRoleObject()->getOs()->family, 'os_generation' => $dbFarmRole->GetRoleObject()->getOs()->generation, 'os_version' => $dbFarmRole->GetRoleObject()->getOs()->version, 'osId' => $dbFarmRole->GetRoleObject()->getOs()->id, 'generation' => $dbFarmRole->GetRoleObject()->generation, 'group' => $dbFarmRole->GetRoleObject()->getCategoryName(), 'cat_id' => $dbFarmRole->GetRoleObject()->catId, 'name' => $roleName, 'is_bundle_running' => $isBundling, 'behaviors' => implode(",", $dbFarmRole->GetRoleObject()->getBehaviors()), 'scripting' => $scriptsObject, 'scripting_params' => $sParams, 'settings' => $dbFarmRole->GetAllSettings(), 'cloud_location' => $dbFarmRole->CloudLocation, 'launch_index' => (int) $dbFarmRole->LaunchIndex, 'scaling' => $scaling, 'config_presets' => $presets, 'image' => $image->getImage(), 'storages' => $storages, 'variables' => $farmRoleVariables->getValues($dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID), 'running_servers' => $dbFarmRole->GetRunningInstancesCount(), 'suspended_servers' => $dbFarmRole->GetSuspendedInstancesCount(), 'security_groups' => $securityGroups, 'hourly_rate' => $this->getInstanceTypeHourlyRate($dbFarmRole->Platform, $dbFarmRole->CloudLocation, $dbFarmRole->getInstanceType(), $dbFarmRole->GetRoleObject()->osFamily));
     }
     $vpc = array();
     if ($dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
         $vpc = array('id' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID), 'region' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_REGION));
     }
     $farmOwnerEditable = $dbFarm->createdByUserId == $this->user->getId() || $this->user->isAccountOwner() || $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_CHANGE_OWNERSHIP);
     return array('farm' => array('name' => $dbFarm->Name, 'description' => $dbFarm->Comments, 'rolesLaunchOrder' => $dbFarm->RolesLaunchOrder, 'timezone' => $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'variables' => $variables->getValues(0, $dbFarm->ID), 'vpc' => $vpc, 'status' => $dbFarm->Status, 'hash' => $dbFarm->Hash, 'owner' => $farmOwnerEditable ? $dbFarm->createdByUserId : $dbFarm->createdByUserEmail, 'ownerEditable' => $farmOwnerEditable, 'teamOwner' => $farmOwnerEditable ? $dbFarm->teamId : ($dbFarm->teamId ? (new Scalr_Account_Team())->loadById($dbFarm->teamId)->name : ''), 'teamOwnerEditable' => $farmOwnerEditable, 'launchPermission' => $this->request->isFarmAllowed($dbFarm, Acl::PERM_FARMS_LAUNCH_TERMINATE), DBFarm::SETTING_SZR_UPD_REPOSITORY => $dbFarm->GetSetting(DBFarm::SETTING_SZR_UPD_REPOSITORY), DBFarm::SETTING_SZR_UPD_SCHEDULE => $dbFarm->GetSetting(DBFarm::SETTING_SZR_UPD_SCHEDULE)), 'roles' => $farmRoles, 'lock' => $dbFarm->isLocked(false), 'changed' => $dbFarm->changedTime);
 }
Beispiel #8
0
 public function getFarm($farmId)
 {
     $dbFarm = DBFarm::LoadByID($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $farmRoleId = $this->getParam('farmRoleId');
     $farmRoles = array();
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         if ($farmRoleId && $farmRoleId != $dbFarmRole->ID) {
             continue;
         }
         $scripts = $this->db->GetAll("SELECT farm_role_scripts.*, scripts.name FROM farm_role_scripts\n\t\t\t\tINNER JOIN scripts ON scripts.id = farm_role_scripts.scriptid\n\t\t\t\tWHERE farm_roleid=? AND issystem='1'", array($dbFarmRole->ID));
         $scriptsObject = array();
         foreach ($scripts as $script) {
             $scriptsObject[] = array('script_id' => $script['scriptid'], 'script' => $script['name'], 'params' => unserialize($script['params']), 'target' => $script['target'], 'version' => $script['version'], 'timeout' => $script['timeout'], 'issync' => $script['issync'], 'order_index' => $script['order_index'], 'event' => $script['event_name']);
         }
         $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
         $scaling = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling[$farmRoleMetric->metricId] = $farmRoleMetric->getSettings();
         }
         $dbPresets = $this->db->GetAll("SELECT * FROM farm_role_service_config_presets WHERE farm_roleid=?", array($dbFarmRole->ID));
         $presets = array();
         foreach ($dbPresets as $preset) {
             $presets[$preset['behavior']] = $preset['preset_id'];
         }
         if ($dbFarmRole->NewRoleID) {
             $roleName = DBRole::loadById($dbFarmRole->NewRoleID)->name;
             $isBundling = true;
         } else {
             $roleName = $dbFarmRole->GetRoleObject()->name;
             $isBundling = false;
         }
         $farmRoles[] = array('farm_role_id' => $dbFarmRole->ID, 'role_id' => $dbFarmRole->RoleID, 'platform' => $dbFarmRole->Platform, 'generation' => $dbFarmRole->GetRoleObject()->generation, 'arch' => $dbFarmRole->GetRoleObject()->architecture, 'group' => ROLE_GROUPS::GetConstByBehavior($dbFarmRole->GetRoleObject()->getBehaviors()), 'name' => $roleName, 'is_bundle_running' => $isBundling, 'behaviors' => implode(",", $dbFarmRole->GetRoleObject()->getBehaviors()), 'scripting' => $scriptsObject, 'settings' => $dbFarmRole->GetAllSettings(), 'cloud_location' => $dbFarmRole->CloudLocation, 'launch_index' => (int) $dbFarmRole->LaunchIndex, 'scaling' => $scaling, 'config_presets' => $presets, 'tags' => $dbFarmRole->GetRoleObject()->getTags());
     }
     return array('farm' => array('name' => $dbFarm->Name, 'description' => $dbFarm->Comments, 'rolesLaunchOrder' => $dbFarm->RolesLauchOrder), 'roles' => $farmRoles);
 }
Beispiel #9
0
 function handleWork($farmId)
 {
     $DBFarm = DBFarm::LoadByID($farmId);
     $GLOBALS["SUB_TRANSACTIONID"] = abs(crc32(posix_getpid() . $farmId));
     $GLOBALS["LOGGER_FARMID"] = $farmId;
     if ($DBFarm->Status != FARM_STATUS::RUNNING) {
         $this->logger->warn("[FarmID: {$DBFarm->ID}] Farm terminated. There is no need to scale it.");
         return;
     }
     foreach ($DBFarm->GetFarmRoles() as $DBFarmRole) {
         for ($i = 0; $i < 10; $i++) {
             if ($DBFarmRole->NewRoleID != '') {
                 $this->logger->warn("[FarmID: {$DBFarm->ID}] Role '{$DBFarmRole->GetRoleObject()->name}' being synchronized. This role will not be scalled.");
                 continue 2;
             }
             if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ENABLED) == '0' && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) {
                 $this->logger->info("[FarmID: {$DBFarm->ID}] Scaling disabled for role '{$DBFarmRole->GetRoleObject()->name}'. Skipping...");
                 continue 2;
             }
             // Get polling interval in seconds
             $polling_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_POLLING_INTERVAL) * 60;
             $dt_last_polling = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_LAST_POLLING_TIME);
             if ($dt_last_polling && $dt_last_polling + $polling_interval > time() && $i == 0) {
                 $this->logger->info("Polling interval: every {$polling_interval} seconds");
                 //continue;
             }
             // Set Last polling time
             $DBFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_LAST_POLLING_TIME, time());
             // Get current count of running and pending instances.
             $this->logger->info(sprintf("Processing role '%s'", $DBFarmRole->GetRoleObject()->name));
             $scalingManager = new Scalr_Scaling_Manager($DBFarmRole);
             $scalingDecision = $scalingManager->makeScalingDecition();
             if ($scalingDecision == Scalr_Scaling_Decision::STOP_SCALING) {
                 return;
             }
             if ($scalingDecision == Scalr_Scaling_Decision::NOOP) {
                 continue 2;
             } elseif ($scalingDecision == Scalr_Scaling_Decision::DOWNSCALE) {
                 /*
                  Timeout instance's count decrease. Decreases instance�s count after scaling 
                  resolution the spare instances are running�g for selected timeout interval
                  from scaling EditOptions							
                 */
                 // We have to check timeout limits before new scaling (downscaling) process will be initiated
                 if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_TIMEOUT_ENABLED)) {
                     // if the farm timeout is exceeded
                     // checking timeout interval.
                     $last_down_scale_data_time = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_DATETIME);
                     $timeout_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_TIMEOUT);
                     // check the time interval to continue scaling or cancel it...
                     if (time() - $last_down_scale_data_time < $timeout_interval * 60) {
                         // if the launch time is too small to terminate smth in this role -> go to the next role in foreach()
                         Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Waiting for downscaling timeout on farm %s, role %s", $DBFarm->Name, $DBFarmRole->GetRoleObject()->name)));
                         continue 2;
                     }
                 }
                 // end Timeout instance's count decrease
                 $sort = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_KEEP_OLDEST) == 1 ? 'DESC' : 'ASC';
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status = ? AND farm_roleid=? ORDER BY dtadded {$sort}", array(SERVER_STATUS::RUNNING, $DBFarmRole->ID));
                 $got_valid_instance = false;
                 // Select instance that will be terminated
                 //
                 // * Instances ordered by uptime (oldest wil be choosen)
                 // * Instance cannot be mysql master
                 // * Choose the one that was rebundled recently
                 while (!$got_valid_instance && count($servers) > 0) {
                     $item = array_shift($servers);
                     $DBServer = DBServer::LoadByID($item['server_id']);
                     if ($DBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                         $serversCount = count($DBServer->GetFarmRoleObject()->GetServersByFilter(array(), array('status' => SERVER_STATUS::TERMINATED)));
                         if ($DBServer->index == 1 && $serversCount > 1) {
                             continue;
                         }
                     }
                     // Exclude db master
                     if ($DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) != 1 && $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER) != 1) {
                         /* 
                          * We do not want to delete the most recently synced instance. Because of LA fluctuation. 
                          * I.e. LA may skyrocket during sync and drop dramatically after sync.
                          */
                         if ($DBServer->dateLastSync != 0) {
                             $chk_sync_time = $this->db->GetOne("SELECT server_id FROM servers \n\t                        \t\tWHERE dtlastsync > {$DBServer->dateLastSync} \n\t\t                        \tAND farm_roleid='{$DBServer->farmRoleId}' AND status != '" . SERVER_STATUS::TERMINATED . "'");
                             if ($chk_sync_time) {
                                 $got_valid_instance = true;
                             }
                         } else {
                             $got_valid_instance = true;
                         }
                     }
                 }
                 if ($DBServer && $got_valid_instance) {
                     $this->logger->info(sprintf("Server '%s' selected for termination...", $DBServer->serverId));
                     $allow_terminate = false;
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $AmazonEC2Client = Scalr_Service_Cloud_Aws::newEc2($DBServer->GetProperty(EC2_SERVER_PROPERTIES::REGION), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::PRIVATE_KEY), $DBServer->GetEnvironmentObject()->getPlatformConfigValue(Modules_Platforms_Ec2::CERTIFICATE));
                         // Shutdown an instance just before a full hour running
                         $response = $AmazonEC2Client->DescribeInstances($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID));
                         if ($response && $response->reservationSet->item) {
                             $launch_time = strtotime($response->reservationSet->item->instancesSet->item->launchTime);
                             $time = 3600 - (time() - $launch_time) % 3600;
                             // Terminate instance in < 10 minutes for full hour.
                             if ($time <= 600) {
                                 $allow_terminate = true;
                             } else {
                                 $timeout = round(($time - 600) / 60, 1);
                                 Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Farm %s, role %s scaling down. Server '%s' will be terminated in %s minutes. Launch time: %s", $DBFarm->Name, $DBServer->GetFarmRoleObject()->GetRoleObject()->name, $DBServer->serverId, $timeout, $response->reservationSet->item->instancesSet->item->launchTime)));
                             }
                         }
                         //
                     } else {
                         $allow_terminate = true;
                     }
                     if ($allow_terminate) {
                         //Check safe shutdown
                         if ($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_SCALING_SAFE_SHUTDOWN) == 1) {
                             $snmpClient = new Scalr_Net_Snmp_Client();
                             $port = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_SNMP_PORT);
                             $snmpClient->connect($DBServer->remoteIp, $port ? $port : 161, $DBFarm->Hash, null, null, false);
                             $res = $snmpClient->get('1.3.6.1.4.1.36632.6.1');
                             if ($res != '1') {
                                 Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Safe shutdown enabled. Server '%s'. Script return '%s', server won't be terminated while return value not '1'", $DBServer->serverId, $res)));
                             }
                         }
                         try {
                             Scalr::FireEvent($DBFarm->ID, new BeforeHostTerminateEvent($DBServer, false));
                             $DBFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_DATETIME, time());
                             Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Farm %s, role %s scaling down. Server '%s' marked as 'Pending terminate' and will be fully terminated in 3 minutes.", $DBFarm->Name, $DBServer->GetFarmRoleObject()->GetRoleObject()->name, $DBServer->serverId)));
                         } catch (Exception $e) {
                             $this->logger->fatal(sprintf("Cannot terminate %s: %s", $DBFarm->ID, $DBServer->serverId, $e->getMessage()));
                         }
                     }
                 } else {
                     $this->logger->warn(sprintf("[FarmID: {$DBFarm->ID}] Scalr unable to determine what instance it should terminate (FarmRoleID: {$DBFarmRole->ID}). Skipping..."));
                 }
                 break;
             } elseif ($scalingDecision == Scalr_Scaling_Decision::UPSCALE) {
                 /*
                 Timeout instance's count increase. Increases  instance's count after 
                 scaling resolution �need more instances� for selected timeout interval
                 from scaling EditOptions						
                 */
                 if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_TIMEOUT_ENABLED)) {
                     // if the farm timeout is exceeded
                     // checking timeout interval.
                     $last_up_scale_data_time = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_DATETIME);
                     $timeout_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_TIMEOUT);
                     // check the time interval to continue scaling or cancel it...
                     if (time() - $last_up_scale_data_time < $timeout_interval * 60) {
                         // if the launch time is too small to terminate smth in this role -> go to the next role in foreach()
                         Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Waiting for upscaling timeout on farm %s, role %s", $DBFarm->Name, $DBFarmRole->GetRoleObject()->name)));
                         continue 2;
                     }
                 }
                 // end Timeout instance's count increase
                 if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ONE_BY_ONE) == 1) {
                     $pendingInstances = $DBFarmRole->GetPendingInstancesCount();
                     if ($pendingInstances > 0) {
                         Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("There are %s pending intances of %s role on % farm. Waiting...", $pendingInstances, $DBFarmRole->GetRoleObject()->name, $DBFarm->Name)));
                         continue 2;
                     }
                 }
                 $fstatus = $this->db->GetOne("SELECT status FROM farms WHERE id=?", array($DBFarm->ID));
                 if ($fstatus != FARM_STATUS::RUNNING) {
                     $this->logger->warn("[FarmID: {$DBFarm->ID}] Farm terminated. There is no need to scale it.");
                     return;
                 }
                 $ServerCreateInfo = new ServerCreateInfo($DBFarmRole->Platform, $DBFarmRole);
                 try {
                     $DBServer = Scalr::LaunchServer($ServerCreateInfo);
                     $DBFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_DATETIME, time());
                     Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Farm %s, role %s scaling up. Starting new instance. ServerID = %s.", $DBFarm->Name, $DBServer->GetFarmRoleObject()->GetRoleObject()->name, $DBServer->serverId)));
                 } catch (Exception $e) {
                     Logger::getLogger(LOG_CATEGORY::SCALING)->error($e->getMessage());
                 }
             }
         }
     }
 }
Beispiel #10
0
 function handleWork($farmId)
 {
     $DBFarm = DBFarm::LoadByID($farmId);
     $GLOBALS["SUB_TRANSACTIONID"] = abs(crc32(posix_getpid() . $farmId));
     $GLOBALS["LOGGER_FARMID"] = $farmId;
     if ($DBFarm->Status != FARM_STATUS::RUNNING) {
         $this->logger->warn("[FarmID: {$DBFarm->ID}] Farm terminated. There is no need to scale it.");
         return;
     }
     foreach ($DBFarm->GetFarmRoles() as $DBFarmRole) {
         for ($i = 0; $i < 10; $i++) {
             if ($DBFarmRole->NewRoleID != '') {
                 $this->logger->warn("[FarmID: {$DBFarm->ID}] Role '{$DBFarmRole->GetRoleObject()->name}' being synchronized. This role will not be scalled.");
                 continue 2;
             }
             if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ENABLED) != '1' && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB) && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ) && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::VPC_ROUTER)) {
                 $this->logger->info("[FarmID: {$DBFarm->ID}] Scaling disabled for role '{$DBFarmRole->GetRoleObject()->name}'. Skipping...");
                 continue 2;
             }
             // Get polling interval in seconds
             $polling_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_POLLING_INTERVAL) * 60;
             $dt_last_polling = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_LAST_POLLING_TIME);
             if ($dt_last_polling && $dt_last_polling + $polling_interval > time() && $i == 0) {
                 $this->logger->info("Polling interval: every {$polling_interval} seconds");
                 continue;
             }
             // Set Last polling time
             $DBFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_LAST_POLLING_TIME, time(), DBFarmRole::TYPE_LCL);
             // Get current count of running and pending instances.
             $this->logger->info(sprintf("Processing role '%s'", $DBFarmRole->GetRoleObject()->name));
             $scalingManager = new Scalr_Scaling_Manager($DBFarmRole);
             $scalingDecision = $scalingManager->makeScalingDecition();
             if ($scalingDecision == Scalr_Scaling_Decision::STOP_SCALING) {
                 return;
             }
             if ($scalingDecision == Scalr_Scaling_Decision::NOOP) {
                 continue 2;
             } elseif ($scalingDecision == Scalr_Scaling_Decision::DOWNSCALE) {
                 /*
                  Timeout instance's count decrease. Decreases instance�s count after scaling
                  resolution the spare instances are running�g for selected timeout interval
                  from scaling EditOptions
                 */
                 // We have to check timeout limits before new scaling (downscaling) process will be initiated
                 if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_TIMEOUT_ENABLED)) {
                     // if the farm timeout is exceeded
                     // checking timeout interval.
                     $last_down_scale_data_time = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_DATETIME);
                     $timeout_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_TIMEOUT);
                     // check the time interval to continue scaling or cancel it...
                     if (time() - $last_down_scale_data_time < $timeout_interval * 60) {
                         // if the launch time is too small to terminate smth in this role -> go to the next role in foreach()
                         Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Waiting for downscaling timeout on farm %s, role %s", $DBFarm->Name, $DBFarmRole->GetRoleObject()->name)));
                         continue 2;
                     }
                 }
                 // end Timeout instance's count decrease
                 $sort = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_KEEP_OLDEST) == 1 ? 'DESC' : 'ASC';
                 $servers = $this->db->GetAll("SELECT server_id FROM servers WHERE status = ? AND farm_roleid=? ORDER BY dtadded {$sort}", array(SERVER_STATUS::RUNNING, $DBFarmRole->ID));
                 $got_valid_instance = false;
                 // Select instance that will be terminated
                 //
                 // * Instances ordered by uptime (oldest wil be choosen)
                 // * Instance cannot be mysql master
                 // * Choose the one that was rebundled recently
                 while (!$got_valid_instance && count($servers) > 0) {
                     $item = array_shift($servers);
                     $DBServer = DBServer::LoadByID($item['server_id']);
                     if ($DBServer->GetFarmRoleObject()->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ)) {
                         $serversCount = count($DBServer->GetFarmRoleObject()->GetServersByFilter(array(), array('status' => array(SERVER_STATUS::TERMINATED, SERVER_STATUS::TROUBLESHOOTING))));
                         if ($DBServer->index == 1 && $serversCount > 1) {
                             continue;
                         }
                     }
                     if ($DBServer->GetProperty(EC2_SERVER_PROPERTIES::IS_LOCKED)) {
                         continue;
                     }
                     // Exclude db master
                     if ($DBServer->GetProperty(SERVER_PROPERTIES::DB_MYSQL_MASTER) != 1 && $DBServer->GetProperty(Scalr_Db_Msr::REPLICATION_MASTER) != 1) {
                         // We do not want to delete the most recently synced instance. Because of LA fluctuation.
                         // I.e. LA may skyrocket during sync and drop dramatically after sync.
                         if ($DBServer->dateLastSync != 0) {
                             $chk_sync_time = $this->db->GetOne("\n                                    SELECT server_id FROM servers\n                                    WHERE dtlastsync > {$DBServer->dateLastSync}\n                                    AND farm_roleid='{$DBServer->farmRoleId}'\n                                    AND status NOT IN('" . SERVER_STATUS::TERMINATED . "', '" . SERVER_STATUS::TROUBLESHOOTING . "')\n                                    LIMIT 1\n                                ");
                             if ($chk_sync_time) {
                                 $got_valid_instance = true;
                             }
                         } else {
                             $got_valid_instance = true;
                         }
                     }
                 }
                 if ($DBServer && $got_valid_instance) {
                     $this->logger->info(sprintf("Server '%s' selected for termination...", $DBServer->serverId));
                     $allow_terminate = false;
                     if ($DBServer->platform == SERVER_PLATFORMS::EC2) {
                         $aws = $DBServer->GetEnvironmentObject()->aws($DBServer);
                         // Shutdown an instance just before a full hour running
                         if (!$DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_SCALING_IGNORE_FULL_HOUR)) {
                             $response = $aws->ec2->instance->describe($DBServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID))->get(0);
                             if ($response && count($response->instancesSet)) {
                                 $launch_time = $response->instancesSet->get(0)->launchTime->getTimestamp();
                                 $time = 3600 - (time() - $launch_time) % 3600;
                                 // Terminate instance in < 10 minutes for full hour.
                                 if ($time <= 600) {
                                     $allow_terminate = true;
                                 } else {
                                     $timeout = round(($time - 600) / 60, 1);
                                     Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Farm %s, role %s scaling down. Server '%s' will be terminated in %s minutes. Launch time: %s", $DBFarm->Name, $DBServer->GetFarmRoleObject()->GetRoleObject()->name, $DBServer->serverId, $timeout, $response->instancesSet->get(0)->launchTime->format('c'))));
                                 }
                             }
                         } else {
                             $allow_terminate = true;
                         }
                         //Releases memory
                         $DBServer->GetEnvironmentObject()->getContainer()->release('aws');
                         unset($aws);
                     } else {
                         $allow_terminate = true;
                     }
                     if ($allow_terminate) {
                         //Check safe shutdown
                         if ($DBServer->GetFarmRoleObject()->GetSetting(DBFarmRole::SETTING_SCALING_SAFE_SHUTDOWN) == 1) {
                             if ($DBServer->IsSupported('0.11.3')) {
                                 try {
                                     $port = $DBServer->GetProperty(SERVER_PROPERTIES::SZR_API_PORT);
                                     if (!$port) {
                                         $port = 8010;
                                     }
                                     $szrClient = Scalr_Net_Scalarizr_Client::getClient($DBServer, Scalr_Net_Scalarizr_Client::NAMESPACE_SYSTEM, $port);
                                     $res = $szrClient->callAuthShutdownHook();
                                 } catch (Exception $e) {
                                     $res = $e->getMessage();
                                 }
                             } else {
                                 Logger::getLogger(LOG_CATEGORY::FARM)->error(new FarmLogMessage($DBFarm->ID, sprintf("Safe shutdown enabled, but not supported by scalarizr installed on server '%s'. Ignoring.", $DBServer->serverId)));
                             }
                             if ($res != '1') {
                                 Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Safe shutdown enabled. Server '%s'. Script returned '%s', server won't be terminated while return value not '1'", $DBServer->serverId, $res)));
                                 break;
                             }
                         }
                         try {
                             $DBServer->terminate('SCALING_DOWN', false);
                             $DBFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_DOWNSCALE_DATETIME, time(), DBFarmRole::TYPE_LCL);
                             Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Farm %s, role %s scaling down. Server '%s' marked as 'Pending terminate' and will be fully terminated in 3 minutes.", $DBFarm->Name, $DBServer->GetFarmRoleObject()->GetRoleObject()->name, $DBServer->serverId)));
                         } catch (Exception $e) {
                             $this->logger->fatal(sprintf("Cannot terminate %s: %s", $DBFarm->ID, $DBServer->serverId, $e->getMessage()));
                         }
                     }
                 } else {
                     $this->logger->warn(sprintf("[FarmID: %s] Scalr unable to determine what instance it should terminate (FarmRoleID: %s). Skipping...", $DBFarm->ID, $DBFarmRole->ID));
                 }
                 break;
             } elseif ($scalingDecision == Scalr_Scaling_Decision::UPSCALE) {
                 /*
                 Timeout instance's count increase. Increases  instance's count after
                 scaling resolution �need more instances� for selected timeout interval
                 from scaling EditOptions
                 */
                 if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_TIMEOUT_ENABLED)) {
                     // if the farm timeout is exceeded
                     // checking timeout interval.
                     $last_up_scale_data_time = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_DATETIME);
                     $timeout_interval = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_TIMEOUT);
                     // check the time interval to continue scaling or cancel it...
                     if (time() - $last_up_scale_data_time < $timeout_interval * 60) {
                         // if the launch time is too small to terminate smth in this role -> go to the next role in foreach()
                         Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("Waiting for upscaling timeout on farm %s, role %s", $DBFarm->Name, $DBFarmRole->GetRoleObject()->name)));
                         continue 2;
                     }
                 }
                 // end Timeout instance's count increase
                 //Check DBMsr. Do not start slave during slave2master process
                 $isDbMsr = $DBFarmRole->GetRoleObject()->getDbMsrBehavior();
                 if ($isDbMsr) {
                     if ($DBFarmRole->GetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER)) {
                         $runningServers = $DBFarmRole->GetRunningInstancesCount();
                         if ($runningServers > 0) {
                             Logger::getLogger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($DBFarm->ID, sprintf("Role is in slave2master promotion process. Do not launch new slaves while there is no active slaves")));
                             continue 2;
                         } else {
                             $DBFarmRole->SetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER, 0, DBFarmRole::TYPE_LCL);
                         }
                     }
                 }
                 if ($DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_ONE_BY_ONE) == 1) {
                     $pendingInstances = $DBFarmRole->GetPendingInstancesCount();
                     if ($pendingInstances > 0) {
                         Logger::getLogger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBFarm->ID, sprintf("There are %s pending intances of %s role on % farm. Waiting...", $pendingInstances, $DBFarmRole->GetRoleObject()->name, $DBFarm->Name)));
                         continue 2;
                     }
                 }
                 $fstatus = $this->db->GetOne("SELECT status FROM farms WHERE id=? LIMIT 1", array($DBFarm->ID));
                 if ($fstatus != FARM_STATUS::RUNNING) {
                     $this->logger->warn("[FarmID: {$DBFarm->ID}] Farm terminated. There is no need to scale it.");
                     return;
                 }
                 $ServerCreateInfo = new ServerCreateInfo($DBFarmRole->Platform, $DBFarmRole);
                 try {
                     $DBServer = Scalr::LaunchServer($ServerCreateInfo, null, false, "Scaling up");
                     $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, $DBServer->GetFarmRoleObject()->GetRoleObject()->name, $DBServer->serverId)));
                 } catch (Exception $e) {
                     Logger::getLogger(LOG_CATEGORY::SCALING)->error($e->getMessage());
                 }
             }
         }
     }
 }
Beispiel #11
0
 public function getFarm2($farmId)
 {
     $dbFarm = DBFarm::LoadByID($farmId);
     $this->user->getPermissions()->validate($dbFarm);
     $farmRoleId = $this->getParam('farmRoleId');
     $farmRoles = array();
     $variables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARM);
     $farmRoleVariables = new Scalr_Scripting_GlobalVariables($this->getEnvironmentId(), Scalr_Scripting_GlobalVariables::SCOPE_FARMROLE);
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         if ($farmRoleId && $farmRoleId != $dbFarmRole->ID) {
             continue;
         }
         $scripts = $this->db->GetAll("\n                SELECT farm_role_scripts.*, scripts.name\n                FROM farm_role_scripts\n                LEFT JOIN scripts ON scripts.id = farm_role_scripts.scriptid\n                WHERE farm_roleid=? AND issystem='1'\n            ", array($dbFarmRole->ID));
         $scriptsObject = array();
         foreach ($scripts as $script) {
             if (!empty($script['scriptid']) || !empty($script['script_path'])) {
                 $s = array('script_id' => $script['scriptid'], 'script' => $script['name'], 'params' => unserialize($script['params']), 'target' => $script['target'], 'version' => $script['version'], 'timeout' => $script['timeout'], 'issync' => $script['issync'], 'order_index' => $script['order_index'], 'event' => $script['event_name'], 'script_path' => $script['script_path'], 'run_as' => $script['run_as']);
             }
             if ($script['target'] == Scalr_Script::TARGET_BEHAVIORS || $script['target'] == Scalr_Script::TARGET_ROLES) {
                 $varName = $script['target'] == Scalr_Script::TARGET_ROLES ? 'target_roles' : 'target_behaviors';
                 $s[$varName] = array();
                 $r = $this->db->GetAll("SELECT `target` FROM farm_role_scripting_targets WHERE farm_role_script_id = ?", array($script['id']));
                 foreach ($r as $v) {
                     array_push($s[$varName], $v['target']);
                 }
             }
             $scriptsObject[] = $s;
         }
         //Scripting params
         $scriptingParams = $this->db->Execute("\n                SELECT * FROM farm_role_scripting_params\n                WHERE farm_role_id = ? AND farm_role_script_id = '0'\n            ", array($dbFarmRole->ID));
         $sParams = array();
         while ($p = $scriptingParams->FetchRow()) {
             $sParams[] = array('hash' => $p['hash'], 'role_script_id' => $p['role_script_id'], 'params' => unserialize($p['params']));
         }
         $scalingManager = new Scalr_Scaling_Manager($dbFarmRole);
         $scaling = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling[$farmRoleMetric->metricId] = $farmRoleMetric->getSettings();
         }
         $dbPresets = $this->db->GetAll("SELECT * FROM farm_role_service_config_presets WHERE farm_roleid=?", array($dbFarmRole->ID));
         $presets = array();
         foreach ($dbPresets as $preset) {
             $presets[$preset['behavior']] = $preset['preset_id'];
         }
         if ($dbFarmRole->NewRoleID) {
             $roleName = DBRole::loadById($dbFarmRole->NewRoleID)->name;
             $isBundling = true;
         } else {
             $roleName = $dbFarmRole->GetRoleObject()->name;
             $isBundling = false;
         }
         $imageDetails = $dbFarmRole->GetRoleObject()->getImageDetails($dbFarmRole->Platform, $dbFarmRole->CloudLocation);
         $storages = array('configs' => $dbFarmRole->getStorage()->getConfigs());
         foreach ($dbFarmRole->getStorage()->getVolumes() as $configKey => $config) {
             $storages['devices'][$configKey] = array();
             foreach ($config as $device) {
                 $info = array('farmRoleId' => $device->farmRoleId, 'placement' => $device->placement, 'serverIndex' => $device->serverIndex, 'storageId' => $device->storageId, 'storageConfigId' => $device->storageConfigId, 'status' => $device->status);
                 try {
                     $server = DBServer::LoadByFarmRoleIDAndIndex($device->farmRoleId, $device->serverIndex);
                     if ($server->status != SERVER_STATUS::TERMINATED && $server->status != SERVER_STATUS::TROUBLESHOOTING) {
                         $info['serverId'] = $server->serverId;
                         $info['serverInstanceId'] = $server->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID);
                     }
                 } catch (Exception $e) {
                     $this->response->varDump($e->getMessage());
                     $this->response->varDump($e->getTraceAsString());
                 }
                 $storages['devices'][$configKey][] = $info;
             }
         }
         $imageInfo = $dbFarmRole->GetRoleObject()->getImageDetails($dbFarmRole->Platform, $dbFarmRole->CloudLocation);
         $architecture = $imageInfo['architecture'];
         $securityGroups = $this->getInitialSecurityGroupsList($dbFarmRole);
         $farmRoles[] = array('farm_role_id' => $dbFarmRole->ID, 'alias' => $dbFarmRole->Alias ? $dbFarmRole->Alias : $dbFarmRole->GetRoleObject()->name, 'role_id' => $dbFarmRole->RoleID, 'platform' => $dbFarmRole->Platform, 'os' => $dbFarmRole->GetRoleObject()->os, 'os_family' => $dbFarmRole->GetRoleObject()->osFamily, 'os_generation' => $dbFarmRole->GetRoleObject()->osGeneration, 'os_version' => $dbFarmRole->GetRoleObject()->osVersion, 'generation' => $dbFarmRole->GetRoleObject()->generation, 'group' => $dbFarmRole->GetRoleObject()->getCategoryName(), 'cat_id' => $dbFarmRole->GetRoleObject()->catId, 'arch' => $architecture, 'name' => $roleName, 'is_bundle_running' => $isBundling, 'behaviors' => implode(",", $dbFarmRole->GetRoleObject()->getBehaviors()), 'scripting' => $scriptsObject, 'scripting_params' => $sParams, 'settings' => $dbFarmRole->GetAllSettings(), 'cloud_location' => $dbFarmRole->CloudLocation, 'launch_index' => (int) $dbFarmRole->LaunchIndex, 'scaling' => $scaling, 'config_presets' => $presets, 'tags' => $dbFarmRole->GetRoleObject()->getTags(), 'storages' => $storages, 'variables' => $farmRoleVariables->getValues($dbFarmRole->GetRoleID(), $dbFarm->ID, $dbFarmRole->ID), 'running_servers' => $dbFarmRole->GetRunningInstancesCount(), 'security_groups' => $securityGroups);
     }
     $vpc = array();
     if ($dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
         $vpc = array('id' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID), 'region' => $dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_REGION));
     }
     return array('farm' => array('name' => $dbFarm->Name, 'description' => $dbFarm->Comments, 'rolesLaunchOrder' => $dbFarm->RolesLaunchOrder, 'timezone' => $dbFarm->GetSetting(DBFarm::SETTING_TIMEZONE), 'variables' => $variables->getValues(0, $dbFarm->ID), 'vpc' => $vpc, 'status' => $dbFarm->Status), 'roles' => $farmRoles, 'lock' => $dbFarm->isLocked(false), 'changed' => $dbFarm->changedTime);
 }
Beispiel #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());
                 }
             }
         }
     }
 }
 /**
  * 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));
     $roles = $DBFarm->GetFarmRoles();
     foreach ($roles as $dbFarmRole) {
         $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);
                 $dbFarmRole->SetSetting(DBFarmRole::SETTING_SCALING_UPSCALE_DATETIME, time());
                 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());
             }
         }
     }
 }
Beispiel #14
0
 public function xListFarmRolesAction()
 {
     $this->request->defineParams(array('farmId' => array('type' => 'int'), 'farmRoleId' => array('type' => 'int'), 'roleId' => array('type' => 'int'), 'id' => array('type' => 'int'), 'sort' => array('type' => 'json')));
     $allFarms = $this->request->isAllowed(Acl::RESOURCE_FARMS, Acl::PERM_FARMS_NOT_OWNED_FARMS);
     $sql = "\n            SELECT farm_roles.*\n            FROM farm_roles\n            JOIN roles ON farm_roles.role_id = roles.id\n            WHERE farmid = ?\n            AND :FILTER:\n        ";
     $params = array($this->getParam('farmId'));
     if (!$allFarms) {
         $sql .= " AND `farmid` IN (SELECT id FROM `farms` WHERE env_id = " . intval($this->getEnvironmentId()) . " AND created_by_id = " . intval($this->user->getId()) . ") ";
     }
     if ($this->getParam('roleId')) {
         $sql .= ' AND role_id = ?';
         $params[] = $this->getParam('roleId');
     }
     if ($this->getParam('farmRoleId')) {
         $sql .= ' AND farm_roles.id = ?';
         $params[] = $this->getParam('farmRoleId');
     }
     $response = $this->buildResponseFromSql($sql, array('platform', 'name', 'alias'), array('name'), $params);
     foreach ($response['data'] as &$row) {
         $row["running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid='{$row['id']}' AND status IN ('Pending', 'Initializing', 'Running', 'Temporary')");
         $row["non_running_servers"] = $this->db->GetOne("SELECT COUNT(*) FROM servers WHERE farm_roleid='{$row['id']}' AND status NOT IN ('Pending', 'Initializing', 'Running', 'Temporary')");
         $row['farm_status'] = $this->db->GetOne("SELECT status FROM farms WHERE id=? LIMIT 1", array($row['farmid']));
         $row["domains"] = $this->db->GetOne("SELECT COUNT(*) FROM dns_zones WHERE farm_roleid=? AND status != ? AND farm_id=?", array($row["id"], DNS_ZONE_STATUS::PENDING_DELETE, $row['farmid']));
         $DBFarmRole = DBFarmRole::LoadByID($row['id']);
         $row['min_count'] = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MIN_INSTANCES);
         $row['max_count'] = $DBFarmRole->GetSetting(DBFarmRole::SETTING_SCALING_MAX_INSTANCES);
         $row['allow_launch_instance'] = !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB) && !$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::CF_CLOUD_CONTROLLER);
         $vpcId = $this->environment->getPlatformConfigValue(Modules_Platforms_Ec2::DEFAULT_VPC_ID . ".{$DBFarmRole->CloudLocation}");
         $row['is_vpc'] = $vpcId || $DBFarmRole->GetFarmObject()->GetSetting(DBFarm::SETTING_EC2_VPC_ID) ? true : false;
         $row['location'] = $DBFarmRole->CloudLocation;
         $DBRole = DBRole::loadById($row['role_id']);
         $row["name"] = $DBRole->name;
         $row['image_id'] = $DBRole->getImageId($DBFarmRole->Platform, $DBFarmRole->CloudLocation);
         $row['shortcuts'] = $this->db->GetAll("SELECT * FROM farm_role_scripts WHERE farm_roleid=? AND ismenuitem='1'", array($row['id']));
         foreach ($row['shortcuts'] as &$shortcut) {
             $shortcut['name'] = $this->db->GetOne("SELECT name FROM scripts WHERE id=? LIMIT 1", array($shortcut['scriptid']));
         }
         $scalingManager = new Scalr_Scaling_Manager($DBFarmRole);
         $scaling_algos = array();
         foreach ($scalingManager->getFarmRoleMetrics() as $farmRoleMetric) {
             $scaling_algos[] = $farmRoleMetric->getMetric()->name;
         }
         if (count($scaling_algos) == 0) {
             $row['scaling_algos'] = _("Scaling disabled");
         } else {
             $row['scaling_algos'] = implode(', ', $scaling_algos);
         }
     }
     $this->response->data($response);
 }