-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathRunScriptTask.php
More file actions
207 lines (185 loc) · 7.68 KB
/
RunScriptTask.php
File metadata and controls
207 lines (185 loc) · 7.68 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
<?php
namespace ProcessMaker\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use ProcessMaker\Enums\ScriptExecutorType;
use ProcessMaker\Exception\ConfigurationException;
use ProcessMaker\Exception\ScriptException;
use ProcessMaker\Facades\Metrics;
use ProcessMaker\Facades\WorkflowManager;
use ProcessMaker\Managers\DataManager;
use ProcessMaker\Models\Process as Definitions;
use ProcessMaker\Models\ProcessRequest;
use ProcessMaker\Models\ProcessRequestToken;
use ProcessMaker\Models\Script;
use ProcessMaker\Models\ScriptExecutor;
use ProcessMaker\Nayra\Contracts\Bpmn\ScriptTaskInterface;
use Throwable;
class RunScriptTask extends BpmnAction implements ShouldQueue
{
public $definitionsId;
public $instanceId;
public $tokenId;
public $data;
public $attemptNum;
/**
* Create a new job instance.
*
* @param Definitions $definitions
* @param ProcessRequest $instance
* @param ProcessRequestToken $token
* @param array $data
*/
public function __construct(Definitions $definitions, ProcessRequest $instance, ProcessRequestToken $token, array $data, $attemptNum = 1)
{
$this->onQueue('bpmn');
$this->definitionsId = $definitions->getKey();
$this->instanceId = $instance->getKey();
$this->tokenId = $token->getKey();
$this->elementId = $token->getProperty('element_ref');
$this->data = $data;
$this->attemptNum = $attemptNum;
}
/**
* Execute the script task.
*
* @return void
*/
public function action(ProcessRequestToken $token = null, ScriptTaskInterface $element = null, ProcessRequest $instance)
{
// Exit if the task was completed or closed
if (!$token || !$element) {
return;
}
$scriptRef = $element->getProperty('scriptRef');
$configuration = json_decode($element->getProperty('config'), true);
// Check to see if we've failed parsing. If so, let's convert to empty array.
if ($configuration === null) {
$configuration = [];
}
$errorHandling = null;
$scriptExecutor = null;
try {
if (empty($scriptRef)) {
$code = $element->getScript();
if (empty($code)) {
throw new ConfigurationException(__('No code or script assigned to ":name"', ['name' => $element->getName()]));
}
$language = Script::scriptFormat2Language($element->getProperty('scriptFormat', 'application/x-php'));
$script = new Script([
'code' => $code,
'language' => $language,
'run_as_user_id' => Script::defaultRunAsUser()->id,
'script_executor_id' => ScriptExecutor::initialExecutor($language)->id,
]);
} else {
$script = Script::find($scriptRef);
if (!$script) {
throw new ConfigurationException(__('Script ":id" not found', ['id' => $scriptRef]));
}
$scriptExecutor = $script->scriptExecutor;
$script = $script->versionFor($instance);
}
$errorHandling = new ErrorHandling($element, $token);
$errorHandling->setDefaultsFromScript($script);
$this->unlock();
$dataManager = new DataManager();
$data = $dataManager->getData($token);
$metadata = [
'script_task' => [
'script_id' => $scriptRef,
'definition_id' => $this->definitionsId,
'instance_id' => $this->instanceId,
'token_id' => $this->tokenId,
'data' => $data,
'attempts' => $this->attemptNum,
],
];
$response = $script->runScript($data, $configuration, $token->getId(), $errorHandling->timeout(), 1, $metadata);
$this->updateData($response);
Metrics::counterInc(
'script_task_completed_total',
'Total number of script tasks completed',
[
'activity_id' => $element->getId(),
'activity_name' => $element->getName(),
'process_id' => $this->definitionsId,
'request_id' => $this->instanceId,
'script_executor' => $scriptExecutor ? $scriptExecutor->title : 'inline',
]
);
} catch (ConfigurationException $exception) {
$this->unlock();
$this->updateData(['output' => $exception->getMessageForData($token)]);
} catch (Throwable $exception) {
$message = $exception->getMessage();
$finalAttempt = true;
if ($errorHandling) {
[$message, $finalAttempt] = $errorHandling->handleRetries($this, $exception);
} else {
$message = $exception->getMessage();
}
if ($finalAttempt) {
$token->setStatus(ScriptTaskInterface::TOKEN_STATE_FAILING);
}
$error = $element->getRepository()->createError();
$error->setName($message);
$token->setProperty('error', $error);
$exceptionClass = get_class($exception);
$modifiedException = new $exceptionClass($message);
$token->logError($modifiedException, $element);
Log::error('Script failed: ' . $scriptRef . ' - ' . $message);
Log::error($exception->getTraceAsString());
}
}
private function updateData($response)
{
$this->withUpdatedContext(function ($engine, $instance, $element, $processModel, $token) use ($response) {
// Exit if the task was completed or closed
if (!$token || !$element) {
return;
}
// Update data
if (is_array($response['output'])) {
// Validate data
WorkflowManager::validateData($response['output'], $processModel, $element);
$dataManager = new DataManager();
$dataManager->updateData($token, $response['output']);
$engine->runToNextState();
}
$element->complete($token);
$this->engine = $engine;
$this->instance = $instance;
});
}
/**
* When Job fails
*/
public function failed(Throwable $exception)
{
if (!$this->tokenId) {
Log::error('Script failed: ' . $exception->getMessage());
return;
}
if (get_class($exception) === 'Illuminate\\Queue\\MaxAttemptsExceededException') {
$message = 'This is a type MaxAttemptsExceededException exception, it appears '
. 'that the global value configured in config/horizon.php has been exceeded '
. 'in the retries. Please consult with your main administrator.';
Log::error($message);
}
Log::error('Script (#' . $this->tokenId . ') failed: ' . $exception->getMessage());
$token = ProcessRequestToken::find($this->tokenId);
if ($token) {
$element = $token->getBpmnDefinition();
$token->setStatus(ScriptTaskInterface::TOKEN_STATE_FAILING);
if (method_exists($element, 'getRepository')) {
$error = $element->getRepository()->createError();
$error->setName($exception->getMessage());
$token->setProperty('error', $error);
}
Log::error($exception->getTraceAsString());
$token->save();
}
}
}