Example #1
0
 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());
     }
 }
Example #2
0
 /**
  * {@inheritdoc}
  * @see \Scalr\System\Zmq\Cron\TaskInterface::enqueue()
  */
 public function enqueue()
 {
     $queue = new ArrayObject([]);
     //This is necessary for the next query
     $this->db->Execute("SET @fid := NULL, @num := NULL");
     //Selects one Farm Role from each Farm with synchronous lauhch type and
     //all Farm Roles from each Farm with asynchronous launch type
     $rs = $this->db->Execute("\n            SELECT * FROM (\n                SELECT IF(f.`farm_roles_launch_order` = 1, @num := IF(@fid = f.`id`, @num + 1, 1), 1) `row_number`,\n            \t    @fid := f.`id` `farm_id`,\n            \t    f.`name` `farm_name`,\n            \t    fr.`id` `farm_role_id`,\n            \t    rs.`value` `dt_last_polling`,\n            \t    rs2.`value` `polling_interval`,\n                    f.`farm_roles_launch_order`\n                FROM `farms` f\n                JOIN `clients` c ON c.`id` = f.`clientid`\n                JOIN `client_environments` ce ON ce.`id` = f.`env_id`\n                JOIN `farm_roles` fr ON fr.`farmid` = f.`id`\n                LEFT JOIN `farm_role_settings` rs  ON rs.`farm_roleid` = fr.`id` AND rs.`name` = ?\n                LEFT JOIN `farm_role_settings` rs2 ON rs2.`farm_roleid` = fr.`id` AND rs2.`name` = ?\n                WHERE c.`status` = ? AND ce.`status` = ? AND f.`status` = ?\n                AND (rs.`value` IS NULL OR UNIX_TIMESTAMP() > rs.`value` + IFNULL(rs2.`value`, 1) * 60)\n                ORDER BY f.`id`, fr.`launch_index`\n            ) t WHERE t.`row_number` = 1\n        ", [DBFarmRole::SETTING_SCALING_LAST_POLLING_TIME, DBFarmRole::SETTING_SCALING_POLLING_INTERVAL, Scalr_Account::STATUS_ACTIVE, Scalr_Environment::STATUS_ACTIVE, FARM_STATUS::RUNNING]);
     while ($row = $rs->FetchRow()) {
         $obj = new stdClass();
         $obj->farmId = $row['farm_id'];
         $obj->farmName = $row['farm_name'];
         if (!$row['farm_roles_launch_order']) {
             //Asynchronous launch order
             $obj->farmRoleId = $row['farm_role_id'];
             $obj->lastPollingTime = $row['last_polling_time'];
             $obj->pollingInterval = $row['polling_interval'];
         }
         $queue->append($obj);
     }
     if ($count = $queue->count()) {
         $this->getLogger()->info("%d running farm roles found.", $count);
     }
     return $queue;
 }
Example #3
0
 /**
  * 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;
 }
Example #4
0
 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;
     }
 }
 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;
         }
     }
 }
Example #6
0
 /**
  * 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;
 }
Example #7
0
 /**
  * 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;
 }
Example #8
0
 /**
  * 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);
     }
 }
Example #9
0
 /**
  * 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;
 }
Example #10
0
 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));
     }
 }
Example #11
0
 /**
  * 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;
 }
Example #12
0
 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());
     }
 }
Example #13
0
 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) {
         }
     }
 }
Example #14
0
 /**
  * Gets all known cloud locations for the specified platform.
  *
  * These locations are retrieved from prices table, not from
  * the environment settings.
  *
  * @param   string    $platform  The cloud platform
  * @return  array     Returns array looks like array(url1 => array(cloudLocation1, cloudLocation2, ...), url2 => ...);
  */
 public function getCloudLocations($platform)
 {
     $ret = [];
     $res = $this->cadb->Execute("\n            SELECT DISTINCT `url`, `cloud_location` FROM `price_history`\n            WHERE `platform` = ?\n        ", [$platform]);
     while ($rec = $res->FetchRow()) {
         $url = is_null($rec['url']) ? '' : $rec['url'];
         $ret[$url][] = $rec['cloud_location'];
     }
     return $ret;
 }
