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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Deploy\Console;
use Psr\Log\AbstractLogger;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Helper\FormatterHelper;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem\Directory\ReadInterface;
/**
* PSR logger implementation for CLI
*/
class ConsoleLogger extends AbstractLogger
{
/**
* Type for informational message
*/
const INFO = 'info';
/**
* Type for error message
*/
const ERROR = 'error';
/**
* Public static files directory read interface
*
* @var ReadInterface
*/
private $tmpDir;
/**
* Console output interface
*
* @var OutputInterface
*/
private $output;
/**
* Helper for preparing data of specific formats (date, percentage, etc)
*
* @var FormatterHelper
*/
private $formatterHelper;
/**
* Maximum progress bar row string length
*
* @var int
*/
private $initialMaxBarSize = 0;
/**
* Number of rendered lines
*
* Used for clearing previously rendered progress bars
*
* @var int
*/
private $renderedLines = 0;
/**
* Time of previous rendering tick
*
* @var int
*/
private $lastTimeRefreshed = 0;
/**
* @var array
*/
private $verbosityLevelMap = [
LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL,
LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL,
LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL,
LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL,
LogLevel::INFO => OutputInterface::VERBOSITY_VERBOSE,
LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG
];
/**
* @var array
*/
private $formatLevelMap = [
LogLevel::EMERGENCY => self::ERROR,
LogLevel::ALERT => self::ERROR,
LogLevel::CRITICAL => self::ERROR,
LogLevel::ERROR => self::ERROR,
LogLevel::WARNING => self::INFO,
LogLevel::NOTICE => self::INFO,
LogLevel::INFO => self::INFO,
LogLevel::DEBUG => self::INFO
];
/**
* Running deployment processes info
*
* @var array[]
*/
private $processes = [];
/**
* @param Filesystem $filesystem
* @param OutputInterface $output
* @param FormatterHelper $formatterHelper
* @param array $verbosityLevelMap
* @param array $formatLevelMap
*/
public function __construct(
Filesystem $filesystem,
OutputInterface $output,
FormatterHelper $formatterHelper,
array $verbosityLevelMap = [],
array $formatLevelMap = []
) {
$this->tmpDir = $filesystem->getDirectoryWrite(DirectoryList::TMP_MATERIALIZATION_DIR);
$this->output = $output;
$this->formatterHelper = $formatterHelper;
$this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap;
$this->formatLevelMap = $formatLevelMap + $this->formatLevelMap;
}
/**
* @inheritdoc
*/
public function log($level, $message, array $context = [])
{
if (!isset($this->verbosityLevelMap[$level])) {
$level = self::INFO;
}
// Write to the error output if necessary and available
if ($this->formatLevelMap[$level] === self::ERROR && $this->output instanceof ConsoleOutputInterface) {
$output = $this->output->getErrorOutput();
} else {
$output = $this->output;
}
if (isset($context['process'])) {
$this->registerProcess($context);
} else {
$this->refresh($output);
}
if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) {
$output->writeln(sprintf('<%1$s>%2$s</%1$s>', $this->formatLevelMap[$level], $message));
}
}
/**
* Add deployment process to rendering stack
*
* @param array $context
* @return void
*/
private function registerProcess(array $context)
{
$name = isset($context['process']) ? $context['process'] : 'main';
if (!isset($this->processes[$name])) {
$context['start'] = time();
$context['elapsed'] = 0;
$this->processes[$name] = $context;
}
}
/**
* Refresh CLI output
*
* @param OutputInterface $output
* @return void
*/
private function refresh(OutputInterface $output)
{
if (!count($this->processes) || (time() - $this->lastTimeRefreshed < 1)) {
return;
}
$this->cleanUp();
$bars = [];
$maxBarSize = 0;
foreach ($this->processes as $name => & $process) {
$this->updateProcessInfo($name, $process);
$bar = $this->renderProgressBar($output, $process);
$maxBarSize = strlen($bar) > $maxBarSize ? strlen($bar) : $maxBarSize;
$bars[] = $bar;
}
if (!$this->initialMaxBarSize) {
$this->initialMaxBarSize = $maxBarSize + 10;
}
if ($bars) {
$this->renderedLines = count($bars);
$bar = '';
foreach ($bars as &$bar) {
if ($this->initialMaxBarSize > strlen($bar)) {
$bar .= str_pad(" ", ($this->initialMaxBarSize - strlen($bar)));
}
}
$bar = trim($bar);
$output->writeln(implode("\n", $bars));
}
}
/**
* Update process information
*
* @param string $deployedPackagePath
* @param array $process
* @return void
*/
private function updateProcessInfo($deployedPackagePath, array & $process)
{
$packageDeploymentInfo = $this->getPackageDeploymentInfo($deployedPackagePath . '/info.json');
if ($packageDeploymentInfo) {
$process['done'] = $packageDeploymentInfo['count'];
} else {
$process['done'] = 0;
}
if ($process['done'] > $process['count']) {
$process['count'] = $process['done'];
}
if ($process['done'] !== $process['count']) {
$process['elapsed'] = $this->formatterHelper->formatTime(time() - $process['start']);
}
$process['percent'] = floor(
($process['count'] ? (float)$process['done'] / $process['count'] : 0) * 100
);
}
/**
* Clear rendered lines
*
* @return void
*/
private function cleanUp()
{
$this->lastTimeRefreshed = time();
// Erase previous lines
if ($this->renderedLines > 0) {
for ($i = 0; $i < $this->renderedLines; ++$i) {
$this->output->write("\x1B[1A\x1B[2K", false, OutputInterface::OUTPUT_RAW);
}
}
$this->renderedLines = 0;
}
/**
* Generate progress bar part
*
* @param OutputInterface $output
* @param array $process
* @return string
*/
private function renderProgressBar(OutputInterface $output, array $process)
{
$title = "{$process['process']}";
$titlePad = str_pad(' ', (40 - strlen($title)));
$count = "{$process['done']}/{$process['count']}";
$countPad = str_pad(' ', (20 - strlen($count)));
$percent = "{$process['percent']}% ";
$percentPad = str_pad(' ', (7 - strlen($percent)));
return "{$title}{$titlePad}"
. "{$count}{$countPad}"
. "{$this->renderBar($output, $process)} "
. "{$percent}%{$percentPad}"
. "{$process['elapsed']} ";
}
/**
* Generate progress bar row
*
* @param OutputInterface $output
* @param array $process
* @return string
*/
private function renderBar(OutputInterface $output, array $process)
{
$completeBars = floor(
$process['count'] > 0 ? ($process['done'] / $process['count']) * 28 : $process['done'] % 28
);
$display = str_repeat('=', $completeBars);
if ($completeBars < 28) {
$emptyBars = 28 - $completeBars
- $this->formatterHelper->strlenWithoutDecoration($output->getFormatter(), '>');
$display .= '>' . str_repeat('-', $emptyBars);
}
return $display;
}
/**
* Retrieve package deployment process information
*
* @param string $relativePath
* @return string|false
*/
private function getPackageDeploymentInfo($relativePath)
{
if ($this->tmpDir->isFile($relativePath)) {
$info = $this->tmpDir->readFile($relativePath);
$info = json_decode($info, true);
} else {
$info = [];
}
return $info;
}
}