/** * @param Application $app */ protected function bootstrapDreamFactory($app) { // Get an instance of the cluster service $app->register(new ClusterServiceProvider($app)); /** @type ClusterService $_cluster */ $_cluster = ClusterServiceProvider::service($app); $_vars = ['DF_CACHE_PREFIX' => $_cluster->getCachePrefix(), 'DF_CACHE_PATH' => $_cluster->getCachePath(), 'DF_LIMITS_CACHE_STORE' => ManagedDefaults::DEFAULT_LIMITS_STORE, 'DF_LIMITS_CACHE_PATH' => Disk::path([$_cluster->getCacheRoot(), '.limits'], true), 'DF_MANAGED_SESSION_PATH' => Disk::path([$_cluster->getCacheRoot(), '.sessions'], true), 'DF_MANAGED_LOG_FILE' => $_cluster->getHostName() . '.log', 'DF_MANAGED' => true, 'DB_DRIVER' => 'mysql']; // Get the cluster database information foreach ($_cluster->getDatabaseConfig() as $_key => $_value) { $_vars['DB_' . strtr(strtoupper($_key), '-', '_')] = $_value; } // Throw in some paths if (!empty($_paths = $_cluster->getConfig('paths', []))) { foreach ($_paths as $_key => $_value) { $_vars['DF_MANAGED_' . strtr(strtoupper($_key), '-', '_')] = $_value; } } // If this is a console request, denote it as such $_vars['DF_CONSOLE_KEY'] = $_cluster->getConsoleKey(); // Is it a console request? Validate /** @type Request $_request */ $_request = $app->make('request'); $_vars['DF_IS_VALID_CONSOLE_REQUEST'] = $_vars['DF_CONSOLE_KEY'] == $_request->header(ManagedDefaults::CONSOLE_X_HEADER, $_request->query('console_key')); // Now jam everything into the environment foreach ($_vars as $_key => $_value) { putenv($_key . '=' . $_value); $_ENV[$_key] = $_value; $_SERVER[$_key] = $_value; } // Finally, let the cluster service push some middleware onto the stack if ($_cluster instanceof HasMiddleware) { $_cluster->pushMiddleware($app->make('Illuminate\\Contracts\\Http\\Kernel')); } }
/** * Tests update request * * @covers \DreamFactory\Enterprise\Console\Commands\Mount::fire() */ public function testCreate() { $_path = Disk::path([dirname(dirname(__DIR__)), 'storage', 'mount-test'], true); $this->arguments['operation'] = 'create'; $this->arguments['mount-id'] = 'mount-test-' . date('YmdHis'); $this->options['--mount-type'] = 'LOCAL'; $this->options['--root-path'] = $_path; /** @noinspection PhpUndefinedMethodInspection */ $_result = Artisan::call('dfe:setup', ['--force' => true, '--admin-password' => 'password', 'admin-email' => '*****@*****.**']); $this->assertEquals(0, $_result); }
/** * @param string|null $append */ protected function setWorkPath($append = null) { $this->workPath = Disk::path([config('provisioning.storage-root'), $append]) . DIRECTORY_SEPARATOR; }
/** * @return bool */ protected function _backupServiceUsers() { $_backupPath = base_path() . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'dfe'; if (!Disk::ensurePath($_backupPath)) { $this->writeln('Unable to write to backup path <comment>' . $_backupPath . '</comment>. Aborting.', 'error'); return false; } $_users = []; /** @type ServiceUser $_user */ foreach (ServiceUser::all() as $_user) { $_users[] = $_user->toArray(); } JsonFile::encodeFile($_backupPath . DIRECTORY_SEPARATOR . 'service-user.backup.' . date('YmdHis') . '.json', $_users); return true; }
/** * Returns the mount to the snapshot itself if it exists here otherwise returns mount to user's snapshot path * * @return \League\Flysystem\Filesystem|null */ public function getMount() { if ($this->user) { if (!is_dir($_path = $this->user->getSnapshotPath())) { return $this->user->getSnapshotMount(); } if (file_exists($_file = Disk::segment([$_path, $this->snapshot_id_text . '.snapshot.zip'], true))) { return new Filesystem(new ZipArchiveAdapter($_file)); } } return null; }
/** * Deletes a previously made work path * * @param string $tag Unique identifier for temp space * * @return bool */ protected static function deleteWorkPath($tag) { $_root = Disk::path([sys_get_temp_dir(), 'dfe', $tag]); return is_dir($_root) ? Disk::rmdir($_root, true) : true; }
/** * Called after form has been submitted. This prepares collected data for writing to * source files and sets the member variable $formData * * @param array $formData * * @return $this */ public function setFormData(array $formData = []) { $_facterData = ['INSTALLER_FACTS' => 1]; $_cleanData = []; if (empty($formData) || count($formData) < 5) { /** @noinspection PhpUndefinedMethodInspection */ Session::flash('failure', 'Not all required fields were completed.'); /** @noinspection PhpUndefinedMethodInspection */ Log::error('Invalid number of post entries: ' . print_r($formData, true)); /** @noinspection PhpUndefinedMethodInspection */ Redirect::home(); } // Remove CSRF token array_forget($formData, '_token'); // Add in things that don't exist in form... $formData['dc-es-exists'] = array_key_exists('dc-es-exists', $formData) ? 'true' : 'false'; $formData['dc-es-cluster'] = array_get($formData, 'dc-es-cluster', $this->defaults['dc_es_cluster']); $formData['dc-es-port'] = array_get($formData, 'dc-es-port', $this->defaults['dc_es_port']); $formData['dc-port'] = array_get($formData, 'dc-port', $this->defaults['dc_port']); $formData['dc-client-port'] = array_get($formData, 'dc-client-port', $this->defaults['dc_client_port']); // Check for non-existent host name if (empty(array_get($formData, 'dc-host'))) { $formData['dc-host'] = implode('.', [$this->defaults['console_host_name'], trim(array_get($formData, 'vendor-id')), trim(array_get($formData, 'domain'))]); } // Clean up the keys for factering foreach ($formData as $_key => $_value) { $_value = trim($_value); $_cleanKey = trim(str_replace('-', '_', $_key)); // Clean up any diabolical leading slashes on values switch ($_cleanKey) { case 'storage_path': $_storagePath = $_value = trim($_value, DIRECTORY_SEPARATOR); break; case 'mount_point': $_mountPoint = $_value = rtrim($_value, DIRECTORY_SEPARATOR); break; case 'dc_host': // Copy DC host to DC client host $_facterData['export FACTER_DC_CLIENT_HOST'] = $_value; break; } // Dump non-empties into the source file if (null !== $_value) { $_facterData['export FACTER_' . strtoupper($_cleanKey)] = $_value; } // Keep a pristine copy $_cleanData[$_cleanKey] = $_value; // Save cleaned value, if any $formData[$_key] = $_value; unset($_cleanKey, $_key, $_value); } // If set have a storage and mount, construct a storage path if (!empty($_storagePath) && !empty($_mountPoint)) { $_cleanData['storage_mount_point'] = $_facterData['export FACTER_STORAGE_MOUNT_POINT'] = Disk::path([$_mountPoint, $_storagePath]); } $this->formData = $formData; $this->cleanData = $_cleanData; $this->facterData = $_facterData; logger('Form data set: ' . print_r($this->formData, true)); logger('Clean data set: ' . print_r($this->cleanData, true)); logger('Facter data set: ' . print_r($this->facterData, true)); return $this; }
/** * @param bool $leading If true, a leading $separator is pre-pended to result * @param string $separator The separator between map parts * * @return array */ protected function resolvePathFromMap($leading = true, $separator = DIRECTORY_SEPARATOR) { return Disk::segment(array_only($this->map, ['zone', 'partition', 'root-hash']), $leading, $separator); }
/** * Commits a blueprint to the repo * * @param string $instanceId * @param array $blueprint * * @return bool */ protected function commitBlueprint($instanceId, $blueprint) { // Create/update the file $_file = Disk::path([$this->repoPath, $instanceId . '.json']); JsonFile::encodeFile($_file, $blueprint, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); // Commit it $_commitMessage = 'Blueprint for instance "' . $instanceId . '" created on ' . date('Y-m-d H:i:s'); $_response = \Event::fire('dfe.blueprint.pre-commit', ['instance-id' => $instanceId, 'blueprint' => $blueprint, 'repository-path' => $this->repoPath, 'commit-message' => $_commitMessage]); // See if the commit message has changed... if (!empty($_response) && null !== ($_message = array_get($_response, 'commit-message'))) { $_commitMessage = $_message; } if (0 !== $this->git->commitChange($_file, $_commitMessage)) { \Log::error('Error committing blueprint file "' . $_file . '".'); return false; } \Event::fire('dfe.blueprint.post-commit', ['instance-id' => $instanceId, 'blueprint' => $blueprint, 'repository-path' => $this->repoPath]); return true; }
/** * Generates a capsule path optionally ensuring * * @param bool $create * @param int $mode * @param bool $recursive * * @return string */ public function makeCapsulePath($create = false, $mode = 0777, $recursive = true) { return Disk::path([$this->capsuleRootPath, $this->id], $create, $mode, $recursive); }
/** * @param string|array|null $append * @param bool|true $create * @param int $mode * @param bool|true $recursive * * @return string */ public function getOwnerPrivatePath($append = null, $create = true, $mode = 0777, $recursive = true) { InstanceStorage::buildStorageMap($this->storage_id_text); return Disk::path([config('provisioning.storage-root', EnterpriseDefaults::STORAGE_ROOT), InstanceStorage::getStorageRootPath(), InstanceStorage::getPrivatePathName(), $append], $create, $mode, $recursive); }
/** @inheritdoc */ public function import($request) { /** @type \ZipArchive $_archive */ $_archive = null; $_from = null; $_instance = $request->getInstance(); $this->info('[provisioning:database:import] instance "' . $_instance->instance_id_text . '" begin'); // Grab the target (zip archive) and pull out the target of the import $_zip = $request->getTarget(); /** @noinspection PhpUndefinedMethodInspection */ $_archive = $_zip->getAdapter()->getArchive(); foreach ($_zip->listContents() as $_file) { if ('dir' != $_file['type'] && false !== strpos($_file['path'], '.database.sql')) { $_path = Disk::segment([sys_get_temp_dir(), 'dfe', 'import', sha1($_file['path'])], true); if (!$_archive->extractTo($_path, $_file['path'])) { throw new \RuntimeException('Unable to unzip archive file "' . $_file['path'] . '" from snapshot.'); } $_from = Disk::path([$_path, $_file['path']], false); if (!$_from || !file_exists($_from)) { throw new \InvalidArgumentException('$from file "' . $_file['path'] . '" missing or unreadable.'); } break; } } /** @type Connection $_db */ list($_db, $_rootConfig, $_rootServer) = $this->getRootDatabaseConnection($_instance); $this->dropDatabase($_db, $_instance->db_name_text); $this->createDatabase($_db, ['database' => $_instance->db_name_text]); $_results = $this->loadSqlDump($_instance, $_from, $_rootConfig); // Clean up temp space... unlink($_from); // Fire off a "database.imported" event... \Event::fire('dfe.database.imported', [$this, $request]); $this->info('[provisioning:database:import] instance "' . $_instance->instance_id_text . '" complete'); return $_results; }
/** @inheritdoc */ public function import($request) { $_from = null; $_instance = $request->getInstance(); $_mount = $_instance->getStorageMount(); $this->info('[provisioning:storage:import] instance "' . $_instance->instance_id_text . '" begin'); // Grab the target (zip archive) and pull out the target of the import $_zip = $request->getTarget(); /** @var \ZipArchive $_archive */ /** @noinspection PhpUndefinedMethodInspection */ $_archive = $_zip->getAdapter()->getArchive(); $_path = null; foreach ($_zip->listContents() as $_file) { if ('dir' != $_file['type'] && false !== strpos($_file['path'], '.storage.zip')) { $_from = Disk::segment([sys_get_temp_dir(), 'dfe', 'import', sha1($_file['path'])], true); if (!$_archive->extractTo($_from, $_file['path'])) { throw new \RuntimeException('Unable to unzip archive file "' . $_file['path'] . '" from snapshot.'); } $_path = Disk::path([$_from, $_file['path']], false); if (!$_path || !file_exists($_path)) { throw new \InvalidArgumentException('$from file "' . $_file['path'] . '" missing or unreadable.'); } $_from = new Filesystem(new ZipArchiveAdapter($_path)); break; } } if (!$_mount instanceof Filesystem) { $_mount = new Filesystem(new ZipArchiveAdapter($_mount)); } // If "clean" == true, storage is wiped clean before restore if (true === $request->get('clean', false)) { $_mount->deleteDir('./'); } // Extract the files $_restored = []; /** @type Filesystem $_archive */ foreach ($_from->listContents() as $_file) { $_filename = $_file['path']; if ('dir' == array_get($_file, 'type')) { $_mount->createDir($_filename); } else { $_mount->writeStream($_filename, $_archive->readStream($_filename)); } $_restored[] = $_file; } unset($_from); $_path && is_dir(dirname($_path)) && Disk::deleteTree(dirname($_path)); // Fire off a "storage.imported" event... \Event::fire('dfe.storage.imported', [$this, $request]); $this->info('[provisioning:storage:import] instance "' . $_instance->instance_id_text . '" complete'); return $_restored; }
/** @inheritdoc */ public function setRepositoryPath($repositoryPath) { if (!empty($repositoryPath)) { $this->setExecutionPath(realpath(Disk::path([$this->repositoryBasePath, $this->repositoryPath = $repositoryPath], true))); } return $this; }
/** * @param string $file Absolute path to our file * * @return bool|int */ protected static function backupExistingFile($file) { static $_template = '{file}.{date}.save'; if (!static::$makeBackups || !file_exists($file)) { return true; } if (!Disk::ensurePath($_path = dirname($file))) { throw new \RuntimeException('Unable to create file "' . $file . '"'); } return file_put_contents(str_replace(['{file}', '{date}'], [basename($file), date('YmdHiS')], $_template), file_get_contents($file)); }
/** * Returns cache root * * @return string */ public function getCacheRoot() { return env('DF_MANAGED_CACHE_PATH', $this->getConfig('cache-root', Disk::path([sys_get_temp_dir(), '.df-cache']))); }
/** * @param string $basePath The application base path * @param ProvidesCapsulePattern $pattern The capsule pattern * * @return \Illuminate\Foundation\Application */ protected function bootstrapPattern($basePath, $pattern) { // Get the app's autoloader /** @noinspection PhpIncludeInspection */ require Disk::path([$basePath, 'vendor', 'autoload.php']); // Create the application $_app = new Application($basePath); $_app->useEnvironmentPath($basePath); foreach ($pattern as $_abstract => $_concrete) { $_app->singleton($_abstract, $_concrete); } // Set up logging $_app->configureMonologUsing(function (Logger $monolog) { $_logFile = Disk::path([env('DFE_CAPSULE_LOG_PATH', storage_path('logs')), $this->instanceId . '.log']); $_handler = new StreamHandler($_logFile); $_handler->setFormatter(new LineFormatter(null, null, true, true)); $monolog->pushHandler($_handler); }); $this->basePath = $basePath; return $this->app = $_app; }