-
Notifications
You must be signed in to change notification settings - Fork 123
/
ExecuteCommand.php
258 lines (222 loc) · 8.87 KB
/
ExecuteCommand.php
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
<?php
namespace JMose\CommandSchedulerBundle\Command;
use Cron\CronExpression;
use Symfony\Bridge\Doctrine\ManagerRegistry;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use JMose\CommandSchedulerBundle\Entity\ScheduledCommand;
/**
* Class ExecuteCommand : This class is the entry point to execute all scheduled command
*
* @author Julien Guyon <julienguyon@hotmail.com>
* @package JMose\CommandSchedulerBundle\Command
*/
class ExecuteCommand extends Command
{
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;
/**
* @var string
*/
private $logPath;
/**
* @var boolean
*/
private $dumpMode;
/**
* @var integer
*/
private $commandsVerbosity;
/**
* ExecuteCommand constructor.
* @param ManagerRegistry $managerRegistry
* @param $managerName
* @param $logPath
*/
public function __construct(ManagerRegistry $managerRegistry, $managerName, $logPath)
{
$this->em = $managerRegistry->getManager($managerName);
$this->logPath = $logPath;
// If logpath is not set to false, append the directory separator to it
if (false !== $this->logPath) {
$this->logPath = rtrim($this->logPath, '/\\').DIRECTORY_SEPARATOR;
}
parent::__construct();
}
/**
* @inheritdoc
*/
protected function configure()
{
$this
->setName('scheduler:execute')
->setDescription('Execute scheduled commands')
->addOption('dump', null, InputOption::VALUE_NONE, 'Display next execution')
->addOption('no-output', null, InputOption::VALUE_NONE, 'Disable output message from scheduler')
->setHelp('This class is the entry point to execute all scheduled command');
}
/**
* Initialize parameters and services used in execute function
*
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->dumpMode = $input->getOption('dump');
// Store the original verbosity before apply the quiet parameter
$this->commandsVerbosity = $output->getVerbosity();
if (true === $input->getOption('no-output')) {
$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
}
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>Start : '.($this->dumpMode ? 'Dump' : 'Execute').' all scheduled command</info>');
// Before continue, we check that the output file is valid and writable (except for gaufrette)
if (false !== $this->logPath && strpos($this->logPath, 'gaufrette:') !== 0 && false === is_writable(
$this->logPath
)
) {
$output->writeln(
'<error>'.$this->logPath.
' not found or not writable. You should override `log_path` in your config.yml'.'</error>'
);
return;
}
$commands = $this->em->getRepository(ScheduledCommand::class)->findEnabledCommand();
$noneExecution = true;
foreach ($commands as $command) {
/** @var ScheduledCommand $command */
$cron = CronExpression::factory($command->getCronExpression());
$nextRunDate = $cron->getNextRunDate($command->getLastExecution());
$now = new \DateTime();
if ($command->isExecuteImmediately()) {
$noneExecution = false;
$output->writeln(
'Immediately execution asked for : <comment>'.$command->getCommand().'</comment>'
);
if (!$input->getOption('dump')) {
$this->executeCommand($command, $output, $input);
}
} elseif ($nextRunDate < $now) {
$noneExecution = false;
$output->writeln(
'Command <comment>'.$command->getCommand().
'</comment> should be executed - last execution : <comment>'.
$command->getLastExecution()->format('d/m/Y H:i:s').'.</comment>'
);
if (!$input->getOption('dump')) {
$this->executeCommand($command, $output, $input);
}
}
}
if (true === $noneExecution) {
$output->writeln('Nothing to do.');
}
}
/**
* @param ScheduledCommand $scheduledCommand
* @param OutputInterface $output
* @param InputInterface $input
*/
private function executeCommand(ScheduledCommand $scheduledCommand, OutputInterface $output, InputInterface $input)
{
//reload command from database before every execution to avoid parallel execution
$this->em->getConnection()->beginTransaction();
try {
$notLockedCommand = $this
->em
->getRepository(ScheduledCommand::class)
->getNotLockedCommand($scheduledCommand);
//$notLockedCommand will be locked for avoiding parallel calls: http://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html
if ($notLockedCommand === null) {
throw new \Exception();
}
$scheduledCommand = $notLockedCommand;
$scheduledCommand->setLastExecution(new \DateTime());
$scheduledCommand->setLocked(true);
$scheduledCommand = $this->em->merge($scheduledCommand);
$this->em->flush();
$this->em->getConnection()->commit();
} catch (\Exception $e) {
$this->em->getConnection()->rollBack();
$output->writeln(
sprintf(
'<error>Command %s is locked %s</error>',
$scheduledCommand->getCommand(),
(!empty($e->getMessage()) ? sprintf('(%s)', $e->getMessage()) : '')
)
);
return;
}
try {
$command = $this->getApplication()->find($scheduledCommand->getCommand());
} catch (\InvalidArgumentException $e) {
$scheduledCommand->setLastReturnCode(-1);
$output->writeln('<error>Cannot find '.$scheduledCommand->getCommand().'</error>');
return;
}
$input = new StringInput(
$scheduledCommand->getCommand().' '.$scheduledCommand->getArguments().' --env='.$input->getOption('env')
);
$command->mergeApplicationDefinition();
$input->bind($command->getDefinition());
// Disable interactive mode if the current command has no-interaction flag
if (true === $input->hasParameterOption(['--no-interaction', '-n'])) {
$input->setInteractive(false);
}
// Use a StreamOutput or NullOutput to redirect write() and writeln() in a log file
if (false === $this->logPath || empty($scheduledCommand->getLogFile())) {
$logOutput = new NullOutput();
} else {
$logOutput = new StreamOutput(
fopen(
$this->logPath.$scheduledCommand->getLogFile(),
'a',
false
), $this->commandsVerbosity
);
}
// Execute command and get return code
try {
$output->writeln(
'<info>Execute</info> : <comment>'.$scheduledCommand->getCommand()
.' '.$scheduledCommand->getArguments().'</comment>'
);
$result = $command->run($input, $logOutput);
} catch (\Exception $e) {
$logOutput->writeln($e->getMessage());
$logOutput->writeln($e->getTraceAsString());
$result = -1;
}
if (false === $this->em->isOpen()) {
$output->writeln('<comment>Entity manager closed by the last command.</comment>');
$this->em = $this->em->create($this->em->getConnection(), $this->em->getConfiguration());
}
$scheduledCommand = $this->em->merge($scheduledCommand);
$scheduledCommand->setLastReturnCode($result);
$scheduledCommand->setLocked(false);
$scheduledCommand->setExecuteImmediately(false);
$this->em->flush();
/*
* This clear() is necessary to avoid conflict between commands and to be sure that none entity are managed
* before entering in a new command
*/
$this->em->clear();
unset($command);
gc_collect_cycles();
}
}