Since: 4.5.0 (10.10.2013)
Author: Vitaliy Demidov (vitaliy@scalr.com)
Inheritance: extends Scalr\Model\AbstractGetter, implements IteratorAggregat\IteratorAggregate
Esempio n. 1
0
 /**
  * Check whether the user has access permissions to the specified object.
  *
  * It should check only Entity level access permissions, NOT ACL
  *
  * @param   AbstractEntity  $entity                  Object that defines permissions
  * @param   User            $user                    The User Entity
  * @param   Environment     $environment    optional The Environment Entity if request is from Environment scope
  * @param   bool            $modify         optional Whether it should check MODIFY permission. By default it checks READ permission.
  *
  * @return  bool    Returns TRUE if the user has access to the specified object
  *
  * @see AccessPermissionsInterface::hasAccessPermissions()
  */
 public function checkInheritedPermissions(AbstractEntity $entity, User $user, Environment $environment = null, $modify = null)
 {
     if (!$entity instanceof ScopeInterface) {
         throw new InvalidArgumentException("Entity must implements ScopeInterface!");
     }
     switch ($entity->getScope()) {
         case static::SCOPE_ACCOUNT:
             return $entity->accountId == $user->accountId && (empty($environment) || !$modify);
         case static::SCOPE_ENVIRONMENT:
             return $environment ? $entity->envId == $environment->id : $user->hasAccessToEnvironment($entity->envId);
         case static::SCOPE_SCALR:
             return !$modify;
         default:
             return false;
     }
 }
Esempio n. 2
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\AbstractEntity::save()
  */
 public function save()
 {
     if (empty($this->emails)) {
         throw new AnalyticsException(sprintf("Email must be set for the %s.", get_class($this)));
     }
     parent::save();
 }
Esempio n. 3
0
 /**
  * {@inheritdoc}
  * @see AbstractEntity::save()
  */
 public function save()
 {
     parent::save();
     if (!empty($this->_settings)) {
         $this->_settings->save();
     }
 }
Esempio n. 4
0
 /**
  * {@inheritdoc}
  * @see ApiEntityAdapter::copyAlterableProperties()
  */
 public function copyAlterableProperties($object, AbstractEntity $entity, $scope = ScopeInterface::SCOPE_SCALR)
 {
     /* @var $entity GlobalVariable */
     $rules = $this->getRules();
     if (!isset($rules[static::RULE_TYPE_ALTERABLE])) {
         //Nothing to copy
         throw new Exception(sprintf("ApiEntityAdapter::RULE_TYPE_ALTERABLE offset of rules has not been defined for the %s class.", get_class($this)));
     }
     $notAlterable = array_diff(array_keys(get_object_vars($object)), $rules[static::RULE_TYPE_ALTERABLE]);
     if (!empty($notAlterable)) {
         if (count($notAlterable) > 1) {
             $message = "You are trying to set properties %s that either are not alterable or do not exist";
         } else {
             $message = "You are trying to set the property %s which either is not alterable or does not exist";
         }
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, sprintf($message, implode(', ', $notAlterable)));
     }
     $allowOnlyValue = $this->scopesPriority[$entity->getScope()] < $this->scopesPriority[$scope];
     if ($entity->final && $allowOnlyValue) {
         throw new ApiErrorException(403, ErrorMessage::ERR_SCOPE_VIOLATION, "You can't change final variable locked on {$entity->getScope()} level");
     }
     foreach ($rules[static::RULE_TYPE_ALTERABLE] as $key) {
         if (!property_exists($object, $key)) {
             continue;
         }
         //As the name of the property that goes into response may be different from the
         //real property name in the Entity object it should be mapped at first
         if (!empty($rules[static::RULE_TYPE_TO_DATA])) {
             //if toData rule is null it means all properties are allowed
             if (($property = array_search($key, $rules[static::RULE_TYPE_TO_DATA])) !== false) {
                 if (is_string($property)) {
                     //In this case the real name of the property is the key of the array
                     if ($property[0] === '_' && method_exists($this, $property)) {
                         //It is callable
                         continue;
                     }
                 } else {
                     $property = $key;
                 }
                 if ($allowOnlyValue && $property != 'value' && isset($object->{$key}) && $object->{$key} != $entity->{$property}) {
                     throw new ApiErrorException(403, ErrorMessage::ERR_SCOPE_VIOLATION, sprintf("This variable was declared in the %s Scope, you can only modify its 'value' field in the Farm Role Scope", ucfirst($entity->getScope())));
                 }
             }
         }
     }
 }
