{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Expand file tree
/
Copy pathExecutor.php
More file actions
346 lines (290 loc) · 11.3 KB
/
Copy pathExecutor.php
File metadata and controls
346 lines (290 loc) · 11.3 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
<?php
namespace Executor;
use Appwrite\Utopia\Fetch\BodyMultipart;
use Executor\Exception as ExecutorException;
use Executor\Exception\Timeout as ExecutorTimeout;
use Utopia\System\System;
class Executor
{
// 0.8.6 is last version with object-based headers
public const RESPONSE_FORMAT_OBJECT_HEADERS = '0.10.0';
// 0.9.0 is first version with array-based headers
public const RESPONSE_FORMAT_ARRAY_HEADERS = '0.11.0';
public const METHOD_GET = 'GET';
public const METHOD_POST = 'POST';
public const METHOD_DELETE = 'DELETE';
protected bool $selfSigned = false;
protected string $endpoint;
protected array $headers;
public function __construct()
{
$this->endpoint = System::getEnv('_APP_EXECUTOR_HOST', '');
$this->headers = [
'content-type' => 'application/json',
'authorization' => 'Bearer ' . System::getEnv('_APP_EXECUTOR_SECRET', ''),
'x-opr-addressing-method' => 'anycast-efficient',
'x-edge-bypass-gateway' => '1'
];
}
/**
* Delete Runtime
*
* Deletes a runtime and cleans up any containers remaining.
*
* @param string $projectId
* @param string $deploymentId
*/
public function deleteRuntime(string $projectId, string $deploymentId, string $suffix = '')
{
$runtimeId = "$projectId-$deploymentId" . $suffix;
$route = "/runtimes/$runtimeId";
$response = $this->call($this->endpoint, self::METHOD_DELETE, $route, [
'x-opr-addressing-method' => 'broadcast'
], [], true, 30);
$status = $response['headers']['status-code'];
$message = \is_string($response['body']) ? $response['body'] : ($response['body']['message'] ?? '');
// Runtime already gone — nothing to do
if ($status === 404) {
return true;
}
// Temporary fix for race condition
if ($status === 500 && \str_contains($message, 'already in progress')) {
return true; // OK, removal already in progress
}
if ($status >= 400) {
$type = \is_array($response['body']) ? ($response['body']['type'] ?? ExecutorException::GENERAL_UNKNOWN) : ExecutorException::GENERAL_UNKNOWN;
throw new ExecutorException($message, $status, type: $type);
}
return $response['body'];
}
/**
* Create an execution
*
* @param string $projectId
* @param string $deploymentId
* @param string $body
* @param array $variables
* @param int $timeout
* @param string $image
* @param string $source
* @param string $entrypoint
* @param string $runtimeEntrypoint
* @param bool $logging
* @param string $responseFormat
*
* @return array
*/
public function createExecution(
string $projectId,
string $deploymentId,
?string $body,
array $variables,
int $timeout,
string $image,
string $source,
string $entrypoint,
string $version,
string $path,
string $method,
array $headers,
float $cpus,
int $memory,
bool $logging,
string $runtimeEntrypoint = '',
?int $requestTimeout = null,
string $responseFormat = self::RESPONSE_FORMAT_OBJECT_HEADERS
) {
$runtimeId = "$projectId-$deploymentId";
$route = '/runtimes/' . $runtimeId . '/executions';
// Remove after migration
if ($version === 'v3' || $version === 'v4') {
$version = 'v5';
}
$params = [
'runtimeId' => $runtimeId,
'variables' => $variables,
'timeout' => $timeout,
'path' => $path,
'method' => $method,
'headers' => $headers,
'image' => $image,
'source' => $source,
'entrypoint' => $entrypoint,
'cpus' => $cpus,
'memory' => $memory,
'version' => $version,
'runtimeEntrypoint' => $runtimeEntrypoint,
'logging' => $logging,
'restartPolicy' => 'always' // Once utopia/orchestration has it, use DockerAPI::ALWAYS (0.13+)
];
if (!empty($body)) {
$params['body'] = $body;
}
// Safety timeout. Executor has timeout, and open runtime has soft timeout.
// This one shouldn't really happen, but prevents from unexpected networking behaviours.
if ($requestTimeout == null) {
$requestTimeout = $timeout + 15;
}
$response = $this->call($this->endpoint, self::METHOD_POST, $route, [ 'x-opr-runtime-id' => $runtimeId, 'content-type' => 'multipart/form-data', 'accept' => 'multipart/form-data', 'x-executor-response-format' => $responseFormat ], $params, true, $requestTimeout);
$status = $response['headers']['status-code'];
if ($status >= 400) {
$message = \is_string($response['body']) ? $response['body'] : ($response['body']['message'] ?? '');
$type = \is_array($response['body']) ? ($response['body']['type'] ?? ExecutorException::GENERAL_UNKNOWN) : ExecutorException::GENERAL_UNKNOWN;
throw new ExecutorException($message, $status, type: $type);
}
$headers = $response['body']['headers'] ?? [];
if (is_string($headers)) {
$headers = \json_decode($headers, true);
}
$response['body']['headers'] = $headers;
$response['body']['statusCode'] = \intval($response['body']['statusCode'] ?? 500);
$response['body']['duration'] = \floatval($response['body']['duration'] ?? 0);
$response['body']['startTime'] = \floatval($response['body']['startTime'] ?? \microtime(true));
return $response['body'];
}
/**
* Call
*
* Make an API call
*
* @param string $method
* @param string $path
* @param array $params
* @param array $headers
* @param bool $decode
* @return array
* @throws Exception
*/
private function call(string $endpoint, string $method, string $path = '', array $headers = [], array $params = [], bool $decode = true, int $timeout = 15, ?callable $callback = null): array
{
$headers = array_merge($this->headers, $headers);
$ch = curl_init($endpoint . $path . (($method == self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : ''));
$responseHeaders = [];
$responseStatus = -1;
$responseType = '';
$responseBody = '';
switch ($headers['content-type']) {
case 'application/json':
$query = json_encode($params);
break;
case 'multipart/form-data':
$multipart = new BodyMultipart();
foreach ($params as $key => $value) {
$multipart->setPart($key, $value);
}
$headers['content-type'] = $multipart->exportHeader();
$query = $multipart->exportBody();
break;
default:
$query = http_build_query($params);
break;
}
foreach ($headers as $i => $header) {
$headers[] = $i . ':' . $header;
unset($headers[$i]);
}
if (isset($callback)) {
$headers[] = 'accept: text/event-stream';
$handleEvent = function ($ch, $data) use ($callback) {
$callback($data);
return \strlen($data);
};
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $handleEvent);
} else {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) { // ignore invalid headers
return $len;
}
$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
});
if ($method != self::METHOD_GET) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
}
// Allow self signed certificates
if ($this->selfSigned) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$responseBody = curl_exec($ch);
if (isset($callback)) {
return [];
}
$responseType = $responseHeaders['content-type'] ?? '';
$responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_errno($ch);
$curlErrorMessage = curl_error($ch);
if ($decode) {
$strpos = strpos($responseType, ';');
$strpos = \is_bool($strpos) ? \strlen($responseType) : $strpos;
switch (substr($responseType, 0, $strpos)) {
case 'multipart/form-data':
$boundary = \explode('boundary=', $responseHeaders['content-type'])[1] ?? '';
$multipartResponse = new BodyMultipart($boundary);
$multipartResponse->load(\is_bool($responseBody) ? '' : $responseBody);
$responseBody = $multipartResponse->getParts();
break;
case 'application/json':
$json = json_decode($responseBody, true);
if ($json === null) {
throw new ExecutorException('Failed to parse response: ' . $responseBody);
}
$responseBody = $json;
$json = null;
break;
}
}
if ($curlError) {
if ($curlError == CURLE_OPERATION_TIMEDOUT) {
throw new ExecutorTimeout('Executor request timed out after ' . $timeout . ' seconds');
}
throw new ExecutorException($curlErrorMessage . ' with status code ' . $responseStatus, $responseStatus);
}
$responseHeaders['status-code'] = $responseStatus;
return [
'headers' => $responseHeaders,
'body' => $responseBody
];
}
/**
* Parse Cookie String
*
* @param string $cookie
* @return array
*/
public function parseCookie(string $cookie): array
{
$cookies = [];
parse_str(strtr($cookie, array('&' => '%26', '+' => '%2B', ';' => '&')), $cookies);
return $cookies;
}
/**
* Flatten params array to PHP multiple format
*
* @param array $data
* @param string $prefix
* @return array
*/
protected function flatten(array $data, string $prefix = ''): array
{
$output = [];
foreach ($data as $key => $value) {
$finalKey = $prefix ? "{$prefix}[{$key}]" : $key;
if (is_array($value)) {
$output += $this->flatten($value, $finalKey); // @todo: handle name collision here if needed
} else {
$output[$finalKey] = $value;
}
}
return $output;
}
}
You can’t perform that action at this time.