Example #15
0
 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) {
         }
     }
 }
Example #16
0
 /**
  * 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;
 }
Example #17
0
 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;
 }
Example #18
0
 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()}");
     }
 }
Example #19
0
 /**
  * {@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;
 }
Example #20
0
 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());
     }
 }
Example #21
0
 /**
  * Gets cloud instance type's name
  *
  * @param string $instanceTypeId    Instance type identifier
  * @param string $envId             Environment identifier
  * @param string $platform          Platform
  * @param string $cloudLocation     Cloud location
  * @return string
  */
 public function getInstanceTypeName($instanceTypeId, $envId, $platform, $cloudLocation)
 {
     static $instanceTypeNames = [];
     static $urlCache = [];
     if ($platform == \SERVER_PLATFORMS::EC2) {
         return $instanceTypeId;
     }
     if (!isset($instanceTypeNames[$envId][$platform][$cloudLocation][$instanceTypeId])) {
         try {
             if (!isset($urlCache[$envId][$platform])) {
                 $curEnv = Scalr_Environment::init()->loadById($envId);
                 $platformObj = PlatformFactory::NewPlatform($platform);
                 $urlCache[$envId][$platform] = $platformObj->getEndpointUrl($curEnv);
             }
             $cloudLocationId = CloudLocation::calculateCloudLocationId($platform, $cloudLocation, $urlCache[$envId][$platform]);
             $rows = $this->db->Execute("\n                    SELECT cit.instance_type_id, cit.name\n                    FROM cloud_instance_types cit\n                    WHERE cit.cloud_location_id = UNHEX(?)\n                ", [str_replace('-', '', $cloudLocationId)]);
             while ($row = $rows->FetchRow()) {
                 $instanceTypeNames[$envId][$platform][$cloudLocation][$row['instance_type_id']] = $row['name'];
             }
         } catch (Exception $e) {
         }
     }
     return !empty($instanceTypeNames[$envId][$platform][$cloudLocation][$instanceTypeId]) ? $instanceTypeNames[$envId][$platform][$cloudLocation][$instanceTypeId] : $instanceTypeId;
 }
Example #22
0
 /**
  * {@inheritdoc}
  * @see Scalr\Upgrade\Entity.AbstractUpgradeEntity::createFailureMessage()
  */
 public function createFailureMessage($log)
 {
     $this->db->Execute("\n            INSERT `" . UpgradeHandler::DB_TABLE_UPGRADE_MESSAGES . "`\n            SET `created` = ?,\n                `uuid` = UNHEX(?),\n                `message` = ?\n        ", array(gmdate('Y-m-d H:i:s'), $this->uuid, $log));
 }
Example #23
0
 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>";
 }
Example #24
0
 public function callActionMethod($method)
 {
     if ($this->request->getRequestType() == Scalr_UI_Request::REQUEST_TYPE_API) {
         $apiMethodCheck = false;
         if (method_exists($this, 'getApiDefinitions')) {
             $api = $this::getApiDefinitions();
             $m = str_replace('Action', '', $method);
             if (in_array($m, $api)) {
                 $apiMethodCheck = true;
             }
         }
         if (!$apiMethodCheck) {
             throw new Scalr_UI_Exception_NotFound();
         }
     }
     /*
      * Debug action section
      * Controller::Action => array of filter's params (accountId, userId) or true
      */
     $debug = false;
     $debugMode = false;
     $key = get_class($this) . '::' . $method;
     if ($debug && array_key_exists($key, $debug)) {
         $value = $debug[$key];
         if (is_array($value) && $this->user) {
             if (isset($value['accountId'])) {
                 if (is_array($value['accountId']) && in_array($this->user->getAccountId(), $value['accountId'])) {
                     $debugMode = true;
                 }
                 if (is_numeric($value['accountId']) && $value['accountId'] == $this->user->getAccountId()) {
                     $debugMode = true;
                 }
             }
             if (isset($value['userId'])) {
                 if (is_array($value['userId']) && in_array($this->user->getId(), $value['userId'])) {
                     $debugMode = true;
                 }
                 if (is_numeric($value['userId']) && $value['userId'] == $this->user->getId()) {
                     $debugMode = true;
                 }
             }
         } else {
             $debugMode = true;
         }
     }
     if ($debugMode) {
         $this->response->debugLog('Server', $_SERVER);
         $this->response->debugLog('Request', $_REQUEST);
         $this->response->debugLog('Session', Scalr_Session::getInstance());
     }
     $this->{$method}();
     if ($debugMode) {
         if ($this->response->jsResponseFlag) {
             $this->response->debugLog('JS Response', $this->response->jsResponse);
         }
         try {
             $message = '';
             foreach ($this->response->serverDebugLog as $value) {
                 $message .= $value['key'] . ":\n" . $value['value'] . "\n\n";
             }
             $this->db->Execute('INSERT INTO ui_debug_log (ipaddress, url, report, env_id, account_id, user_id) VALUES(?, ?, ?, ?, ?, ?)', array($this->request->getClientIp(), $key, $message, $this->getEnvironment() ? $this->getEnvironmentId() : 0, $this->user ? $this->user->getAccountId() : 0, $this->user ? $this->user->getId() : 0));
         } catch (Exception $e) {
         }
     }
 }