Esempio n. 5
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\AbstractEntity::save()
  */
 public function save()
 {
     if ($this->{static::ENTITY_VALUE_FIELD_NAME} === null) {
         $this->delete();
     } else {
         parent::save();
     }
 }
Esempio n. 6
0
 /**
  * Copies all alterable properties from the request object to Entity
  *
  * It does not validate the values. It only checks whether the request
  * contains only alterable properties. If not it will raise ApiErrorExceptions
  *
  * @param    object         $object An object (source)
  * @param    AbstractEntity $entity An Entity (destination)
  * @throws ApiErrorException
  * @throws Exception
  */
 public function copyAlterableProperties($object, AbstractEntity $entity)
 {
     $rules = $this->getRules();
     if (!isset($rules[static::RULE_TYPE_ALTERABLE])) {
         //Nothing to copy
         throw new \Exception(sprintf("ApiEntityAdapter::RULE_TYPE_ALTERABLE offset of rules has not been defined for the %s class.", get_class($this)));
     }
     $it = $entity->getIterator();
     $notAlterable = array_diff(array_keys(get_object_vars($object)), $rules[static::RULE_TYPE_ALTERABLE]);
     if (!empty($notAlterable)) {
         if (count($notAlterable) > 1) {
             $message = "You are trying to set properties %s that either are not alterable or do not exist";
         } else {
             $message = "You are trying to set the property %s which either is not alterable or does not exist";
         }
         throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_STRUCTURE, sprintf($message, implode(', ', $notAlterable)));
     }
     foreach ($rules[static::RULE_TYPE_ALTERABLE] as $key) {
         if (!property_exists($object, $key)) {
             continue;
         }
         //As the name of the property that goes into response may be different from the
         //real property name in the Entity object it should be mapped at first
         if (!empty($rules[static::RULE_TYPE_TO_DATA])) {
             //if toData rule is null it means all properties are allowed
             if (($property = array_search($key, $rules[static::RULE_TYPE_TO_DATA])) !== false) {
                 if (is_string($property)) {
                     //In this case the real name of the property is the key of the array
                     if ($property[0] === '_' && method_exists($this, $property)) {
                         //It is callable
                         $this->{$property}($object, $entity, self::ACT_CONVERT_TO_ENTITY);
                         continue;
                     }
                 } else {
                     $property = $key;
                 }
             }
         }
         $property = isset($property) ? $property : $key;
         $entity->{$property} = $object->{$key} === null ? null : self::convertInputValue($it->getField($property)->column->type, $object->{$key});
     }
 }
Esempio n. 7
0
 /**
  * Creates partitions
  */
 public function create()
 {
     $db = $this->entity->db();
     $dt = new \DateTime('tomorrow');
     $end = new \DateTime('+1 month');
     $interval = new \DateInterval("P1D");
     $patritionSet = '';
     while ($dt <= $end) {
         $patritionSet .= "PARTITION p" . $dt->format('Ymd') . " VALUES LESS THAN (UNIX_TIMESTAMP('" . $dt->format('Y-m-d') . " 00:00:00')),";
         $dt->add($interval);
     }
     $this->_disableChecks();
     try {
         $this->entity->db()->Execute("\n                ALTER TABLE " . $this->entity->table() . "\n                PARTITION BY RANGE(UNIX_TIMESTAMP(" . $this->field->getColumnName() . ")) (" . rtrim($patritionSet, ',') . ")\n            ");
     } catch (\Exception $e) {
         $this->_enableChecks();
         throw $e;
     }
     $this->_enableChecks();
 }
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\AbstractEntity::save()
  */
 public function save()
 {
     if (empty($this->eventId)) {
         throw new ModelException(sprintf("eventId must be set for %s before saving.", get_class($this)));
     } else {
         if (empty($this->ccId)) {
             throw new ModelException(sprintf("ccId must be set for %s before saving.", get_class($this)));
         }
     }
     parent::save();
 }
