-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathStaticInstaller.php
More file actions
531 lines (479 loc) · 20.4 KB
/
StaticInstaller.php
File metadata and controls
531 lines (479 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
<?php
namespace axenox\PackageManager;
use Composer\Installer\PackageEvent;
use exface\Core\CommonLogic\Workbench;
use Composer\Script\Event;
use exface\Core\Factories\AppFactory;
use exface\Core\Interfaces\Exceptions\ExceptionInterface;
use exface\Core\CommonLogic\Selectors\AppSelector;
use exface\Core\Factories\ActionFactory;
use axenox\PackageManager\Actions\ListApps;
use exface\Core\Interfaces\WorkbenchInterface;
/**
* The static installer allows Composer (or anything else outside of the Workbench) to launch app installers.
*
* The following methods are run on composer events. Thy are registered as composer scripts.
*
* - `StaticInstaller::composerFinishInstall()`
* - `StaticInstaller::composerFinishUpdate()`
* - `StaticInstaller::composerFinishPackageInstall()`
* - `StaticInstaller::composerFinishPackageUpdate()`
* - `StaticInstaller::composerPrepareUninstall()`
*
* By default, this installer will initialize a new Workbench before running installers for each app. However, this
* might cause rare side effects, so you can opt for a global workbench instance for all apps by setting
* `COMPOSER.USE_NEW_WORKBENCH_FOR_EVERY_APP` to FALSE in `config/axenox.PackageManager.config.json` in your
* installation folder.
*
* For example, when using a remote MS SQL database for the metamodel, the installer of the second app being
* installed might just hang because the MS SQL connector cannot establish a new connection to the DB. If this happens,
* use a global workbench here to make every app use the same DB connection.
*
* @author Andrej Kabachnik
*
*/
class StaticInstaller
{
const PACKAGE_MANAGER_APP_ALIAS = 'axenox.PackageManager';
const PACKAGE_MANAGER_INSTALL_ACTION_ALIAS = 'axenox.PackageManager.InstallApp';
const PACKAGE_MANAGER_BACKUP_ACTION_ALIAS = 'axenox.PackageManager.BackupApp';
const PACKAGE_MANAGER_UNINSTALL_ACTION_ALIAS = 'axenox.PackageManager.UninstallApp';
const PACAKGE_MANAGER_GENERATE_LIC_BOM_ALIAS = 'axenox.PackageManager.GenerateLicenseBOM';
private $workbench = null;
private static $globalWorkbench = null;
/**
*
* @param PackageEvent $composer_event
* @return void
*/
public static function composerFinishPackageInstall(PackageEvent $composer_event)
{
static::init();
$app_alias = self::composerGetAppAliasFromExtras($composer_event->getOperation()->getPackage()->getExtra());
if ($app_alias) {
self::addAppToTempFile('install', $app_alias);
}
}
/**
*
* @param PackageEvent $composer_event
* @return void
*/
public static function composerFinishPackageUpdate(PackageEvent $composer_event)
{
static::init();
$app_alias = self::composerGetAppAliasFromExtras($composer_event->getOperation()->getTargetPackage()->getExtra());
if ($app_alias) {
self::addAppToTempFile('update', $app_alias);
}
}
/**
*
* @param Event $composer_event
* @return string
*/
public static function composerFinishInstall(Event $composer_event = null)
{
static::init();
try {
$result = '';
self::printToStdout('-> Installing "' . self::getCoreAppAlias() . '": ' . PHP_EOL . PHP_EOL);
$result = self::install(self::getCoreAppAlias());
self::printToStdout(($result ? $result : 'Nothing to do') . "." . PHP_EOL);
} catch (\Throwable $e) {
self::printToStdout('FAILED to install "' . self::getCoreAppAlias() . '": ' . $result . "." . PHP_EOL);
self::printException($e);
}
self::printToStdout("Searching for apps in vendor-folder...");
$vendorBase = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..';
$installedAppAliases = ListApps::findAppAliasesInVendorFolders($vendorBase);
self::printToStdout("found " . count($installedAppAliases) . " apps" . PHP_EOL);
foreach ($installedAppAliases as $app_alias) {
self::printToStdout('-> Installing app "' . $app_alias . '": ' . PHP_EOL . PHP_EOL);
$result = self::install($app_alias);
self::printToStdout(($result ? trim($result, ".") : 'Nothing to do') . PHP_EOL);
}
self::setTempFile([]);
self::generateLicenseBOM();
return empty($installedAppAliases) === true ? "No apps to update.\n" : "Installed " . count($installedAppAliases) . " apps.\n";
}
/**
*
* @param Event $composer_event
* @return string
*/
public static function composerFinishUpdate(Event $composer_event = null)
{
static::init();
self::printToStdout("Running installers for newly installed and updated apps...\n");
$processed_aliases = array();
$temp = self::getTempFile();
$appAliases = array_key_exists('update', $temp) ? $temp['update'] : [];
if (array_key_exists('install', $temp) && is_array($temp['install']) === true) {
// If the package manager is being installed for the first time, run
// install instead of update
if (in_array('axenox.PackageManager', $temp['install'])) {
return self::composerFinishInstall($composer_event);
}
$appAliases = array_merge($appAliases, $temp['install']);
}
// Run installers for updated apps
if (empty($appAliases) === false) {
// First of all check, if the core needs to be updated. If so, do that before updating other apps
if (in_array(self::getCoreAppAlias(), $appAliases)) {
if (! in_array(self::getCoreAppAlias(), $processed_aliases)) {
$processed_aliases[] = self::getCoreAppAlias();
self::printToStdout('-> Updating app "' . self::getCoreAppAlias() . '": ' . PHP_EOL . PHP_EOL);
$result = self::install(self::getCoreAppAlias());
self::printToStdout(($result ? $result : 'Nothing to do') . PHP_EOL);
}
}
// Now that the core is up to date, we can update the others
foreach ($appAliases as $app_alias) {
if (! in_array($app_alias, $processed_aliases)) {
$processed_aliases[] = $app_alias;
} else {
continue;
}
self::printToStdout('-> Updating app "' . $app_alias . '": ' . PHP_EOL . PHP_EOL);
$result = self::install($app_alias);
self::printToStdout(($result ? $result : 'Nothing to do') . "." . PHP_EOL);
}
}
if (array_key_exists('update', $temp) && is_array($temp['update'])){
$updatedPackages = $temp['update'];
} else {
$updatedPackages = [];
}
// Cleanup backup
if (array_key_exists('backupTime', $temp)) {
self::printToStdout("Delete unused backup components:" . PHP_EOL);
$installer = new self();
$apps = ListApps::findAppAliasesInModel($installer->getWorkbench());
$backupTime = $temp['backupTime'];
$unlinkResult = array();
foreach($apps as $app){
if (! in_array($app, $updatedPackages)){
$unlinkResult[] = $installer->unlinkBackup($app,$backupTime);
}
}
$installer->copyTempFile($backupTime);
if (!in_array(false,$unlinkResult)){
self::printToStdout("Cleared backup from excess data." . PHP_EOL);
} else {
self::printToStdout("Could not clear backup." . PHP_EOL);
}
}
unset($temp['update']);
unset($temp['install']);
self::setTempFile($temp);
self::generateLicenseBOM();
return empty($processed_aliases) === true ? "No apps to update.\n" : "Updated/installed " . count($processed_aliases) . " apps.\n";
}
/**
* Prepare the environment to run installers
*
* @return void
*/
protected static function init()
{
// Make sure no warnings/notices are thrown because they will break
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED & ~E_USER_DEPRECATED);
// Make sure errors are displayed even if local php.ini hides them (not sure, if this will really
// help because it will not affect fatal errors according to PHP documentation)
ini_set('display_errors', 1);
}
/**
* Unlink backup from specified backup folder, folder name is defined by backupTime-String
*
* @param string $app_alias
* @param string $backupTime
* @return boolean return TRUE if unlinking BackUp was successful, return FALSE if it was not
*/
public function unlinkBackup($app_alias, $backupTime){
$exface = $this->getWorkbench();
$app = $exface->getApp(self::PACKAGE_MANAGER_APP_ALIAS);
try {
$link = $exface->filemanager()->getPathToBackupFolder().DIRECTORY_SEPARATOR."autobackup".DIRECTORY_SEPARATOR.$backupTime.DIRECTORY_SEPARATOR.str_replace(".",DIRECTORY_SEPARATOR,$app_alias);
if ($exface->filemanager()->exists($link)){
$exface->filemanager()->deleteDir($link);
// Delete Parent folders to avoid clutter, provided that they are in fact empty
$parentLink = explode(".",$app_alias);
$parentLink = $app->getWorkbench()->filemanager()->getPathToBackupFolder().DIRECTORY_SEPARATOR."autobackup".DIRECTORY_SEPARATOR.$backupTime.DIRECTORY_SEPARATOR.$parentLink[0].DIRECTORY_SEPARATOR;
if ($exface->filemanager()->isDirEmpty($parentLink)){
$exface->filemanager()->deleteDir($parentLink);
}
self::printToStdout('-> '.$app_alias. "Delete unused backups" . PHP_EOL);
}
else {
$text = '-> '.$app_alias. " - Directory can't be found at ".$link.". Check your database for old app definitions that have since been uninstalled.\n\n";
self::printToStdout($text);
}
} catch (\Throwable $e){
static::printException($e);
$exface->getLogger()->logException($e);
return false;
}
return true;
}
/**
* Backup all apps
* since they have no own backup function to call to
*
* @param Event $composer_event
* @return Event $composer_event
*/
public static function composerBackupEverything(Event $composer_event = null){
static::init();
$installer = new self();
$apps = ListApps::findAppAliasesInModel($installer->getWorkbench());
//write consistent backuptime to delete excess data after update run
$backupTime = date('Y_m_d_H_i');
$temp = self::getTempFile();
$temp['backupTime'] = $backupTime;
self::setTempFile($temp);
$backupPath = $installer->getWorkbench()->filemanager()->getPathToBackupFolder();
$backupPath = "autobackup".DIRECTORY_SEPARATOR.$backupTime;
self::printToStdout("Starting automatic backup to ".$backupPath);
foreach($apps as $app){
$installer->backup($app, $backupPath);
}
return $backupPath;
}
/**
* Call backup function on app, install at specified backup folder, folder name is defined by backupTime-String
* @param string $app_alias
* @param string $backupTime
* @return string
*/
public function backup($app_alias, $backupPath){
$exface = $this->getWorkbench();
$text = "-> {$app_alias} being backed up to {$backupPath}...";
try {
self::printToStdout($text);
$app_selector = new AppSelector($exface, $app_alias);
$backupAction = ActionFactory::createFromString($exface, self::PACKAGE_MANAGER_BACKUP_ACTION_ALIAS);
$backupDir = $exface->filemanager()->getPathToBaseFolder();
$backupDir .= DIRECTORY_SEPARATOR . "vendor" . DIRECTORY_SEPARATOR. str_replace(".",DIRECTORY_SEPARATOR,$app_alias);
if ($exface->filemanager()->exists($backupDir)){
$backupAction->setBackupPath($backupPath);
$backupAction->backup($app_selector);
$text .= " DONE!";
}
else {
$text .= ' SKIPPED - app not installed correctly?';
$exface->getLogger()->error("No folder for app {$app_alias} can be found at {$backupDir}. Check your database for old app definitions that have since been uninstalled.");
}
self::printToStdout($text);
} catch (\Throwable $e){
$text .= ' FAILED!';
self::printToStdout($text);
self::printException($e);
$exface->getLogger()->logException($e);
}
return $text;
}
public static function composerPrepareUninstall(PackageEvent $composer_event)
{
return self::uninstall($composer_event->getOperation()->getPackage()->getName());
}
protected static function composerGetAppAliasFromExtras($extras_array)
{
static::init();
if (is_array($extras_array) && array_key_exists('app', $extras_array) && is_array($extras_array['app']) && array_key_exists('app_alias', $extras_array['app'])) {
return $extras_array['app']['app_alias'];
}
return false;
}
public static function install($app_alias)
{
$installer = new self();
return $installer->installApp($app_alias);
}
public static function uninstall($app_alias)
{
static::init();
// TODO
}
public function installApp($app_alias)
{
$result = '';
try {
$exface = $this->getWorkbench();
$app_selector = new AppSelector($exface, $app_alias);
$action = ActionFactory::createFromString($exface, self::PACKAGE_MANAGER_INSTALL_ACTION_ALIAS);
$installerResult = $action->installApp($app_selector);
foreach ($installerResult as $msg) {
$result .= $msg;
}
} catch (\Throwable $e) {
$result = 'FAILED - ' . $e->getMessage() . '!';
$this::printToStdout('FAILED installing ' . $app_alias . '!');
$this::printException($e);
if ($exface !== null) {
$exface->getLogger()->logException($e);
}
}
return $result;
}
public function uninstallApp($app_alias)
{
$result = '';
try {
$exface = $this->getWorkbench();
$app_selector = new AppSelector($exface, $app_alias);
$action = ActionFactory::createFromString($exface, self::PACKAGE_MANAGER_INSTALL_ACTION_ALIAS);
$result = $action->uninstall($app_selector);
} catch (\Throwable $e) {
$result = 'FAILED - ' . $e->getMessage() . '!';
$this::printToStdout('FAILED uninstalling ' . $app_alias . '!');
$this::printException($e);
if ($exface !== null) {
$exface->getLogger()->logException($e);
}
}
return $result;
}
/**
*
* @return Workbench
*/
public function getWorkbench() : WorkbenchInterface
{
if (static::$globalWorkbench !== null) {
return static::$globalWorkbench;
}
$this->importSources();
if (is_null($this->workbench)) {
static::init();
try {
$this::printToStdout('Starting new workbench instance');
$this->workbench = Workbench::startNewInstance();
try {
$thisApp = AppFactory::createFromAlias('axenox.PackageManager', $this->workbench);
$config = $thisApp->getConfig();
if ($config->getOption('COMPOSER.USE_NEW_WORKBENCH_FOR_EVERY_APP') === false) {
$this::printToStdout(' - using this workbench globally' . PHP_EOL);
static::$globalWorkbench = $this->workbench;
} else {
$this::printToStdout(' - it will be used for this app only' . PHP_EOL);
}
} catch (\Throwable $e) {
$this::printException($e);
$this::printToStdout('Cannot read configuration "COMPOSER.USE_NEW_WORKBENCH_FOR_EVERY_APP" - using new workbench for every app by default.' . PHP_EOL);
}
} catch (\Throwable $e) {
$this::printToStdout('FAILED to start workbench!' . PHP_EOL);
$this::printException($e);
try {
$workbench = new Workbench();
$workbench->getLogger()->logException($e);
return $workbench;
} catch (\Throwable $e2) {
$this::printToStdout('FAILED to start logger!');
$this::printException($e2);
}
}
}
return $this->workbench;
}
public static function generateLicenseBOM()
{
$installer = new self();
try {
$exface = $installer->getWorkbench();
$action = ActionFactory::createFromString($exface, self::PACAKGE_MANAGER_GENERATE_LIC_BOM_ALIAS);
self::printToStdout('Generating license BOM' . PHP_EOL . PHP_EOL);
foreach ($action->generateMarkdownBOM() as $output) {
self::printToStdout($output);
}
} catch (\Throwable $e) {
$installer::printToStdout('FAILED generating license BOM!');
$installer::printException($e);
if ($exface !== null) {
$exface->getLogger()->logException($e);
} else {
$installer::printToStdout('Cannot log error: workbench not available!');
}
}
}
protected static function getTempFilePathAbsolute()
{
return dirname(__FILE__) . DIRECTORY_SEPARATOR . 'LastInstall.temp.json';
}
protected function copyTempFile($backuptime){
$exface = $this->getWorkbench();
$exface->filemanager()->copy(self::getTempFilePathAbsolute(),$exface->filemanager()->getPathToBaseFolder().DIRECTORY_SEPARATOR."autobackup".DIRECTORY_SEPARATOR.$backuptime.DIRECTORY_SEPARATOR."LastInstall.json");
}
/**
*
* @return array
*/
protected static function getTempFile()
{
$json_array = array();
$filename = self::getTempFilePathAbsolute();
if (file_exists($filename)) {
$json_array = json_decode(file_get_contents($filename), true);
}
return $json_array;
}
/**
*
* @param array $json_array
*/
protected static function setTempFile(array $json_array)
{
if (count($json_array) > 0) {
return file_put_contents(self::getTempFilePathAbsolute(), json_encode($json_array, JSON_PRETTY_PRINT));
} elseif (file_exists(self::getTempFilePathAbsolute())) {
return unlink(self::getTempFilePathAbsolute());
}
}
/**
*
* @param string $operation
* @param string $app_alias
* @return array
*/
protected static function addAppToTempFile($operation, $app_alias)
{
$temp_file = self::getTempFile();
$temp_file[$operation][] = $app_alias;
self::setTempFile($temp_file);
return $temp_file;
}
protected static function printToStdout($text)
{
if (defined('STDOUT') === true && is_resource(STDOUT) === true) {
fwrite(STDOUT, $text);
return true;
} else {
echo $text;
}
}
protected static function printException(\Throwable $e, $prefix = 'ERROR ')
{
if ($e instanceof ExceptionInterface){
$log_hint = 'See log ID ' . $e->getId();
}
self::printToStdout(PHP_EOL . PHP_EOL . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine() . PHP_EOL . "-> " . $log_hint . PHP_EOL);
if ($p = $e->getPrevious()) {
self::printException($p);
}
}
public static function getCoreAppAlias()
{
return 'exface.Core';
}
protected static function importSources()
{
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR
. '..' . DIRECTORY_SEPARATOR
. 'exface' . DIRECTORY_SEPARATOR
. 'core' . DIRECTORY_SEPARATOR
. 'CommonLogic' . DIRECTORY_SEPARATOR
. 'Workbench.php';
}
}