Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathInstall.php
More file actions
351 lines (317 loc) · 11.7 KB
/
Copy pathInstall.php
File metadata and controls
351 lines (317 loc) · 11.7 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
<?php
/**
* -------------------------------------------------------------------------
* Carbon plugin for GLPI
*
* @copyright Copyright (C) 2024-2025 Teclib' and contributors.
* @license https://www.gnu.org/licenses/gpl-3.0.txt GPLv3+
* @link https://github.com/pluginsGLPI/carbon
*
* -------------------------------------------------------------------------
*
* LICENSE
*
* This file is part of Carbon plugin for GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
namespace GlpiPlugin\Carbon;
use Config;
use DBmysql;
use DirectoryIterator;
use Migration;
use Plugin;
use RuntimeException;
class Install
{
/**
* GLPI Migration instance
*
* @var Migration
*/
private Migration $migration;
/**
* Force upgrade from the previous version to the currrent one
*
* @var bool
*/
private bool $force_upgrade = false;
/**
* Version to upgrade from, when upgrade is forced
*
* @var string
*/
private string $force_upgrade_from_version = '';
/**
* Oldest version that can be upgraded
*
* @var string
*/
private const OLDEST_UPGRADABLE_VERSION = '1.0.0';
/**
* Regular expression for semver version : 3 numbers separated wit a dot
*
* @var string
*/
private const SEMVER_REGEX = '\d+\.\d+\.(?:\d+|x)';
public function __construct(Migration $migration)
{
$this->migration = $migration;
}
/**
* Get installed version of the plugin, from database information
*/
public static function detectVersion(): string
{
$version = Config::getConfigurationValue('plugin:carbon', 'dbversion');
if ($version === null) {
return '0.0.0';
}
return $version;
}
/**
* Fresh install of the plugin
*
* @param array $args
* @return bool
*/
public function install(array $args = []): bool
{
/** @var DBmysql $DB */
global $DB;
$dbFile = plugin_carbon_getSchemaPath();
if ($dbFile === null) {
$this->migration->addWarningMessage("Error creating tables : " . $DB->error());
return false;
}
try {
$DB->runFile($dbFile);
} catch (RuntimeException $e) {
$this->migration->addWarningMessage("Error creating tables : " . $e->getMessage());
return false;
}
// Execute all install sub tasks
$install_dir = __DIR__ . '/install/';
$update_scripts = scandir($install_dir);
$migration = $this->migration; // Used in called scripts in for loop
foreach ($update_scripts as $update_script) {
if (preg_match('/\.php$/', $update_script) !== 1) {
continue;
}
require $install_dir . $update_script;
}
Config::setConfigurationValues('plugin:carbon', ['dbversion' => PLUGIN_CARBON_SCHEMA_VERSION]);
return true;
}
/**
* Run an upgrade of the plugin
*
* @param string $from_version previous version of the plugin
* @param array $args arguments given in command line
* @return bool
*/
public function upgrade(string $from_version, array $args = []): bool
{
$oldest_upgradable_version = self::OLDEST_UPGRADABLE_VERSION;
$db_version = Config::getConfigurationValue('plugin:carbon', 'dbversion');
$matches = [];
preg_match('/^(\d+\.\d+\.\d+)/', PLUGIN_CARBON_VERSION, $matches);
$current_version = $matches[1];
if (version_compare($db_version, $current_version) > 0) {
// database more recent than current version
$e = new RuntimeException(sprintf(
'Database of the plugin %s is more recent than the installed version %s.',
$db_version,
$current_version
));
trigger_error($e->getMessage(), E_USER_WARNING);
throw $e;
}
$this->force_upgrade = array_key_exists('force-upgrade', $args);
if ($this->force_upgrade) {
$this->force_upgrade_from_version = PLUGIN_CARBON_VERSION;
if (array_key_exists('version', $args)) {
$this->force_upgrade_from_version = $args['version'];
// Check the version os SEMVER compliant
$regex = '!^' . self::SEMVER_REGEX . '$!';
if (preg_match($regex, $this->force_upgrade_from_version) !== 1) {
$e = new RuntimeException('Invalid start version for upgrade.');
trigger_error($e->getMessage(), E_USER_WARNING);
throw $e;
}
if (version_compare($this->force_upgrade_from_version, $oldest_upgradable_version) < 0) {
$e = new RuntimeException('Upgrade is not supported before ' . $this->force_upgrade_from_version . '.');
trigger_error($e->getMessage(), E_USER_WARNING);
throw $e;
}
}
} else {
if (version_compare($from_version, $oldest_upgradable_version, 'lt')) {
$e = new RuntimeException("Upgrade is not supported before $oldest_upgradable_version!");
trigger_error($e->getMessage(), E_USER_WARNING);
throw $e;
}
}
ini_set("max_execution_time", "0");
$migrations = $this->getMigrationsToDo($from_version);
foreach ($migrations as $file => $data) {
if (!$this->upgradeOneVersion($file, $data, $args)) {
return false;
}
}
// Cherry pick sub tasks to run from fresh install workflow
// Useful to rewrite missing data in DB
$install_dir = __DIR__ . '/install/';
$update_scripts = scandir($install_dir);
$whitelist = [
'init_datasources.php',
];
foreach ($update_scripts as $update_script) {
if (!in_array($update_script, $whitelist)) {
continue;
}
require $install_dir . $update_script;
}
// If no migration was ran, we still set the version to the current one
Config::setConfigurationValues('plugin:carbon', ['dbversion' => PLUGIN_CARBON_SCHEMA_VERSION]);
return true;
}
public function upgradeOneVersion(string $file, array $data, array $args = []): bool
{
$function = $data['function'];
$target_version = $data['target_version'];
include_once($file);
if ($function($this->migration, $args) === false) {
return false;
}
// Set the version to the target one s it is complete
// May be useful if subsequent steps fail and need to run upgrade again, by not running already done steps
Config::setConfigurationValues('plugin:carbon', ['dbversion' => $target_version]);
return true;
}
/**
* Get migrations that have to be ran.
*
* @param string $current_version
*
* @return array
*/
public function getMigrationsToDo(string $current_version): array
{
$pattern = '/^update_(?<source_version>\d+\.\d+\.(?:\d+|x))_to_(?<target_version>\d+\.\d+\.(?:\d+|x))\.php$/';
$plugin_directory = Plugin::getPhpDir('carbon') . '/install/migration';
$migration_iterator = new DirectoryIterator($plugin_directory);
$migrations = [];
foreach ($migration_iterator as $file) {
$versions_matches = [];
if ($file->isDir() || $file->isDot() || preg_match($pattern, $file->getFilename(), $versions_matches) !== 1) {
continue;
}
$operator = '>';
if ($this->force_upgrade) {
$operator .= '=';
$current_version = $this->force_upgrade_from_version;
}
if (version_compare($versions_matches['target_version'], $current_version, $operator)) {
$function = preg_replace(
'/^update_(\d+)\.(\d+)\.(\d+|x)_to_(\d+)\.(\d+)\.(\d+|x)\.php$/',
'update$1$2$3to$4$5$6',
$file->getBasename()
);
$migrations[$file->getPathname()] = [
'function' => $function,
'target_version' => $versions_matches['target_version'],
];
}
}
ksort($migrations, SORT_NATURAL);
return $migrations;
}
/**
* Get or create a carbon intensity source by name
*
* @param string $name Name of the zone
* @param int $fallback_level Is the zone a fallback zone (1) or not (0)
* @param int $is_carbon_intensity_source Does the source provide carbon intensity (1) or not (0)
* @return int ID of the zone
*/
public static function getOrCreateSource(string $name, int $fallback_level = 1, int $is_carbon_intensity_source = 1): int
{
$source = new Source();
$source->getOrCreate([
'fallback_level' => $fallback_level,
'is_carbon_intensity_source' => $is_carbon_intensity_source,
], [
'name' => $name,
]);
if ($source->isNewItem()) {
throw new RuntimeException("Failed to create carbon intensity source '$name' in DB");
}
return $source->getID();
}
/**
* Get or create a carbon intensity zone by name
*
* @param string $name Name of the zone
* @param int $source_id ID of the source to associate with the zone
* @return int ID of the zone
*/
public static function getOrCreateZone(string $name, int $source_id): int
{
$zone = new Zone();
$zone->getOrCreate([
'plugin_carbon_sources_id_historical' => $source_id,
], [
'name' => $name,
]);
$zone->getFromDBByCrit(['name' => $name]);
if ($zone->isNewItem()) {
throw new RuntimeException("Failed to create zone '$name' in DB");
}
return $zone->getID();
}
/**
* Link a carbon intensity source to a zone
*
* @param int $source_id ID of the carbon intensity source
* @param int $zone_id ID of the zone
* @param string $code Identifier of the zone used by the source
* @return int ID of the link
*/
public static function linkSourceZone(int $source_id, int $zone_id, string $code = ''): int
{
$source_zone = new Source_Zone();
$source_zone->getFromDBByCrit([
'plugin_carbon_sources_id' => $source_id,
'plugin_carbon_zones_id' => $zone_id,
]);
if ($source_zone->isNewItem()) {
$source_zone->add([
'plugin_carbon_sources_id' => $source_id,
'plugin_carbon_zones_id' => $zone_id,
'code' => $code,
]);
} else {
if ($source_zone->fields['code'] !== $code) {
$source_zone->update([
'id' => $source_zone->getID(),
'code' => $code,
]);
}
}
return $source_zone->getID();
}
}
You can’t perform that action at this time.