Esempio n. 9
0
 /**
  * Constructor
  *
  * @param   AbstractEntity   $entity An entity
  */
 public function __construct(AbstractEntity $entity)
 {
     $this->position = 0;
     $this->entity = $entity;
     $this->refl = $entity->_getReflectionClass();
     $this->refProps = new ArrayObject(array());
     $this->primaryKey = array();
     $entityAnnotation = $entity->getEntityAnnotation();
     $fieldsIterator = array();
     $pos = 0;
     $properties = $this->refl->getProperties(ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC);
     $staticProperties = $this->refl->getProperties(ReflectionProperty::IS_STATIC);
     foreach (array_diff($properties, $staticProperties) as $refProp) {
         /* @var $refProp \ReflectionProperty */
         /* @var $field \Scalr\Model\Loader\Field */
         if (substr($refProp->name, 0, 1) != '_') {
             if (!isset(self::$cache[$this->refl->name][$refProp->name])) {
                 //executes only once
                 $loader = \Scalr::getContainer()->get('model.loader');
                 $loader->load($refProp);
                 $field = $refProp->annotation;
                 $field->setEntityAnnotation($entityAnnotation);
                 $typeClass = __NAMESPACE__ . '\\Type\\' . ucfirst($field->column->type) . 'Type';
                 $refProp->annotation->setType(new $typeClass($field));
                 self::$cache[$refProp->class][$refProp->name] = $field;
                 unset($field);
             }
             $refProp->annotation = self::$cache[$refProp->class][$refProp->name];
             $fieldsIterator[$refProp->annotation->name] = $refProp->annotation;
             if (isset($refProp->annotation->id)) {
                 $this->primaryKey[] = $refProp->name;
             }
             if (isset($refProp->annotation->generatedValue->strategy) && $refProp->annotation->generatedValue->strategy == GeneratedValue::STRATEGY_AUTO) {
                 $this->autogenerated = $refProp->annotation;
             }
             $this->refProps->append($refProp);
             $this->propertyPositions[$refProp->name] = $pos++;
         }
     }
     $this->_fieldsIterator = new ArrayIterator($fieldsIterator);
 }
Esempio n. 10
0
 public function save()
 {
     $this->variables = [];
     $matches = [];
     $text = preg_replace('/(\\\\%)/si', '$$scalr$$', $this->content);
     preg_match_all("/\\%([^\\%\\s]+)\\%/si", $text, $matches);
     $builtin = array_keys(\Scalr_Scripting_Manager::getScriptingBuiltinVariables());
     foreach ($matches[1] as $var) {
         if (!in_array($var, $builtin)) {
             $this->variables[$var] = ucwords(str_replace("_", " ", $var));
         }
     }
     parent::save();
 }
Esempio n. 11
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\AbstractEntity::delete()
  */
 public function delete()
 {
     if (!$this->checkRemoval()) {
         //Archive it
         $this->archived = true;
         $this->save();
     } else {
         //Completely remove it
         parent::delete();
     }
 }
Esempio n. 12
0
 public function delete()
 {
     parent::delete();
     ReportEntity::deleteByAccountId($this->id);
     NotificationEntity::deleteByAccountId($this->id);
 }
Esempio n. 13
0
 private function checkResultEntries(AbstractEntity $entity, $expectedCount, $expectedResultClass, $expectedEntryType, array $criteria = null, callable $countFunction = null)
 {
     $result = $entity->find($criteria);
     $this->assertNotEmpty($result);
     $this->assertInstanceOf($expectedResultClass, $result, get_class($result));
     if ($countFunction === null) {
         $countFunction = 'count';
     }
     $this->assertEquals($expectedCount, $countFunction($result));
     $classType = class_exists($expectedEntryType);
     foreach ($result as $entry) {
         if ($classType) {
             $this->assertInstanceOf($expectedEntryType, $entry, get_class($entry));
         } else {
             $this->assertInternalType($expectedEntryType, $entry, gettype($entry));
         }
     }
 }
