/** * Create a new instance record * * @param string $instanceName * @param array $options Array of options for creation. Options are: * * owner-id The id of the instance owner * cluster-id The cluster that owns this instance * trial If true, the "trial" flagged is set for the instance * * @return Instance * @throws DuplicateInstanceException * @throws ProvisioningException */ public function make($instanceName, $options = []) { try { // Basic checks... if (null === ($_ownerId = array_get($options, 'owner-id'))) { throw new \InvalidArgumentException('No "owner-id" given. Cannot create instance.'); } if (null == ($_ownerType = array_get($options, 'owner-type'))) { $_ownerType = OwnerTypes::USER; } try { $_owner = OwnerTypes::getOwner($_ownerId, $_ownerType); } catch (ModelNotFoundException $_ex) { throw new \InvalidArgumentException('The "owner-id" and/or "owner-type" specified is/are invalid.'); } //$this->debug('owner validated: ' . $_owner->id . ($_owner->admin_ind ? ' (admin)' : ' (non-admin)')); if (false === ($_sanitized = Instance::isNameAvailable($instanceName, $_owner->admin_ind))) { throw new DuplicateInstanceException('The instance name "' . $instanceName . '" is not available.'); } // Get the proper location $_guestLocation = array_get($options, 'guest-location', config('provisioning.default-guest-location')); // Validate the cluster and pull component ids $_clusterId = array_get($options, 'cluster-id', config('provisioning.default-cluster-id')); $_clusterConfig = $this->getServersForCluster($_clusterId); $_ownerId = $_owner->id; $_attributes = ['user_id' => (int) $_ownerId, 'instance_id_text' => $_sanitized, 'instance_name_text' => $_sanitized, 'guest_location_nbr' => $_guestLocation, 'cluster_id' => (int) $_clusterConfig['cluster-id'], 'db_server_id' => (int) $_clusterConfig['db-server-id'], 'app_server_id' => (int) $_clusterConfig['app-server-id'], 'web_server_id' => (int) $_clusterConfig['web-server-id'], 'state_nbr' => ProvisionStates::CREATED]; $_guestAttributes = ['instance_id' => null, 'vendor_id' => $_guestLocation, 'vendor_image_id' => array_get($options, 'vendor-image-id', config('provisioning.default-vendor-image-id')), 'vendor_credentials_id' => array_get($options, 'vendor-credentials-id', config('provisioning.default-vendor-credentials-id'))]; // Write it out return \DB::transaction(function () use($_ownerId, $_attributes, $_guestAttributes) { $_instance = Instance::create($_attributes); //$this->debug('created instance row id#' . $_instance->id); $_guestAttributes['instance_id'] = $_instance->id; $_guest = InstanceGuest::create($_guestAttributes); //$this->debug('created guest row id#' . $_guest->id); if (!$_instance || !$_guest) { throw new \RuntimeException('Instance creation failed'); } return $_instance; }); } catch (\Exception $_ex) { throw new ProvisioningException('Error creating new instance: ' . $_ex->getMessage()); } }