Example #25
0
 function handle($queue, Scalr_Messaging_Msg $message, $rawMessage)
 {
     $dbserver = DBServer::LoadByID($message->getServerId());
     if ($message instanceof Scalr_Messaging_Msg_ExecScriptResult) {
         try {
             $storage = \Scalr::config('scalr.system.scripting.logs_storage');
             if (!$message->executionId || $storage == 'scalr') {
                 $msg = sprintf("STDERR: %s \n\n STDOUT: %s", base64_decode($message->stderr), base64_decode($message->stdout));
             }
             if ($message->scriptPath) {
                 $name = stristr($message->scriptPath, '/usr/local/bin/scalr-scripting') ? $message->scriptName : $message->scriptPath;
             } else {
                 $name = $message->scriptName;
             }
             $this->db->Execute("INSERT DELAYED INTO scripting_log SET\n                    farmid = ?,\n                    server_id = ?,\n                    event = ?,\n                    message = ?,\n                    dtadded = NOW(),\n                    script_name = ?,\n                    event_server_id = ?,\n                    exec_time = ?,\n                    exec_exitcode = ?,\n                    event_id = ?,\n                    execution_id = ?,\n                    run_as = ?\n                ", array($dbserver->farmId, $message->getServerId(), $message->eventName, $msg, $name, $message->eventServerId, round($message->timeElapsed, 2), $message->returnCode, $message->eventId, $message->executionId, $message->runAs));
             if ($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]) {
                 DBServer::LoadByID($message->getServerId())->setScalarizrVersion($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]);
             }
             if ($message->eventId) {
                 $updateTotal = '';
                 if ($message->returnCode == 130) {
                     $field = 'scripts_timedout';
                 } elseif ($message->returnCode != 0) {
                     $field = 'scripts_failed';
                 } else {
                     $field = 'scripts_completed';
                 }
                 if (stristr($name, '[Scalr built-in]')) {
                     $updateTotal = ', `scripts_total` = `scripts_total`+1';
                 }
                 $this->db->Execute("UPDATE events SET `{$field}` = `{$field}`+1 {$updateTotal} WHERE event_id = ?", array($message->eventId));
             }
         } catch (Exception $e) {
             $this->logger->fatal($e->getMessage());
         }
     } elseif ($message instanceof Scalr_Messaging_Msg_Log) {
         try {
             if ($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]) {
                 DBServer::LoadByID($message->getServerId())->setScalarizrVersion($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]);
             }
         } catch (Exception $e) {
         }
         foreach ($message->entries as $entry) {
             try {
                 if (self::$severityCodes[$entry->level] < 3) {
                     continue;
                 }
                 $tm = date('YmdH');
                 $hash = md5("{$message->getServerId()}:{$entry->msg}:{$dbserver->farmId}:{$entry->name}:{$tm}", true);
                 $this->db->Execute("INSERT DELAYED INTO logentries SET\n                        `id` = ?,\n                        `serverid` = ?,\n                        `message` = ?,\n                        `severity` = ?,\n                        `time` = ?,\n                        `source` = ?,\n                        `farmid` = ?\n                        ON DUPLICATE KEY UPDATE cnt = cnt + 1, `time` = ?\n                    ", array($hash, $message->getServerId(), $entry->msg, self::$severityCodes[$entry->level], time(), $entry->name, $dbserver->farmId, time()));
             } catch (Exception $e) {
                 $this->logger->error($e->getMessage());
             }
         }
     } elseif ($message instanceof Scalr_Messaging_Msg_RebundleLog) {
         try {
             $this->db->Execute("INSERT INTO bundle_task_log SET\n                    bundle_task_id = ?,\n                    dtadded = NOW(),\n                    message = ?\n                ", array($message->bundleTaskId, $message->message));
         } catch (Exception $e) {
             $this->logger->error($e->getMessage());
         }
     } elseif ($message instanceof Scalr_Messaging_Msg_DeployLog) {
         try {
             $this->db->Execute("INSERT INTO dm_deployment_task_logs SET\n                    `dm_deployment_task_id` = ?,\n                    `dtadded` = NOW(),\n                    `message` = ?\n                ", array($message->deployTaskId, $message->message));
         } catch (Exception $e) {
         }
     }
 }
 public function save()
 {
     $this->db->Execute("INSERT INTO farm_role_storage_devices SET\n            farm_role_id = ?,\n            server_index = ?,\n            storage_config_id = ?,\n            env_id = ?,\n            cloud_location = ?,\n            config = ?,\n            placement = ?,\n            storage_id = ?,\n            status = ?\n        ON DUPLICATE KEY UPDATE config = ?, status = ?, placement = ?\n        ", array($this->farmRoleId, $this->serverIndex, $this->storageConfigId, $this->envId, $this->cloudLocation, @json_encode($this->config), $this->placement, $this->storageId, $this->status, @json_encode($this->config), $this->status, $this->placement));
     return $this;
 }