Esempio n. 14
0
 /**
  * {@inheritdoc}
  * @see AbstractEntity::delete()
  */
 public function delete()
 {
     $db = $this->db();
     try {
         // we should set scaling to manual to prevent starting new instances while we are deleting FarmRole
         $frs = new FarmRoleSetting();
         $db->Execute("\n                 UPDATE {$frs->table()}\n                 SET {$frs->columnValue} = ?\n                 WHERE {$frs->columnFarmRoleId} = ?\n                 AND {$frs->columnName} = ?\n            ", [0, $this->id, FarmRoleSetting::SCALING_ENABLED]);
         $this->terminateServers();
         $db->BeginTrans();
         // Clear farm role options & scripts
         $db->Execute("DELETE FROM farm_role_service_config_presets WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM farm_role_service_config_presets WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM farm_role_scripting_targets WHERE `target`=? AND `target_type` = 'farmrole'", [$this->id]);
         $db->Execute("DELETE FROM ec2_ebs WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM elastic_ips WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM storage_volumes WHERE farm_roleid=?", [$this->id]);
         // Clear apache vhosts and update DNS zones
         $db->Execute("UPDATE apache_vhosts SET farm_roleid='0', farm_id='0' WHERE farm_roleid=?", [$this->id]);
         $db->Execute("UPDATE dns_zones SET farm_roleid='0' WHERE farm_roleid=?", [$this->id]);
         $this->deleteScheduled();
         $db->Execute("DELETE FROM farm_role_scripts WHERE farm_roleid=?", [$this->id]);
         parent::delete();
         $db->CommitTrans();
     } catch (Exception $e) {
         $db->RollbackTrans();
         throw $e;
     }
 }
Esempio n. 15
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\AbstractEntity::load()
  */
 public function load($obj, $tableAlias = null)
 {
     parent::load($obj);
     if (empty($this->ccId) || $this->ccId === '00000000-0000-0000-0000-000000000000') {
         $this->ccId = null;
     }
     if (empty($this->projectId) || $this->projectId === '00000000-0000-0000-0000-000000000000') {
         $this->projectId = null;
     }
 }
Esempio n. 16
0
 /**
  * Magic getter
  *
  * @param   string $name Name of property that is accessed
  *
  * @return  mixed   Returns property value
  */
 public function __get($name)
 {
     switch ($name) {
         case 'properties':
             if (empty($this->_properties)) {
                 $this->_properties = new SettingsCollection('Scalr\\Model\\Entity\\ServerProperty', [['serverId' => &$this->serverId]], ['serverId' => &$this->serverId]);
             }
             return $this->_properties;
         case 'scalarizr':
             $this->_scalarizr = new stdClass();
             // Get list of namespaces
             $refl = new ReflectionClass('Scalr_Net_Scalarizr_Client');
             foreach ($refl->getConstants() as $c => $v) {
                 if (substr($c, 0, 9) == 'NAMESPACE') {
                     $this->_scalarizr->{$v} = Scalr_Net_Scalarizr_Client::getClient($this->__getDBServer(), $v, $this->getPort(self::PORT_API));
                 }
             }
             return $this->_scalarizr;
         case 'scalarizrUpdateClient':
             $this->_scalarizrUpdateClient = new Scalr_Net_Scalarizr_UpdateClient($this->__getDBServer(), $this->getPort(self::PORT_UPDC), \Scalr::config('scalr.system.instances_connection_timeout'));
             return $this->_scalarizrUpdateClient;
         default:
             return parent::__get($name);
     }
 }
Esempio n. 17
0
 /**
  * {@inheritdoc}
  *
  * @see Scalr\Model\AbstractEntity::delete()
  *
  */
 public function delete()
 {
     $cnt = $this->db()->GetOne("SELECT COUNT(*) FROM apache_vhosts WHERE ssl_cert_id = ?", [$this->id]);
     if ($cnt > 0) {
         throw new ModelException(sprintf('Certificate "%s" is used by %s apache virtual host(s)', $this->name, $cnt));
     }
     parent::delete();
 }
