-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathBase.php
More file actions
214 lines (182 loc) · 6.49 KB
/
Base.php
File metadata and controls
214 lines (182 loc) · 6.49 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
<?php
namespace ProcessMaker\ScriptRunners;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use ProcessMaker\GenerateAccessToken;
use ProcessMaker\Models\EnvironmentVariable;
use ProcessMaker\Models\ScriptDockerBindingFilesTrait;
use ProcessMaker\Models\ScriptDockerCopyingFilesTrait;
use ProcessMaker\Models\ScriptDockerNayraTrait;
use ProcessMaker\Models\ScriptExecutor;
use ProcessMaker\Models\User;
use RuntimeException;
abstract class Base
{
use ScriptDockerCopyingFilesTrait;
use ScriptDockerBindingFilesTrait;
use ScriptDockerNayraTrait;
const NAYRA_LANG = 'php-nayra';
private $tokenId = '';
/**
* Prepare the docker configuration.
*
* @param string $code
* @param array $dockerConfig
*
* @return array
*/
abstract public function config($code, array $dockerConfig);
/**
* Set the user to run this script as
*
* @var User
*/
private $user;
/**
* Set the script executor
*
* @var ScriptExecutor
*/
private $scriptExecutor;
public function __construct(ScriptExecutor $scriptExecutor)
{
$this->scriptExecutor = $scriptExecutor;
}
/**
* Run a script code.
*
* @param string $code
* @param array $data
* @param array $config
* @param int $timeout
* @param User $user
*
* @return array
* @throws RuntimeException
*/
public function run($code, array $data, array $config, $timeout, ?User $user, $sync, $metadata)
{
$isNayra = $this->scriptExecutor->language === self::NAYRA_LANG;
// Prepare the docker parameters
$environmentVariables = $this->getEnvironmentVariables(!$isNayra);
if (!getenv('HOME')) {
putenv('HOME=' . base_path());
}
// Create tokens for the SDK if a user is set
$token = null;
if ($user) {
$expires = Carbon::now()->addWeek();
$accessToken = Cache::remember('script-runner-' . $user->id, $expires, function () use ($user) {
$user->removeOldRunScriptTokens();
$token = new GenerateAccessToken($user);
return $token->getToken();
});
$environmentVariables[] = 'API_TOKEN=' . (!$isNayra ? escapeshellarg($accessToken) : $accessToken);
$environmentVariables[] = 'API_HOST=' . config('app.docker_host_url') . '/api/1.0';
$environmentVariables[] = 'APP_URL=' . config('app.docker_host_url');
$environmentVariables[] = 'API_SSL_VERIFY=' . (config('app.api_ssl_verify') ? '1' : '0');
}
// Nayra Executor
if ($isNayra) {
$response = $this->handleNayraDocker($code, $data, $config, $timeout, $environmentVariables);
return json_decode($response, true);
}
if ($environmentVariables) {
$parameters = '-e ' . implode(' -e ', $environmentVariables);
} else {
$parameters = '';
}
// Set docker shared memory size
$parameters .= ' --shm-size=' . env('DOCKER_SHARED_MEMORY', '256m');
// Add any custom parameters specified in the config file
$parameters .= ' ' . config('app.processmaker_scripts_docker_params');
$dockerConfig = $this->config($code, [
'timeout' => $timeout,
'parameters' => $parameters,
'inputs' => [
'/opt/executor/data.json' => json_encode($data),
'/opt/executor/config.json' => json_encode($config),
],
'outputs' => [
'response' => '/opt/executor/output.json',
],
]);
// If the image is not specified, use the one set by the executor
if (!isset($dockerConfig['image'])) {
$dockerConfig['image'] = $this->scriptExecutor->dockerImageName();
}
// Execute docker
$executeMethod = config('app.processmaker_scripts_docker_mode') === 'binding'
? 'executeBinding' : 'executeCopying';
Log::debug('Executing docker ' . $this->getRunId() . ':', [
'executeMethod' => $executeMethod,
]);
$response = $this->$executeMethod($dockerConfig);
// Delete the token we created for this run
if ($token) {
$token->delete();
}
// Process the output
$returnCode = $response['returnCode'];
$stdOutput = $response['output'];
$output = $response['outputs']['response'];
Log::info("Docker returned {$this->getRunId()}", [
'response' => [
'responseCode' => $returnCode,
'line' => $response['line'] ?? '',
'stdOutput' => substr(json_encode($stdOutput), 0, 500) . '...',
'outputs' => substr(json_encode($output), 0, 500) . '...',
],
]);
if ($returnCode || $stdOutput) {
// Has an error code
throw new RuntimeException("(Code: {$returnCode})" . implode("\n", $stdOutput));
}
// Success
return ['output' => json_decode($output, true)];
}
/**
* Get the environment variables.
*
* @param bool $useEscape
* @return array
*/
private function getEnvironmentVariables($useEscape = true)
{
$variablesParameter = [];
EnvironmentVariable::chunk(50, function ($variables) use (&$variablesParameter, $useEscape) {
foreach ($variables as $variable) {
// Fix variables that have spaces
$variable['name'] = str_replace(' ', '_', $variable['name']);
if ($useEscape) {
$variablesParameter[] = escapeshellarg($variable['name']) . '=' . escapeshellarg($variable['value']);
} else {
$variablesParameter[] = $variable['name'] . '=' . $variable['value'];
}
}
});
// Add the url to the host
if ($useEscape) {
$variablesParameter[] = 'HOST_URL=' . escapeshellarg(config('app.docker_host_url'));
} else {
$variablesParameter[] = 'HOST_URL=' . config('app.docker_host_url');
}
return $variablesParameter;
}
/**
* Set the tokenId of reference.
*
* @param string $tokenId
*
* @return void
*/
public function setTokenId($tokenId)
{
$this->tokenId = $tokenId;
}
private function getRunId()
{
return $this->tokenId ? '#' . $this->tokenId : '';
}
}