Example #27
0
File: Acl.php Project: recipe/scalr
 /**
  * Gets all users which belong to the specified account role.
  *
  * @param   string     $accountRoleId The identifier of the role of account level.
  * @param   int        $accountId     The identifier of the account
  * @return  array      Returns users array looks like
  *                     array(userid => array(
  *                        'id'    => identifier of the user,
  *                        'name'  => full name,
  *                        'type'  => user type,
  *                        'email' => user email,
  *                        'status'=> status,
  *                        'teams' => array(teamId => team name),
  *                     ))
  */
 public function getUsersHaveAccountRole($accountRoleId, $accountId)
 {
     $accountId = intval($accountId);
     $users = array();
     $select = "SELECT tu.`user_id`, tu.`team_id`, u.`type`, u.`email`, u.`status`, u.`fullname`, t.`name` AS `team_name`";
     //Users which belong to the team with defined ACL roles
     $rs = $this->db->Execute("\n            " . $select . "\n            FROM `acl_account_roles` ar\n            JOIN `account_team_user_acls` tua ON tua.`account_role_id` = ar.`account_role_id`\n            JOIN `account_team_users` tu ON tua.`account_team_user_id` = tu.id\n            JOIN `account_teams` t ON t.`account_id` = " . $accountId . " AND t.id = tu.`team_id`\n            JOIN `account_users` u ON u.`account_id` = " . $accountId . " AND u.id = tu.`user_id`\n            WHERE ar.`account_role_id` = ?\n            AND ar.`account_id` = " . $accountId . "\n            GROUP by tu.`user_id`, tu.`team_id`\n        ", array($accountRoleId));
     while ($rec = $rs->FetchRow()) {
         if (!isset($users[$rec['user_id']])) {
             $users[$rec['user_id']] = array('id' => $rec['user_id'], 'name' => $rec['fullname'], 'type' => $rec['type'], 'email' => $rec['email'], 'status' => $rec['status'], 'teams' => array());
         }
         $users[$rec['user_id']]['teams'][$rec['team_id']] = $rec['team_name'];
     }
     //Users which belong to the teams with team's default ACL role
     $rs = $this->db->Execute("\n            " . $select . "\n            FROM acl_account_roles ar\n            JOIN account_teams t ON t.account_id = " . $accountId . " AND t.account_role_id = ar.account_role_id\n            JOIN account_team_users tu ON tu.team_id = t.id\n            JOIN account_users u ON u.account_id = " . $accountId . " AND u.id = tu.user_id\n            LEFT JOIN account_team_user_acls tua ON tua.account_team_user_id = tu.id\n            WHERE ar.account_role_id = ?\n            AND ar.account_id = " . $accountId . "\n            AND tua.account_role_id IS NULL\n            GROUP by tu.user_id, tu.team_id\n        ", array($accountRoleId));
     while ($rec = $rs->FetchRow()) {
         if (!isset($users[$rec['user_id']])) {
             $users[$rec['user_id']] = array('id' => $rec['user_id'], 'name' => $rec['fullname'], 'type' => $rec['type'], 'email' => $rec['email'], 'status' => $rec['status'], 'teams' => array());
         }
         if (!array_key_exists($rec['team_id'], $users[$rec['user_id']]['teams'])) {
             $users[$rec['user_id']]['teams'][$rec['team_id']] = $rec['team_name'];
         }
     }
     return $users;
 }