Esempio n. 18
0
 /**
  * Creates and save entity to DB, keeps entity to delete after test
  *
  * @param AbstractEntity $entity       Entity instance
  * @param array          $data         Properties to initialize
  * @param array          $requiredData The list of names properties which should be save and initialize after delete
  * @return AbstractEntity
  * @throws \Scalr\Exception\ModelException
  */
 public static function createEntity(AbstractEntity $entity, array $data, array $requiredData = null)
 {
     if (!empty($data)) {
         $it = $entity->getIterator();
         foreach ($data as $prop => $value) {
             if ($it->getField($prop)) {
                 $entity->{$prop} = $value;
             } else {
                 throw new InvalidArgumentException(sprintf("Field %s does not exist in %s entity.", $prop, get_class($entity)));
             }
         }
     }
     $initProperties = [];
     if (!empty($requiredData)) {
         foreach ($requiredData as $prop) {
             if (isset($data[$prop])) {
                 $initProperties[$prop] = $data[$prop];
             } else {
                 throw new InvalidArgumentException(sprintf("Field %s does not exist in data.", $prop));
             }
         }
     }
     $entity->save();
     $key = [];
     foreach ($entity->getIterator()->getPrimaryKey() as $position => $property) {
         $key[$position] = $entity->{$property};
     }
     static::toDelete(get_class($entity), $key, $initProperties);
     return $entity;
 }
Esempio n. 19
0
 /**
  * {@inheritdoc}
  * @see AbstractEntity::delete()
  */
 public function delete()
 {
     $db = $this->db();
     try {
         $db->BeginTrans();
         // We need to perpetuate server_properties records for removed servers
         $db->Execute("DELETE FROM messages WHERE server_id=?", [$this->serverId]);
         $db->Execute("\n                UPDATE `dm_deployment_tasks` SET status=? WHERE server_id=?\n            ", [\Scalr_Dm_DeploymentTask::STATUS_ARCHIVED, $this->serverId]);
         $db->Execute("DELETE FROM `server_properties` WHERE `server_id` = ? AND `name` NOT IN (" . implode(", ", array_map([$db, "qstr"], self::getImportantPropertyList())) . ")", [$this->serverId]);
         $db->CommitTrans();
     } catch (Exception $e) {
         $db->RollbackTrans();
         throw $e;
     }
     parent::delete();
 }
Esempio n. 20
0
File: Team.php Progetto: scalr/scalr
 /**
  * {@inheritdoc}
  * @see AbstractEntity::delete()
  */
 public function delete()
 {
     parent::delete();
     TeamEnvs::deleteByTeamId($this->id);
     TeamUser::deleteByTeamId($this->id);
 }
Esempio n. 21
0
File: Role.php Progetto: scalr/scalr
 public function save()
 {
     $this->db()->BeginTrans();
     try {
         parent::save();
         $this->db()->Execute("DELETE FROM `role_behaviors` WHERE `role_id` = ?", [$this->id]);
         $sql = $args = [];
         foreach ($this->getBehaviors() as $behavior) {
             $sql[] = '(?, ?)';
             $args = array_merge($args, [$this->id, $behavior]);
         }
         if (count($sql)) {
             $this->db()->Execute("INSERT INTO `role_behaviors` (`role_id`, `behavior`) VALUES " . join(', ', $sql), $args);
         }
         $this->db()->CommitTrans();
     } catch (\Exception $e) {
         $this->db()->RollbackTrans();
         throw $e;
     }
 }
Esempio n. 22
0
 /**
  * {@inheritdoc}
  * @see AbstractEntity::delete()
  */
 public function delete()
 {
     $db = $this->db();
     try {
         $this->terminateServers();
         $db->BeginTrans();
         // Clear farm role options & scripts
         $db->Execute("DELETE FROM farm_role_service_config_presets WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM farm_role_scaling_times WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM farm_role_service_config_presets WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM farm_role_scripting_targets WHERE `target`=? AND `target_type` = 'farmrole'", [$this->id]);
         $db->Execute("DELETE FROM ec2_ebs WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM elastic_ips WHERE farm_roleid=?", [$this->id]);
         $db->Execute("DELETE FROM storage_volumes WHERE farm_roleid=?", [$this->id]);
         // Clear apache vhosts and update DNS zones
         $db->Execute("UPDATE apache_vhosts SET farm_roleid='0', farm_id='0' WHERE farm_roleid=?", [$this->id]);
         $db->Execute("UPDATE dns_zones SET farm_roleid='0' WHERE farm_roleid=?", [$this->id]);
         $this->deleteScheduled();
         $db->Execute("DELETE FROM farm_role_scripts WHERE farm_roleid=?", [$this->id]);
         parent::delete();
         $db->CommitTrans();
     } catch (Exception $e) {
         $db->RollbackTrans();
         throw $e;
     }
 }
