function enqueueWork($workQueue) { $this->logger->info("Fetching farms..."); $farms = array(); $envs = $this->db->GetAll('SELECT env_id, value FROM governance WHERE enabled = 1 AND name = ?', array(Scalr_Governance::GENERAL_LEASE)); foreach ($envs as $env) { $env['value'] = json_decode($env['value'], true); $period = 0; if (is_array($env['value']['notifications'])) { foreach ($env['value']['notifications'] as $notif) { if ($notif['period'] > $period) { $period = $notif['period']; } } $dt = new DateTime(); $dt->sub(new DateInterval('P' . $period . 'D')); $fs = $this->db->GetAll('SELECT farmid, status FROM farm_settings LEFT JOIN farms ON farms.id = farm_settings.farmid WHERE farm_settings.name = ? AND status = ? AND env_id = ? AND value > ?', array(DBFarm::SETTING_LEASE_TERMINATE_DATE, FARM_STATUS::RUNNING, $env['env_id'], $dt->format('Y-m-d H:i:s'))); foreach ($fs as $f) { if (!isset($farms[$f['farmid']])) { $farms[$f['farmid']] = true; $workQueue->put($f['farmid']); } } } } $this->logger->info("Found " . count($farms) . " lease tasks"); }
function handleWork($msgId) { $message = $this->db->GetRow("SELECT server_id, message, id, handle_attempts FROM messages WHERE id=?", array($msgId)); try { if ($message['handle_attempts'] >= 3) { $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); } else { try { $DBServer = DBServer::LoadByID($message['server_id']); } catch (Exception $e) { $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); return; } if ($DBServer->status == SERVER_STATUS::RUNNING || $DBServer->status == SERVER_STATUS::INIT || $DBServer->status == SERVER_STATUS::IMPORTING || $DBServer->status == SERVER_STATUS::TEMPORARY || $DBServer->status == SERVER_STATUS::PENDING_TERMINATE) { $msg = $this->messageSerializer->unserialize($message['message']); $msg->dbMessageId = $message['id']; $DBServer->SendMessage($msg); } elseif (in_array($DBServer->status, array(SERVER_STATUS::TROUBLESHOOTING, SERVER_STATUS::TERMINATED, SERVER_STATUS::SUSPENDED))) { $this->db->Execute("UPDATE messages SET status=? WHERE id=?", array(MESSAGE_STATUS::FAILED, $message['id'])); } } } catch (Exception $e) { //var_dump($e->getMessage()); } }
/** * Gets MongoDb Collection * * @return ADOConnection Returns the instance of the ADOConnection */ protected function getDb() { if ($this->db === null) { $this->db = NewADOConnection($this->options['dsn']); $this->db->SetFetchMode(ADODB_FETCH_ASSOC); } return $this->db; }
function enqueueWork($workQueue) { $rows = $this->db->GetAll("SELECT id FROM farm_roles WHERE role_id IN (SELECT role_id FROM role_behaviors WHERE behavior IN (?,?,?,?))", array(ROLE_BEHAVIORS::POSTGRESQL, ROLE_BEHAVIORS::REDIS, ROLE_BEHAVIORS::MYSQL2, ROLE_BEHAVIORS::PERCONA)); $this->logger->info("Found " . count($rows) . " DbMsr farm roles..."); foreach ($rows as $row) { $workQueue->put($row["id"]); } }
function enqueueWork($workQueue) { $this->logger->info("Fetching active farms..."); $rows = $this->db->GetAll("SELECT id FROM dm_deployment_tasks WHERE status IN ('pending','deploying')"); $this->logger->info("Found " . count($rows) . " deployment tasks"); foreach ($rows as $row) { $workQueue->put($row["id"]); } }
/** * Gets all active financial admins * * @return array Returns all financial admins array(Scalr_Account_User) */ public function getFinancialAdmins() { $rs = $this->db->Execute("SELECT id FROM account_users WHERE type = ? AND status = ?", [\Scalr_Account_User::TYPE_FIN_ADMIN, \Scalr_Account_User::STATUS_ACTIVE]); $result = []; while ($row = $rs->FetchRow()) { $user = \Scalr_Account_User::init()->loadById($row['id']); $result[$user->id] = $user; } return $result; }
public function cancelLastRequest() { $last = $this->getLastRequest(); if ($last && $last['status'] == self::STATUS_PENDING) { $this->db->Execute('UPDATE farm_lease_requests SET status = ? WHERE id = ?', array(self::STATUS_CANCEL, $last['id'])); return true; } else { return false; } }
public static function takeCredits(\PDO $pdo_db, \ADODB_mysqli $db, array $langvars, int $planet_id) { // Get basic Database information (ship and planet) $res = $db->Execute("SELECT * FROM {$db->prefix}ships WHERE email = ?;", array($_SESSION['username'])); \Tki\Db::LogDbErrors($pdo_db, $res, __LINE__, __FILE__); $playerinfo = $res->fields; $res = $db->Execute("SELECT * FROM {$db->prefix}planets WHERE planet_id = ?;", array($planet_id)); \Tki\Db::LogDbErrors($pdo_db, $res, __LINE__, __FILE__); $planetinfo = $res->fields; // Set the name for unamed planets to be "unnamed" if (empty($planetinfo['name'])) { $planetinfo['name'] = $langvars['l_unnamed']; } // Verify player is still in same sector as the planet if ($playerinfo['sector'] == $planetinfo['sector_id']) { if ($playerinfo['turns'] >= 1) { // Verify player owns the planet to take credits from if ($planetinfo['owner'] == $playerinfo['ship_id']) { // Get number of credits from the planet and current number player has on ship $CreditsTaken = $planetinfo['credits']; $CreditsOnShip = $playerinfo['credits']; $NewShipCredits = $CreditsTaken + $CreditsOnShip; // Update the planet record for credits $res = $db->Execute("UPDATE {$db->prefix}planets SET credits = 0 WHERE planet_id = ?;", array($planetinfo['planet_id'])); \Tki\Db::LogDbErrors($pdo_db, $res, __LINE__, __FILE__); // update the player info with updated credits $res = $db->Execute("UPDATE {$db->prefix}ships SET credits = ? WHERE email = ?;", array($NewShipCredits, $_SESSION['username'])); \Tki\Db::LogDbErrors($pdo_db, $res, __LINE__, __FILE__); // update the player info with updated turns $res = $db->Execute("UPDATE {$db->prefix}ships SET turns = turns - 1 WHERE email = ?;", array($_SESSION['username'])); \Tki\Db::LogDbErrors($pdo_db, $res, __LINE__, __FILE__); $tempa1 = str_replace("[credits_taken]", number_format($CreditsTaken, 0, $langvars['local_number_dec_point'], $langvars['local_number_thousands_sep']), $langvars['l_pr_took_credits']); $tempa2 = str_replace("[planet_name]", $planetinfo['name'], $tempa1); echo $tempa2 . "<br>"; $tempb1 = str_replace("[ship_name]", $playerinfo['ship_name'], $langvars['l_pr_have_credits_onboard']); $tempb2 = str_replace("[new_ship_credits]", number_format($NewShipCredits, 0, $langvars['local_number_dec_point'], $langvars['local_number_thousands_sep']), $tempb1); echo $tempb2 . "<br>"; $retval = "GO"; } else { echo "<br><br>" . str_replace("[planet_name]", $planetinfo['name'], $langvars['l_pr_not_your_planet']) . "<br><br>"; $retval = "BREAK-INVALID"; } } else { $tempc1 = str_replace("[planet_name]", $planetinfo['name'], $langvars['l_pr_not_enough_turns']); $tempc2 = str_replace("[sector_id]", $planetinfo['sector_id'], $tempc1); echo "<br><br>" . $tempc2 . "<br><br>"; $retval = "BREAK-TURNS"; } } else { echo "<br><br>" . $langvars['l_pr_must_same_sector'] . "<br><br>"; $retval = "BREAK-SECTORS"; } return $retval; }
function handle($queue, Scalr_Messaging_Msg $message, $rawMessage, $type = 'xml') { $this->logger->info(sprintf("Received message '%s' from server '%s'", $message->getName(), $message->getServerId())); try { $this->db->Execute("INSERT INTO messages SET\n messageid = ?,\n message = ?,\n server_id = ?,\n dtadded = NOW(),\n type = ?,\n ipaddress = ?,\n message_name = ?,\n message_format = ?\n ", array($message->messageId, $rawMessage, $message->getServerId(), "in", $_SERVER['REMOTE_ADDR'], $message->getName(), $type)); } catch (Exception $e) { // Message may be already delivered. // urlopen issue on scalarizr side: // QueryEnvError: <urlopen error [Errno 4] Interrupted system call> if (strpos($e->getMessage(), 'Duplicate entry') === false) { throw $e; } } }
/** * Gets event list * * @param \DateTime $start Start date of the period * @param \DateTime $end End date of the period * @param array $criteria optional Filter array ['filterId' => 'value'] * @return ArrayCollection Returns collection of the TimelineEventEntity objects */ public function get($start, $end, array $criteria = null) { $eventEntity = new TimelineEventEntity(); $joinData = $this->buildJoin($criteria); $and = ''; if (!empty($criteria['envId'])) { $and = 'AND e.env_id =' . $criteria['envId']; } else { if (!empty($criteria['accountId'])) { $and = 'AND e.account_id =' . $criteria['accountId']; } } $fields = ''; foreach ($eventEntity->getIterator()->fields() as $field) { $fields .= ',`' . $field->column->name . '`'; } $result = $this->db->Execute("\n SELECT " . ltrim($fields, ',') . "\n FROM (\n SELECT " . $eventEntity->fields('e') . "\n FROM " . $eventEntity->table('e') . (isset($joinData['join']) ? $joinData['join'] : '') . "\n WHERE e.dtime BETWEEN " . $eventEntity->qstr('dtime', $start) . " AND " . $eventEntity->qstr('dtime', $end) . " " . $and . "\n " . (isset($joinData['join']) ? "\n UNION\n SELECT " . $eventEntity->fields('e2') . "\n FROM " . $eventEntity->table('e2') . "\n WHERE e2.event_type = " . $eventEntity::EVENT_TYPE_CHANGE_CLOUD_PRICING . "\n AND e2.dtime BETWEEN " . $eventEntity->qstr('dtime', $start) . " AND " . $eventEntity->qstr('dtime', $end) : "") . "\n ) p\n ORDER BY p.dtime DESC\n "); $events = new ArrayCollection(); while ($record = $result->FetchRow()) { $item = new TimelineEventEntity(); $item->load($record); $events->append($item); } return $events; }
/** * Fetches statuses of the previous updates */ private function fetchStatusBefore() { $this->stateBefore = new \ArrayObject(); //Loads performed updates of MYSQL type $rs = $this->db->Execute("\n SELECT LOWER(HEX(u.`uuid`)) `uuid`, u.`released`, u.`appears`, u.`applied`, u.`status`, LOWER(HEX(u.`hash`)) `hash`\n FROM `" . self::DB_TABLE_UPGRADES . "` u\n "); while ($rec = $rs->FetchRow()) { $entity = new MysqlUpgradeEntity(); $entity->load($rec); $this->stateBefore[$rec['uuid']] = $entity; if (isset($entity->appears) && $this->maxDate < $entity->appears) { $this->maxDate = $entity->appears; } } //Loads updates of FileSystem type self::checkFilesystemStorage(); //Loads performed updates of Filesystem type foreach (new FilesystemStorageIterator(self::FS_STORAGE_PATH) as $fileInfo) { /* @var $fileInfo \SplFileInfo */ if (!$fileInfo->isReadable()) { throw new Exception\UpgradeException(sprintf('Could not read from file "%s". Lack of access permissions.', $fileInfo->getFilename())); } $entity = new FilesystemUpgradeEntity(); $obj = unserialize(file_get_contents($fileInfo->getPathname())); if (!is_object($obj)) { throw new Exception\UpgradeException(sprintf('There was error while trying to load record from filesystem storage "%s". Object is expected, %s given', $fileInfo->getPathname(), gettype($obj))); } $entity->load($obj); $this->stateBefore[$entity->uuid] = $entity; if (isset($entity->appears) && $this->maxDate < $entity->appears) { $this->maxDate = $entity->appears; } unset($obj); } }
/** * Gets available projects for account scope * * @param int $accountId Current user object * @param string $query optional Search criteria * @return \Scalr\Model\Collections\ArrayCollection */ public function getAccountProjects($accountId, $query = null) { $collection = $this->findByKey($query, ['accountId' => $accountId], true); //Select identifiers of all projects assigned to farms from the account $assignedProjects = []; $rs = $this->db->Execute("\n SELECT DISTINCT fs.value\n FROM farms f\n JOIN farm_settings fs ON f.id = fs.farmid\n WHERE fs.name = ?\n AND f.clientid = ?\n ", [Entity\FarmSetting::PROJECT_ID, $accountId]); while ($rec = $rs->fetchRow()) { $assignedProjects[$rec['value']] = true; } //Adjusts missing projects. //This is going to be very rare event. foreach ($collection as $projectEntity) { if (isset($assignedProjects[$projectEntity->projectId])) { unset($assignedProjects[$projectEntity->projectId]); } } foreach ($assignedProjects as $projectId => $v) { $project = ProjectEntity::findPk($projectId); /* @var $project ProjectEntity */ $projectBillingCode = $project->getProperty(ProjectPropertyEntity::NAME_BILLING_CODE); if (empty($query) || (stripos($project->name, $query) !== false || stripos($projectBillingCode, $query) !== false)) { $collection->append($project); } } return $collection; }
/** * Synchronizes the account level tag value * * It does not verify itself whether the cost analytics service is enabled * * @param int $accountId The identifier of the client's account * @param int $tagId The identifier of the clould analytics tag * @param string $valueId The identifier of the tag's value * @param string $valueName The name of the tag's value */ public function syncValue($accountId, $tagId, $valueId, $valueName) { if ($accountId === null) { $accountId = 0; } $tag = AccountTagEntity::findPk($accountId, $tagId, $valueId); if (!$tag instanceof AccountTagEntity) { $tag = new AccountTagEntity(); $tag->accountId = $accountId; $tag->tagId = $tagId; $tag->valueId = $valueId; $tag->valueName = $valueName; } else { if ($tag->valueName != $valueName) { $tag->valueName = $valueName; if ($tagId == TagEntity::TAG_ID_FARM) { foreach ($this->db->GetAll("\n SELECT fr.id AS farm_role_id, fr.alias\n FROM farm_roles fr\n WHERE fr.farmid = ?\n ", [$valueId]) as $v) { //Updates all related farm roles $this->syncValue($accountId, TagEntity::TAG_ID_FARM_ROLE, $v['farm_role_id'], sprintf('%s', $v['alias'])); } } } else { $ignoreupdate = true; } } if (!isset($ignoreupdate)) { $tag->save(); } }
/** * @param Scalr_Service_ZohoCrm_Entity_SalesOrder $salesOrder * @param Client $client * @param int $invoiceId */ private function bindSalesOrder($salesOrder, $client, $invoiceId) { $invoice = $this->db->GetRow("SELECT * FROM payments WHERE id = ?", array($invoiceId)); $packageId = $client->GetSettingValue(CLIENT_SETTINGS::BILLING_PACKAGE); $package = $this->db->GetRow("SELECT * FROM billing_packages WHERE id = ?", array($packageId)); $salesOrder->accountId = $client->GetSettingValue(CLIENT_SETTINGS::ZOHOCRM_ACCOUNT_ID); $salesOrder->subject = sprintf('Monthly fee $%s (%s)', $invoice["amount"], date("F y", strtotime($invoice["dtpaid"]))); $salesOrder->discount = 0; $salesOrder->tax = 0; $salesOrder->subTotal = $package["cost"]; $salesOrder->grandTotal = $package["cost"]; $salesOrder->status = "Delivered"; $salesOrder->setProperty(Scalr_Integration_ZohoCrm_CustomFields::PAYMENT_SUBSCRIPTION_ID, $invoice["subscriptionid"]); // Add product $productDetail = new Scalr_Service_ZohoCrm_Entity_ProductDetail(); $productDetail->productId = Scalr_Integration_ZohoCrm_CustomFields::$BILLING_PACKAGE_PRODUCT_ID_MAP[$packageId]; $productDetail->quantity = 1; $productDetail->listPrice = $package["cost"]; $productDetail->discount = 0; $productDetail->tax = 0; $productDetail->total = $package["cost"]; $productDetail->totalAfterDiscount = $package["cost"]; $productDetail->netTotal = $package["cost"]; $salesOrder->addProductDetail($productDetail); }
/** * Saves an entity to database * * @return \Scalr\Server\History * @throws Exception */ public function save() { $stmt = array(); $bind = array(); $idKey = 'id'; $idValue = array(); $cols = array(); foreach ($this->_getFields() as $field) { $cols[$field] = $this->{$field}; } if (array_key_exists($idKey, $cols)) { if ($cols[$idKey]) { $idValue[] = $cols[$idKey]; } unset($cols[$idKey]); } foreach ($cols as $field => $value) { $stmt[] = "`" . Scalr::decamelize($field) . "` = ?"; $bind[] = $value; } try { $stmt = (empty($idValue) ? "INSERT" : "UPDATE") . " `servers_history` SET " . join(", ", $stmt) . (!empty($idValue) ? " WHERE `" . Scalr::decamelize($idKey) . "` = ?" : ""); $this->db->Execute($stmt, array_merge($bind, $idValue)); if (empty($idValue)) { $this->{$idKey} = $this->db->Insert_ID(); } } catch (Exception $e) { throw new Exception(sprintf("Cannot save server history record. Error: %s", $e->getMessage()), $e->getCode()); } return $this; }
/** * Checks whether current connection is alive * * @param ADODB_mysqli $conn * @return bool Returns true on success or false otherwise */ private static function isConnectionAlive($conn) { $alive = true; if (!empty($conn->_connectionID) && method_exists($conn->_connectionID, 'ping')) { $alive = (bool) @$conn->_connectionID->ping(); } else { try { $conn->GetOne('SELECT 1'); } catch (\ADODB_Exception $e) { if (stristr($e->getMessage(), 'has gone away') !== false) { $alive = false; } } } return $alive; }
/** * @param int $cID * @param int $cvID */ public function inspectCollection($cID, $cvID) { $this->write("Collection {$cID} @ version {$cvID}"); ++$this->indent; $cID = (int) $cID; $cvID = (int) $cvID; $c = $this->cn->GetRow(' select CollectionVersions.cvName, CollectionVersions.cvHandle, CollectionVersions.cvComments, CollectionVersions.cvIsApproved, PagePaths.cPath from CollectionVersions left join PagePaths on CollectionVersions.cID = PagePaths.cID where CollectionVersions.cID = ? and CollectionVersions.cvID = ? order by PagePaths.ppIsCanonical desc ', array($cID, $cvID)); if (empty($c)) { $this->write("COLLECTION VERSION {$cvID} NOT FOUND FOR COLLECTION {$cID}!"); } else { $this->write('Name : ' . (string) $c['cvName']); $this->write('Handle : ' . (string) $c['cvHandle']); $this->write('Approved: ' . ($c['cvIsApproved'] ? 'yes' : 'no')); $this->write('Path : ' . (string) $c['cPath']); $this->write('comments: ' . (string) $c['cvComments']); } --$this->indent; }
public function save() { if ($this->exists) { $this->db->Execute("UPDATE farm_role_cloud_services SET\n `farm_id` = ?,\n `farm_role_id` = ?,\n `platform` = ?,\n `cloud_location` = ?\n WHERE `id` = ?\n ", array($this->farmId, $this->farmRoleId, $this->platform, $this->cloudLocation, $this->serviceId)); } else { $this->db->Execute("INSERT INTO farm_role_cloud_services SET\n `id` = ?,\n `type` = ?,\n `env_id` = ?,\n `farm_id` = ?,\n `farm_role_id` = ?,\n `platform` = ?,\n `cloud_location` = ?\n ", array($this->serviceId, $this->type, $this->envId, $this->farmId, $this->farmRoleId, $this->platform, $this->cloudLocation)); } }
protected function LogRequest($trans_id, $action, $ipaddr, $request, $response) { if ($request['debug'] == 1 || $request['Debug'] == 1 || $request['Action'] == 'DNSZoneRecordAdd') { try { $this->DB->Execute("INSERT INTO api_log SET\n transaction_id\t= ?,\n dtadded\t\t\t= ?,\n action\t\t\t= ?,\n ipaddress\t\t= ?,\n request\t\t\t= ?,\n response\t\t= ?,\n clientid\t\t= ?,\n env_id\t\t\t= ?\n ", array($trans_id, time(), $action, $ipaddr, http_build_query($request), $response, $this->user->getAccountId(), $this->Environment->id)); } catch (Exception $e) { } } }
public function delete($id = null) { $id = !is_null($id) ? $id : $this->id; try { $this->db->Execute("DELETE FROM {$this->dbTableName} WHERE id=?", array($id)); } catch (Exception $e) { throw new Exception(sprintf(_("Cannot delete record. Error: %s"), $e->getMessage()), $e->getCode()); } }
/** * Get the list of the farms which are assigned to specified project * * @param string $projectId The UUID of the project * @return array Returns the array looks like [farm_id => name] */ public function getFarmsList($projectId) { $ret = []; $res = $this->db->Execute("\n SELECT f.id, f.name FROM farms f\n JOIN farm_settings s ON s.farmid = f.id\n WHERE s.name = ? AND s.value = ?\n ", [\DBFarm::SETTING_PROJECT_ID, $projectId]); while ($rec = $res->FetchRow()) { $ret[$rec['id']] = $rec['name']; } return $ret; }
protected function LogRequest($trans_id, $action, $ipaddr, $request, $response) { $request = filter_var_array($request, ['debug' => ['filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_SCALAR], 'Debug' => ['filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_SCALAR], 'Action' => ['filter' => FILTER_DEFAULT, 'flags' => FILTER_REQUIRE_SCALAR]], true); if ($request['debug'] === 1 || $request['Debug'] === 1 || $request['Action'] === 'DNSZoneRecordAdd') { try { $this->DB->Execute("\n INSERT INTO api_log SET\n transaction_id = ?,\n dtadded = ?,\n action = ?,\n ipaddress = ?,\n request = ?,\n response = ?,\n clientid = ?,\n env_id = ?\n ", [$trans_id, time(), $action, $ipaddr, http_build_query($request), $response, $this->user instanceof Scalr_Account_User ? $this->user->getAccountId() : null, !empty($this->Environment->id) ? $this->Environment->id : null]); } catch (Exception $ignore) { } } }
/** * Gets the list of the environments which have no association with any cost center. * * @return array Returns array looks like [env_id => name] */ public function getUnassignedEnvironments() { $ret = []; //Selects only active environments of active accounts with no cc_id defined $rs = $this->db->Execute("\n SELECT ce.id, ce.name\n FROM client_environments ce\n JOIN clients c ON c.id = ce.client_id\n LEFT JOIN client_environment_properties cep ON ce.id = cep.env_id AND cep.name = ?\n WHERE c.status = ? AND ce.status = ?\n AND (cep.`value` IS NULL OR cep.`value` = '')\n ", [Scalr_Environment::SETTING_CC_ID, Scalr_Account::STATUS_ACTIVE, Scalr_Environment::STATUS_ACTIVE]); while ($rec = $rs->FetchRow()) { $ret[$rec['id']] = $rec['name']; } return $ret; }
public function save($update_system_records = false) { $row = $this->unBind(); unset($row['id']); unset($row['dtlastmodified']); $this->db->BeginTrans(); // Prepare SQL statement $set = array(); $bind = array(); foreach ($row as $field => $value) { $set[] = "`{$field}` = ?"; $bind[] = $value; } $set = join(', ', $set); try { //Save zone; if ($this->id) { if ($update_system_records) { $this->updateSystemRecords(); } // Perform Update $bind[] = $this->id; $this->db->Execute("UPDATE dns_zones SET {$set}, `dtlastmodified` = NOW() WHERE id = ?", $bind); //TODO: if ($update_system_records) { $this->db->Execute("UPDATE dns_zones SET status=?, `dtlastmodified` = NOW() WHERE id = ?", array($this->status, $this->id)); } } else { // Perform Insert $this->db->Execute("INSERT INTO dns_zones SET {$set}", $bind); $this->id = $this->db->Insert_ID(); if ($update_system_records) { $this->updateSystemRecords(); $this->db->Execute("UPDATE dns_zones SET status=?, `dtlastmodified` = NOW() WHERE id = ?", array($this->status, $this->id)); } } if ($this->updateRecords) { $this->db->Execute("DELETE FROM dns_zone_records WHERE zone_id=? AND issystem='0'", array($this->id)); foreach ($this->records as $record) { //UNIQUE KEY `zoneid` (`zone_id`,`type`(1),`value`,`name`) $this->db->Execute("\n INSERT INTO dns_zone_records\n SET `zone_id` = ?,\n `type` = ?,\n `value` = ?,\n `name` = ?,\n `issystem` = '0',\n `ttl` = ?,\n `priority` = ?,\n `weight` = ?,\n `port` = ?\n ON DUPLICATE KEY UPDATE\n `issystem` = '0',\n `ttl` = ?,\n `priority` = ?,\n `weight` = ?,\n `port` = ?\n ", array($this->id, $record['type'], $record['value'], $record['name'], (int) $record['ttl'], (int) $record['priority'], (int) $record['weight'], (int) $record['port'], (int) $record['ttl'], (int) $record['priority'], (int) $record['weight'], (int) $record['port'])); } } } catch (Exception $e) { $this->db->RollbackTrans(); throw new Exception("Cannot save DBDNS zone. Error: " . $e->getMessage(), $e->getCode()); } $this->db->CommitTrans(); try { //$this->saveInPowerDns(); } catch (Exception $e) { Logger::getLogger("DNS")->fatal("Unable to save data in PowerDNS db: {$e->getMessage()}"); } }
/** * Checks if user has permissions to project in environment or account scope * * @param string $projectId Identifier of the project * @param array $criteria ['envId' => '', 'clientid' => ''] * @return bool|mixed */ public function checkPermission($projectId, array $criteria) { $and = ''; foreach ($criteria as $name => $value) { $field = 'f.' . \Scalr::decamelize($name); $and .= " AND " . $field . "=" . $this->db->escape($value); } $projectEntity = new ProjectEntity(); $projectId = $projectEntity->type('projectId')->toDb($projectId); $where = " WHERE p.project_id = UNHEX('" . $projectId . "') AND EXISTS (\n SELECT * FROM farms f\n LEFT JOIN farm_settings fs ON f.id = fs.farmid\n WHERE fs.name = '" . Entity\FarmSetting::PROJECT_ID . "'\n AND REPLACE(fs.value, '-', '') = HEX(p.project_id)\n {$and})"; $sql = "SELECT " . $projectEntity->fields('p') . "\n FROM " . $projectEntity->table('p') . $where; return $this->db->GetOne($sql); }
/** * {@inheritdoc} * @see \Scalr\System\Zmq\Cron\TaskInterface::enqueue() */ public function enqueue() { $this->prepare(); $queue = new ArrayObject([]); $rs = $this->db->Execute($this->stmt, $this->params); while ($row = $rs->FetchRow()) { $obj = new stdClass(); $obj->serverId = $row['server_id']; $obj->status = $row['status']; $queue->append($obj); } if (($cnt = count($queue)) > 0) { $this->getLogger()->info("Found %d server%s to manage.", $cnt, $cnt == 1 ? '' : 's'); } return $queue; }
function Save() { $row = $this->Unbind(); unset($row['id']); // Prepare SQL statement $set = array(); $bind = array(); foreach ($row as $field => $value) { $set[] = "`{$field}` = ?"; $bind[] = $value; } $set = join(', ', $set); try { // Perform Update $bind[] = $this->id; $this->Db->Execute("UPDATE bundle_tasks SET {$set} WHERE id = ?", $bind); } catch (Exception $e) { throw new Exception("Cannot save bundle task. Error: " . $e->getMessage(), $e->getCode()); } }
/** * {@inheritdoc} * @see Scalr\Upgrade.UpdateInterface::hasTable() */ public function hasTable($table, $database = null) { $ret = $this->db->getOne("SHOW TABLES " . ($database ? "FROM `" . $this->db->escape($database) . "` " : "") . "LIKE ?", array($table)); return $ret ? true : false; }
/** * {@inheritdoc} * @see \Scalr\System\Zmq\Cron\TaskInterface::worker() */ public function worker($request) { //Warming up static DI cache \Scalr::getContainer()->warmup(); // Reconfigure observers \Scalr::ReconfigureObservers(); if (!isset($request->farmRoleId)) { //This is the farm with synchronous launch of roles try { $DBFarm = DBFarm::LoadByID($request->farmId); if ($DBFarm->Status != FARM_STATUS::RUNNING) { $this->getLogger()->warn("[FarmID: %d] Farm isn't running. There is no need to scale it.", $DBFarm->ID); return false; } } catch (Exception $e) { $this->getLogger()->error("Could not load farm '%s' with ID:%d", $request->farmName, $request->farmId); throw $e; } //Gets the list of the roles $list = $DBFarm->GetFarmRoles(); } else { //This is asynchronous lauhch try { $DBFarmRole = DBFarmRole::LoadByID($request->farmRoleId); if ($DBFarmRole->getFarmStatus() != FARM_STATUS::RUNNING) { //We don't need to handle inactive farms return false; } } catch (Exception $e) { $this->getLogger()->error("Could not load FarmRole with ID:%d", $request->farmRoleId); throw $e; } $list = [$DBFarmRole]; } $this->getLogger()->debug("Processing %s FarmRoles", count($list)); foreach ($list as $DBFarmRole) { // Set Last polling time $DBFarmRole->SetSetting(Entity\FarmRoleSetting::SCALING_LAST_POLLING_TIME, time(), Entity\FarmRoleSetting::TYPE_LCL); $disabledScaling = false; if ($DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_ENABLED) != '1') { if ($DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ) || $DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::VPC_ROUTER)) { // For Mongo, RabbitMQ and VPC Router we need to launch first instance (or maintain 1 instance running) // When 1 instance is already running, the rest is fully manual $roleTotalInstances = $DBFarmRole->GetRunningInstancesCount() + $DBFarmRole->GetPendingInstancesCount(); if ($roleTotalInstances != 0) { $disabledScaling = true; } } else { if (!$DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::MONGODB)) { $disabledScaling = true; } } if ($disabledScaling) { $this->getLogger()->info("[FarmID: %d] Scaling is disabled for role '%s'. Skipping...", $request->farmId, $DBFarmRole->Alias); continue; } } $farmRoleName = $DBFarmRole->Alias ? $DBFarmRole->Alias : $DBFarmRole->GetRoleObject()->name; // Get current count of running and pending instances. $this->getLogger()->info(sprintf("Processing role '%s'", $farmRoleName)); $scalingManager = new Scalr_Scaling_Manager($DBFarmRole); //Replacing the logger $scalingManager->logger = $this->getLogger(); $scalingDecision = $scalingManager->makeScalingDecision(); $scalingDecisionDetails = $scalingManager->decisonInfo; $this->getLogger()->info(sprintf("Decision '%s' (%s)", $scalingDecision, $scalingDecisionDetails)); if ($scalingDecision == Scalr_Scaling_Decision::STOP_SCALING) { return; } if ($scalingDecision == Scalr_Scaling_Decision::NOOP) { continue; } else { if ($scalingDecision == Scalr_Scaling_Decision::DOWNSCALE) { /* Timeout instance's count decrease. Decreases instances count after scaling resolution the spare instances are running for selected timeout interval from scaling EditOptions */ // We have to check timeout limits before new scaling (downscaling) process will be initiated if ($DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_DOWNSCALE_TIMEOUT_ENABLED)) { // if the farm timeout is exceeded // checking timeout interval. $last_down_scale_data_time = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_DOWNSCALE_DATETIME); $timeout_interval = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::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() \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage(!empty($request->farmId) ? $request->farmId : null, sprintf("Waiting for downscaling timeout on farm %s, role %s", !empty($request->farmName) ? $request->farmName : null, !empty($DBFarmRole->Alias) ? $DBFarmRole->Alias : null), null, null, !empty($DBFarmRole->ID) ? $DBFarmRole->ID : null)); continue; } } // end Timeout instance's count decrease $sort = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::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; $ignoreFullHour = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_IGNORE_FULL_HOUR); $useSafeShutdown = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_SAFE_SHUTDOWN); $isRabbitMQ = $DBFarmRole->GetRoleObject()->hasBehavior(ROLE_BEHAVIORS::RABBITMQ); // 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 $DBServer = null; while (!$got_valid_instance && count($servers) > 0) { $item = array_shift($servers); $DBServer = DBServer::LoadByID($item['server_id']); if ($isRabbitMQ) { $serverExists = $this->db->GetOne("\n SELECT EXISTS (\n SELECT 1 FROM servers\n WHERE farm_roleid = ?\n AND status NOT IN (?, ?)\n AND `index` != ?\n )\n ", [$DBServer->farmRoleId, SERVER_STATUS::TERMINATED, SERVER_STATUS::SUSPENDED, 1]); if ($DBServer->index == 1 && $serverExists) { 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) { $got_valid_instance = true; } //Check safe shutdown if ($useSafeShutdown == 1) { try { $res = $DBServer->scalarizr->system->callAuthShutdownHook(); } catch (Exception $e) { $res = $e->getMessage(); } if ($res != '1') { \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($DBServer->farmId, sprintf("Safe shutdown enabled. Server '%s'. Script returned '%s' skipping it.", $DBServer->serverId, $res), $DBServer->serverId, $DBServer->envId, $DBServer->farmRoleId)); $got_valid_instance = false; } } } // end while if ($DBServer !== null && $got_valid_instance) { $this->getLogger()->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 (!$ignoreFullHour) { $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); \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($request->farmId, sprintf("Role '%s' scaling down (%s). Server '%s' will be terminated in %s minutes. Launch time: %s", $DBServer->GetFarmRoleObject()->Alias, $scalingDecisionDetails, $DBServer->serverId, $timeout, $response->instancesSet->get(0)->launchTime->format('c')), $DBServer->serverId, $DBServer->envId, $DBServer->farmRoleId)); } } } else { $allow_terminate = true; } //Releases memory $DBServer->GetEnvironmentObject()->getContainer()->release('aws'); unset($aws); } else { $allow_terminate = true; } if ($allow_terminate) { $terminateStrategy = $DBFarmRole->GetSetting(Scalr_Role_Behavior::ROLE_BASE_TERMINATE_STRATEGY); if (!$terminateStrategy) { $terminateStrategy = 'terminate'; } try { if ($terminateStrategy == 'terminate') { $DBServer->terminate(DBServer::TERMINATE_REASON_SCALING_DOWN, false); $DBFarmRole->SetSetting(Entity\FarmRoleSetting::SCALING_DOWNSCALE_DATETIME, time(), Entity\FarmRoleSetting::TYPE_LCL); \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($request->farmId, sprintf("Role '%s' scaling down (%s). Server '%s' marked as 'Pending terminate' and will be fully terminated in 3 minutes.", $DBServer->GetFarmRoleObject()->Alias, $scalingDecisionDetails, $DBServer->serverId), $DBServer->serverId, $DBServer->envId, $DBServer->farmRoleId)); } else { $DBServer->suspend('SCALING_DOWN', false); $DBFarmRole->SetSetting(Entity\FarmRoleSetting::SCALING_DOWNSCALE_DATETIME, time(), Entity\FarmRoleSetting::TYPE_LCL); \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($request->farmId, sprintf("Role '%s' scaling down (%s). Server '%s' marked as 'Pending suspend' and will be fully suspended in 3 minutes.", $DBServer->GetFarmRoleObject()->Alias, $scalingDecisionDetails, $DBServer->serverId), $DBServer->serverId, $DBServer->envId, $DBServer->farmRoleId)); } } catch (Exception $e) { $this->getLogger()->fatal(sprintf("Cannot %s %s: %s", $terminateStrategy, $request->farmId, $DBServer->serverId)); } } } else { $this->getLogger()->warn(sprintf("[FarmID: %s] Scalr unable to determine what instance it should terminate (FarmRoleID: %s). Skipping...", $request->farmId, $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(Entity\FarmRoleSetting::SCALING_UPSCALE_TIMEOUT_ENABLED)) { // if the farm timeout is exceeded // checking timeout interval. $last_up_scale_data_time = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_UPSCALE_DATETIME); $timeout_interval = $DBFarmRole->GetSetting(Entity\FarmRoleSetting::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() \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(sprintf("Waiting for upscaling timeout on farm %s, role %s", $request->farmName, $DBFarmRole->Alias)); continue; } } // 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) { \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($request->farmId, sprintf("Role is in slave2master promotion process. Do not launch new slaves while there is no active slaves"))); continue; } else { $DBFarmRole->SetSetting(Scalr_Db_Msr::SLAVE_TO_MASTER, 0, Entity\FarmRoleSetting::TYPE_LCL); } } } if ($DBFarmRole->GetSetting(Entity\FarmRoleSetting::SCALING_ONE_BY_ONE) == 1) { $pendingInstances = $DBFarmRole->GetPendingInstancesCount(); if ($pendingInstances > 0) { \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($request->farmId, sprintf("There are %s pending intances of %s role on % farm. Waiting...", $pendingInstances, $DBFarmRole->Alias, $request->farmName))); continue; } } $fstatus = $this->db->GetOne("SELECT status FROM farms WHERE id=? LIMIT 1", array($request->farmId)); if ($fstatus != FARM_STATUS::RUNNING) { $this->getLogger()->warn("[FarmID: {$request->farmId}] Farm terminated. There is no need to scale it."); return; } $terminateStrategy = $DBFarmRole->GetSetting(Scalr_Role_Behavior::ROLE_BASE_TERMINATE_STRATEGY); if (!$terminateStrategy) { $terminateStrategy = 'terminate'; } $suspendedServer = null; if ($terminateStrategy == 'suspend') { $suspendedServers = $DBFarmRole->GetServersByFilter(array('status' => SERVER_STATUS::SUSPENDED)); if (count($suspendedServers) > 0) { $suspendedServer = array_shift($suspendedServers); } } if ($terminateStrategy == 'suspend' && $suspendedServer) { \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->warn(new FarmLogMessage($request->farmId, sprintf("Role '%s' scaling up (%s). Found server to resume. ServerID = %s.", $suspendedServer->GetFarmRoleObject()->Alias, $scalingDecisionDetails, $suspendedServer->serverId), $suspendedServer->serverId, $suspendedServer->envId, $suspendedServer->farmRoleId)); } if ($terminateStrategy == 'terminate' || !$suspendedServer || !PlatformFactory::isOpenstack($suspendedServer->platform) && $suspendedServer->platform != SERVER_PLATFORMS::EC2 && $suspendedServer->platform != SERVER_PLATFORMS::GCE) { $ServerCreateInfo = new ServerCreateInfo($DBFarmRole->Platform, $DBFarmRole); try { $DBServer = \Scalr::LaunchServer($ServerCreateInfo, null, false, DBServer::LAUNCH_REASON_SCALING_UP); $DBFarmRole->SetSetting(Entity\FarmRoleSetting::SCALING_UPSCALE_DATETIME, time(), Entity\FarmRoleSetting::TYPE_LCL); \Scalr::getContainer()->logger(LOG_CATEGORY::FARM)->info(new FarmLogMessage($request->farmId, sprintf("Role '%s' scaling up (%s). Starting new instance. ServerID = %s.", $DBServer->GetFarmRoleObject()->Alias, $scalingDecisionDetails, $DBServer->serverId), $DBServer->serverId, $DBServer->envId, $DBServer->farmRoleId)); } catch (Exception $e) { \Scalr::getContainer()->logger(LOG_CATEGORY::SCALING)->error($e->getMessage()); } } else { $platform = PlatformFactory::NewPlatform($suspendedServer->platform); $platform->ResumeServer($suspendedServer); } } } } return true; }
public static function showInfo(\PDO $pdo_db, \ADODB_mysqli $db, array $langvars, $whichteam, $isowner, array $playerinfo, $invite_info, $team, Reg $tkireg) { // Heading echo "<div align=center><h3><font color=white><strong>{$team['team_name']}</strong>"; echo "<br><font size=2>\"<i>{$team['description']}</i>\"</font></h3>"; if ($playerinfo['team'] == $team['id']) { echo "<font color=white>"; if ($playerinfo['ship_id'] == $team['creator']) { echo $langvars['l_team_coord'] . " "; } else { echo $langvars['l_team_member'] . " "; } echo $langvars['l_options'] . " <br><font size=2>"; if (is_team_owner($team, $playerinfo) === true) { echo "[<a href=teams.php?teamwhat=9&whichteam={$playerinfo['team']}>" . $langvars['l_edit'] . "</a>] - "; } echo "[<a href=teams.php?teamwhat=7&whichteam={$playerinfo['team']}>" . $langvars['l_team_inv'] . "</a>] - [<a href=teams.php?teamwhat=2&whichteam={$playerinfo['team']}>" . $langvars['l_team_leave'] . "</a>]</font></font>"; } self::displayInviteInfo($langvars, $playerinfo, $invite_info); echo "</div>"; // Main table echo "<table border=2 cellspacing=2 cellpadding=2 bgcolor=\"#400040\" width=\"75%\" align=center><tr>"; echo "<td><font color=white>" . $langvars['l_team_members'] . "</font></td></tr><tr bgcolor={$tkireg->color_line2}>"; $result = $db->Execute("SELECT * FROM {$db->prefix}ships WHERE team = ?;", array($whichteam)); \Tki\Db::LogDbErrors($pdo_db, $result, __LINE__, __FILE__); while (!$result->EOF) { $member = $result->fields; echo "<td> - " . $member['character_name'] . " (" . $langvars['l_score'] . " " . $member['score'] . ")"; if ($isowner && $member['ship_id'] != $playerinfo['ship_id']) { echo " - <font size=2>[<a href=\"teams.php?teamwhat=5&who={$member['ship_id']}\">" . $langvars['l_team_eject'] . "</a>]</font></td>"; } else { if ($member['ship_id'] == $team['creator']) { echo " - " . $langvars['l_team_coord'] . " </td>"; } } echo "</tr><tr bgcolor={$tkireg->color_line2}>"; $result->MoveNext(); } // Displays for members name $res = $db->Execute("SELECT ship_id, character_name FROM {$db->prefix}ships WHERE team_invite = ?;", array($whichteam)); \Tki\Db::LogDbErrors($pdo_db, $res, __LINE__, __FILE__); echo "<td bgcolor={$tkireg->color_line2}><font color=white>" . $langvars['l_team_pending'] . " <strong>" . $team['team_name'] . "</strong></font></td>"; echo "</tr><tr>"; if ($res->RecordCount() > 0) { echo "</tr><tr bgcolor={$tkireg->color_line2}>"; while (!$res->EOF) { $who = $res->fields; echo "<td> - {$who['character_name']}</td>"; echo "</tr><tr bgcolor={$tkireg->color_line2}>"; $res->MoveNext(); } } else { echo "<td>" . $langvars['l_team_noinvites'] . " <strong>" . $team['team_name'] . "</strong>.</td></tr><tr>"; } echo "</tr></table>"; }