Example #28
0
 /**
  * {@inheritdoc}
  * @see Scalr_System_Cronjob_MultiProcess_DefaultWorker::handleWork()
  */
 function handleWork($farmId)
 {
     try {
         $dbFarm = DBFarm::LoadByID($farmId);
         if ($dbFarm->Status != FARM_STATUS::RUNNING) {
             return;
         }
     } catch (Exception $e) {
         return;
     }
     foreach ($dbFarm->GetFarmRoles() as $dbFarmRole) {
         $instancesHealth = array();
         if ($dbFarmRole->Platform == SERVER_PLATFORMS::EC2) {
             $env = Scalr_Environment::init()->loadById($dbFarm->EnvID);
             $aws = $env->aws($dbFarmRole);
             $statusList = $aws->ec2->instance->describeStatus();
             foreach ($statusList as $sd) {
                 /* @var $sd \Scalr\Service\Aws\Ec2\DataType\InstanceStatusData */
                 $instancesHealth[$sd->instanceId] = $sd;
             }
             unset($statusList);
             //Releases memory
             $env->getContainer()->release('aws');
             unset($aws);
         }
         $servers = $this->db->Execute("\n                SELECT server_id FROM servers\n                WHERE farm_roleid = ? AND status = ?\n            ", array($dbFarmRole->ID, SERVER_STATUS::RUNNING));
         while ($server = $servers->FetchRow()) {
             $dbServer = DBServer::LoadByID($server['server_id']);
             // Do not support ami-scripts
             if (!$dbServer->IsSupported("0.5")) {
                 continue;
             }
             // Do not support windows
             if ($dbServer->IsSupported("0.8") && !$dbServer->IsSupported("0.9")) {
                 continue;
             }
             if ($dbServer->GetProperty(SERVER_PROPERTIES::REBOOTING)) {
                 continue;
             }
             $serverAlerts = new Alerts($dbServer);
             //Check AWS healthchecks
             if ($dbServer->platform == SERVER_PLATFORMS::EC2) {
                 try {
                     /* @var $statusInfo \Scalr\Service\Aws\Ec2\DataType\InstanceStatusData */
                     $statusInfo = isset($instancesHealth[$dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID)]) ? $instancesHealth[$dbServer->GetProperty(EC2_SERVER_PROPERTIES::INSTANCE_ID)] : null;
                     if ($statusInfo) {
                         $check = Alerts::METRIC_AWS_SYSTEM_STATUS;
                         $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
                         if ($statusInfo->systemStatus->status == 'ok' && $hasActiveAlert) {
                             Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
                         } elseif ($statusInfo->systemStatus->status != 'ok' && $statusInfo->systemStatus->status != 'initializing' && !$hasActiveAlert) {
                             $txtDetails = "";
                             $details = $statusInfo->systemStatus->details;
                             if ($details) {
                                 foreach ($details as $d) {
                                     /* @var $d \Scalr\Service\Aws\Ec2\DataType\InstanceStatusDetailsSetData */
                                     $txtDetails .= " {$d->name} is {$d->status},";
                                 }
                                 $txtDetails = trim($txtDetails, " ,");
                                 unset($details);
                             }
                             Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, "{$statusInfo->systemStatus->status}: {$txtDetails}"));
                         }
                         $check = Alerts::METRIC_AWS_INSTANCE_STATUS;
                         $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
                         if ($statusInfo->instanceStatus->status == 'ok' && $hasActiveAlert) {
                             Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
                         } else {
                             if ($statusInfo->instanceStatus->status != 'ok' && $statusInfo->instanceStatus->status != 'initializing' && !$hasActiveAlert) {
                                 $txtDetails = "";
                                 $details = $statusInfo->instanceStatus->details;
                                 if ($details) {
                                     foreach ($details as $d) {
                                         /* @var $d \Scalr\Service\Aws\Ec2\DataType\InstanceStatusDetailsSetData */
                                         $txtDetails .= " {$d->name} is {$d->status},";
                                     }
                                     $txtDetails = trim($txtDetails, " ,");
                                     unset($details);
                                 }
                                 Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, "{$statusInfo->instanceStatus->status}: {$txtDetails}"));
                             }
                         }
                         unset($statusInfo);
                     }
                 } catch (Exception $e) {
                 }
             }
             //Not supported by VPC yet.
             if ($dbFarm->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) {
                 continue;
             }
             $ip = $dbServer->getSzrHost();
             //Check scalr-upd-client status
             $check = Alerts::METRIC_SCALARIZR_UPD_CLIENT_CONNECTIVITY;
             $port = $dbServer->getPort(DBServer::PORT_UPDC);
             $result = $this->checkPort($ip, $port);
             $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
             if (!$result['status'] && !$hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, $result['error']));
             } elseif ($result['status'] && $hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
             } elseif ($hasActiveAlert) {
                 $serverAlerts->updateLastCheckTime($check);
             }
             //Check scalarizr connectivity status
             $check = Alerts::METRIC_SCALARIZR_CONNECTIVITY;
             $port = $dbServer->getPort(DBServer::PORT_CTRL);
             $result = $this->checkPort($ip, $port);
             $hasActiveAlert = $serverAlerts->hasActiveAlert($check);
             if (!$result['status'] && !$hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckFailedEvent($dbServer, $check, $result['error']));
             } elseif ($result['status'] && $hasActiveAlert) {
                 Scalr::FireEvent($dbServer->farmId, new CheckRecoveredEvent($dbServer, $check));
             } elseif ($hasActiveAlert) {
                 $serverAlerts->updateLastCheckTime($check);
             }
         }
     }
     exit;
 }