Esempio n. 23
0
 /**
  * {@inheritdoc}
  * @see AbstractEntity::delete()
  */
 public function delete()
 {
     EnvironmentCloudCredentials::deleteByCloudCredentialsId($this->id);
     parent::delete();
 }
Esempio n. 24
0
 /**
  * Execute statement
  *
  * @param   AbstractEntity  $entity          Next entity to saving in database
  * @param   string          $type   optional The statement type (see EntityStatement::TYPE_* const)
  *
  * @return  EntityStatement
  * @throws  ModelException
  */
 public function execute(AbstractEntity $entity, $type = null)
 {
     if (!$entity instanceof $this->entityClass) {
         throw new InvalidArgumentException("This statement processes only '{$this->entityClass}' entities!");
     }
     /* @var $entity AbstractEntity */
     $params = [];
     $auto = $entity->getIterator()->getAutogenerated();
     if (empty($type)) {
         $type = isset($auto) && !empty($entity->{$auto->name}) ? static::TYPE_UPDATE : static::TYPE_INSERT;
     }
     switch ($type) {
         case static::TYPE_UPDATE:
             $stmt = $this->updateStmt;
             $fields = $this->updateParams;
             break;
         case static::TYPE_INSERT:
             $stmt = $this->insertStmt;
             $fields = $this->insertParams;
             break;
         case static::TYPE_DELETE:
             $stmt = $this->deleteStmt;
             $fields = $this->deleteParams;
             break;
         default:
             throw new DomainException("Unknown statement type {$type}");
     }
     foreach ($this->prepare($type, $fields) as $field) {
         if (empty($entity->{$field->name})) {
             $entity->{$field->name} = $field->type->generateValue($entity);
         }
     }
     foreach ($fields as $field) {
         $params[] = $field->type->toDb($entity->{$field->name});
     }
     $this->db->Execute($stmt, $params);
     if (isset($auto)) {
         $entity->{$auto->name} = $auto->type->toPhp($this->db->Insert_ID());
     }
     return $this;
 }
Esempio n. 25
0
 /**
  * {@inheritdoc}
  * @see AbstractEntity::delete()
  */
 public function delete()
 {
     if ($this->status != FARM_STATUS::TERMINATED) {
         throw new FarmInUseException("Cannot delete a running farm, please terminate a farm before deleting it");
     }
     $servers = Server::find([['farmId' => $this->id], ['status' => ['$ne' => Server::STATUS_TERMINATED]]]);
     if (count($servers)) {
         throw new FarmInUseException(sprintf("Cannot delete a running farm, %s server%s still running on this farm", count($servers), count($servers) > 1 ? 's are' : ' is'));
     }
     $db = $this->db();
     try {
         $db->BeginTrans();
         foreach ($this->farmRoles as $farmRole) {
             $farmRole->delete();
         }
         $this->deleteScheduled();
         $db->Execute("DELETE FROM `logentries` WHERE `farmid` = ?", [$this->id]);
         $db->Execute("DELETE FROM `elastic_ips` WHERE `farmid` = ?", [$this->id]);
         $db->Execute("DELETE FROM `events` WHERE `farmid` = ?", [$this->id]);
         $db->Execute("DELETE FROM `ec2_ebs` WHERE `farm_id` = ?", [$this->id]);
         $db->Execute("DELETE FROM `farm_lease_requests` WHERE `farm_id` = ?", [$this->id]);
         foreach ($this->servers as $server) {
             $server->delete();
         }
         $db->Execute("UPDATE `dns_zones` SET `farm_id` = '0', `farm_roleid` ='0' WHERE `farm_id` = ?", [$this->id]);
         $db->Execute("UPDATE `apache_vhosts` SET `farm_id` = '0', `farm_roleid` ='0' WHERE `farm_id` = ?", [$this->id]);
         parent::delete();
         $db->CommitTrans();
     } catch (Exception $e) {
         $db->RollbackTrans();
         throw $e;
     }
     $db->Execute("DELETE FROM `scripting_log` WHERE `farmid` = ?", [$this->id]);
 }
Esempio n. 26
0
 public function save()
 {
     $this->variables = [];
     $variables = Script::fetchVariables($this->content);
     if (!empty($variables)) {
         $builtin = array_keys(\Scalr_Scripting_Manager::getScriptingBuiltinVariables());
         foreach ($variables as $var) {
             if (!in_array($var, $builtin)) {
                 $this->variables[$var] = ucwords(str_replace("_", " ", $var));
             }
         }
     }
     parent::save();
 }
Esempio n. 27
0
 /**
  * Deletes this script
  *
  * @throws Scalr_Exception_Core
  * @throws Exception
  * @throws ModelException
  */
 public function delete()
 {
     // Check script usage
     $usage = [];
     $farmRolesCount = $this->db()->GetOne("SELECT COUNT(DISTINCT farm_roleid) FROM farm_role_scripts WHERE scriptid=?", array($this->id));
     if ($farmRolesCount > 0) {
         $message = [];
         foreach ($this->db()->GetCol("SELECT DISTINCT farm_roleid FROM farm_role_scripts WHERE scriptid = ? LIMIT 3", array($this->id)) as $id) {
             $dbFarmRole = \DBFarmRole::LoadByID($id);
             $message[] = $dbFarmRole->GetFarmObject()->Name . ' (' . $dbFarmRole->Alias . ')';
         }
         $usage[] = sprintf("%d farm roles: %s%s", $farmRolesCount, join(', ', $message), $farmRolesCount > 3 ? ' and others' : '');
     }
     $rolesCount = $this->db()->GetOne("SELECT COUNT(DISTINCT role_id) FROM role_scripts WHERE script_id=?", array($this->id));
     if ($rolesCount > 0) {
         $message = [];
         foreach ($this->db()->GetCol("SELECT DISTINCT role_id FROM role_scripts WHERE script_id = ? LIMIT 3", array($this->id)) as $id) {
             $dbRole = \DBRole::LoadByID($id);
             $message[] = $dbRole->name;
         }
         $usage[] = sprintf("%d roles: %s%s", $rolesCount, join(', ', $message), $rolesCount > 3 ? ' and others' : '');
     }
     $accountCount = $this->db()->GetOne("SELECT COUNT(*) FROM account_scripts WHERE script_id=?", array($this->id));
     if ($accountCount > 0) {
         $usage[] = sprintf("%d orchestration rule(s) on account level", $accountCount);
     }
     $taskCount = $this->db()->GetOne("SELECT COUNT(*) FROM scheduler WHERE script_id = ?", array($this->id));
     if ($taskCount > 0) {
         $usage[] = sprintf("%d scheduler task(s)", $taskCount);
     }
     if (count($usage)) {
         throw new Scalr_Exception_Core(sprintf('Script "%s" being used by %s, and can\'t be deleted', $this->name, join(', ', $usage)));
     }
     Tag::deleteTags(Tag::RESOURCE_SCRIPT, $this->id);
     parent::delete();
 }
Esempio n. 28
0
 /**
  * {@inheritdoc}
  * @see AbstractEntity::delete()
  */
 public function delete()
 {
     parent::delete();
     if (ScalingMetric::METRIC_DATE_AND_TIME_ID === $this->metricId) {
         FarmRoleScalingTime::deleteByFarmRoleId($this->farmRoleId);
     }
 }
Esempio n. 29
0
 public function save()
 {
     if ($this->platform == \SERVER_PLATFORMS::GCE || $this->platform == \SERVER_PLATFORMS::AZURE) {
         $this->cloudLocation = '';
     }
     // image on GCE or Azure doesn't require cloudLocation
     parent::save();
 }
Esempio n. 30
0
 /**
  * {@inheritdoc}
  * @see \Scalr\Model\AbstractEntity::delete()
  */
 public function delete()
 {
     if ($this->checkRemoval()) {
         //Completely remove it
         parent::delete();
         ReportEntity::deleteBy([['subjectId' => $this->projectId], ['subjectType' => ReportEntity::SUBJECT_TYPE_PROJECT]]);
         NotificationEntity::deleteBy([['subjectId' => $this->projectId], ['subjectType' => NotificationEntity::SUBJECT_TYPE_PROJECT]]);
     } else {
         //Archive it
         $this->archived = true;
         $this->save();
     }
 }