Example #29
0
 public function ClearSettings($filter)
 {
     $this->DB->Execute("DELETE FROM client_settings WHERE `key` LIKE '{$filter}' AND clientid = ?", array($this->ID));
 }
Example #30
0
 function handle($queue, Scalr_Messaging_Msg $message, $rawMessage)
 {
     $dbserver = DBServer::LoadByID($message->getServerId());
     if ($message instanceof Scalr_Messaging_Msg_ExecScriptResult) {
         try {
             $storage = \Scalr::config('scalr.system.scripting.logs_storage');
             if (!$message->executionId || $storage == 'scalr') {
                 $msg = sprintf("STDERR: %s \n\n STDOUT: %s", base64_decode($message->stderr), base64_decode($message->stdout));
             }
             if ($message->scriptPath) {
                 $name = stristr($message->scriptPath, '/usr/local/bin/scalr-scripting') ? $message->scriptName : $message->scriptPath;
             } else {
                 $name = $message->scriptName;
             }
             $this->db->Execute("INSERT DELAYED INTO scripting_log SET\n                    farmid = ?,\n                    server_id = ?,\n                    event = ?,\n                    message = ?,\n                    dtadded = NOW(),\n                    script_name = ?,\n                    event_server_id = ?,\n                    exec_time = ?,\n                    exec_exitcode = ?,\n                    event_id = ?,\n                    execution_id = ?,\n                    run_as = ?\n                ", array($dbserver->farmId, $message->getServerId(), $message->eventName, $msg, $name, $message->eventServerId, round($message->timeElapsed, 2), $message->returnCode, $message->eventId, $message->executionId, $message->runAs));
             if ($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]) {
                 DBServer::LoadByID($message->getServerId())->setScalarizrVersion($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]);
             }
         } catch (Exception $e) {
             $this->logger->fatal($e->getMessage());
         }
     } elseif ($message instanceof Scalr_Messaging_Msg_Log) {
         try {
             if ($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]) {
                 DBServer::LoadByID($message->getServerId())->setScalarizrVersion($message->meta[Scalr_Messaging_MsgMeta::SZR_VERSION]);
             }
         } catch (Exception $e) {
         }
         foreach ($message->entries as $entry) {
             try {
                 if (self::$severityCodes[$entry->level] < 3) {
                     continue;
                 }
                 $tm = date('YmdH');
                 $hash = md5("{$message->getServerId()}:{$entry->msg}:{$dbserver->farmId}:{$entry->name}:{$tm}", true);
                 $this->db->Execute("INSERT DELAYED INTO logentries SET\n                        `id` = ?,\n                        `serverid` = ?,\n                        `message` = ?,\n                        `severity` = ?,\n                        `time` = ?,\n                        `source` = ?,\n                        `farmid` = ?\n                        ON DUPLICATE KEY UPDATE cnt = cnt + 1, `time` = ?\n                    ", array($hash, $message->getServerId(), $entry->msg, self::$severityCodes[$entry->level], time(), $entry->name, $dbserver->farmId, time()));
             } catch (Exception $e) {
                 $this->logger->error($e->getMessage());
             }
         }
     } elseif ($message instanceof Scalr_Messaging_Msg_RebundleLog) {
         try {
             $this->db->Execute("INSERT INTO bundle_task_log SET\n                    bundle_task_id = ?,\n                    dtadded = NOW(),\n                    message = ?\n                ", array($message->bundleTaskId, $message->message));
         } catch (Exception $e) {
             $this->logger->error($e->getMessage());
         }
     } elseif ($message instanceof Scalr_Messaging_Msg_DeployLog) {
         try {
             $this->db->Execute("INSERT INTO dm_deployment_task_logs SET\n                    `dm_deployment_task_id` = ?,\n                    `dtadded` = NOW(),\n                    `message` = ?\n                ", array($message->deployTaskId, $message->message));
         } catch (Exception $e) {
         }
     }
     /*elseif ($message instanceof Scalr_Messaging_Msg_OperationDefinition) {
                 try {
                     if ($message->name == 'Execute scripts')
                         return;
     
                     $this->db->Execute("INSERT INTO server_operations SET
                         `id` = ?,
                         `server_id` = ?,
                         `timestamp` = ?,
                         `status`	= ?,
                         `name` = ?,
                         `phases` = ?
                     ", array(
                         $message->id,
                         $dbserver->serverId,
                         time(),
                         'running',
                         $message->name,
                         json_encode($message->phases)
                     ));
                 } catch (Exception $e) {}
             } elseif ($message instanceof Scalr_Messaging_Msg_OperationProgress) {
                 try {
     
                     $opName = $this->db->GetOne("SELECT name FROM server_operations WHERE id = ? LIMIT 1", array($message->id));
                     if (!$opName || ($opName != 'Initialization' && $opName != 'Grow MySQL/Percona data volume'))
                         return;
     
                     if ($message->warning) {
                         $msg = $message->warning->message;
                         $trace = $message->warning->trace;
                         $handler = $message->warning->handler;
                     }
     
                     $this->db->Execute("INSERT INTO server_operation_progress SET
                         `operation_id` = ?,
                         `timestamp` = ?,
                         `phase` = ?,
                         `step` = ?,
                         `status` = ?,
                         `message`= ?,
                         `trace` = ?,
                         `handler` = ?,
                         `progress` = ?,
                         `stepno` = ?
                         ON DUPLICATE KEY UPDATE status = ?, progress = ?, trace = ?, handler = ?, message = ?
                     ", array(
                         $message->id,
                         $message->getTimestamp(),
                         $message->phase,
                         $message->step,
                         $message->status,
                         $msg,
                         $trace,
                         $handler,
                         $message->progress,
                         $message->stepno,
                         //
                         $message->status,
                         $message->progress,
                         $trace,
                         $handler,
                         $msg
                     ));
                 } catch (Exception $e) {}
             }*/
 }