-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWikiEntityImportJob.php
More file actions
244 lines (218 loc) · 9.41 KB
/
WikiEntityImportJob.php
File metadata and controls
244 lines (218 loc) · 9.41 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
<?php
namespace App\Jobs;
use App\Services\MediaWikiHostResolver;
use App\Wiki;
use App\WikiEntityImport;
use App\WikiEntityImportStatus;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Maclof\Kubernetes\Client;
use Maclof\Kubernetes\Models\Job as KubernetesJob;
class WikiEntityImportJob implements ShouldQueue {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct(
public int $wikiId,
public string $sourceWikiUrl,
public array $entityIds,
public int $importId
) {}
private string $targetWikiUrl;
/**
* Execute the job.
*/
public function handle(Client $kubernetesClient, MediaWikiHostResolver $mwHostResolver): void {
$import = null;
try {
$wiki = Wiki::findOrFail($this->wikiId);
$import = WikiEntityImport::findOrFail($this->importId);
$creds = $this->acquireCredentials($wiki->domain, $mwHostResolver);
$this->targetWikiUrl = $this->domainToOrigin($wiki->domain);
$kubernetesJob = new TransferBotKubernetesJob(
kubernetesClient: $kubernetesClient,
wiki: $wiki,
creds: $creds,
entityIds: $this->entityIds,
sourceWikiUrl: $this->sourceWikiUrl,
targetWikiUrl: $this->targetWikiUrl,
importId: $this->importId,
);
$jobName = $kubernetesJob->spawn();
Log::info(
'transferbot job for wiki "' . $wiki->domain . '" was created with name "' . $jobName . '".'
);
} catch (\Exception $ex) {
Log::error('Entity import job failed with error: ' . $ex->getMessage());
$import?->update([
'status' => WikiEntityImportStatus::Failed,
'finished_at' => Carbon::now(),
]);
$this->fail(
new \Exception('Error spawning transferbot for wiki ' . $this->wikiId . ': ' . $ex->getMessage()),
);
}
}
private static function domainToOrigin(string $domain): string {
$tld = last(explode('.', $domain));
return $tld === 'localhost'
? 'http://' . $domain
: 'https://' . $domain;
}
private static function acquireCredentials(string $wikiDomain, MediaWikiHostResolver $mwHostResolver): OAuthCredentials {
$response = Http::withHeaders(['host' => $wikiDomain])->asForm()->post(
$mwHostResolver->getBackendHostForDomain($wikiDomain) . '/w/api.php?action=wbstackPlatformOauthGet&format=json',
[
'consumerName' => 'WikiEntityImportJob',
'ownerOnly' => '1',
'consumerVersion' => '1',
'grants' => 'basic|highvolume|import|editpage|editprotected|createeditmovepage|uploadfile|uploadeditmovefile|rollback|delete|mergehistory',
'callbackUrlTail' => '/w/index.php',
],
);
if ($response->status() > 399) {
throw new \Exception('Unexpected status code ' . $response->status() . ' from Mediawiki');
}
$body = $response->json();
if (!$body || $body['wbstackPlatformOauthGet']['success'] !== '1') {
throw new \ErrorException('Unexpected error acquiring oauth credentials for wiki ' . $wikiDomain);
}
return OAuthCredentials::unmarshalMediaWikiResponse($body);
}
}
class TransferBotKubernetesJob {
public function __construct(
public Client $kubernetesClient,
public Wiki $wiki,
public OAuthCredentials $creds,
public array $entityIds,
public string $sourceWikiUrl,
public string $targetWikiUrl,
public int $importId,
) {
$this->kubernetesNamespace = Config::get('wbstack.api_job_namespace');
$this->transferbotImageRepo = Config::get('wbstack.transferbot_image_repo');
$this->transferbotImageVersion = Config::get('wbstack.transferbot_image_version');
}
private string $kubernetesNamespace;
private string $transferbotImageRepo;
private string $transferbotImageVersion;
public function spawn(): string {
$spec = $this->constructSpec();
$jobSpec = new KubernetesJob($spec);
$this->kubernetesClient->setNamespace($this->kubernetesNamespace);
$jobObject = $this->kubernetesClient->jobs()->apply($jobSpec);
$jobName = data_get($jobObject, 'metadata.name');
if (data_get($jobObject, 'status') === 'Failure' || !$jobName) {
// The k8s client does not fail reliably on 4xx responses, so checking the name
// currently serves as poor man's error handling.
throw new \RuntimeException(
'transferbot creation for wiki "' . $this->wiki->domain . '" failed with message: ' . data_get($jobObject, 'message', 'n/a')
);
}
return $jobName;
}
private function constructSpec(): array {
return [
'metadata' => [
'generateName' => 'run-transferbot-',
'namespace' => $this->kubernetesNamespace,
'labels' => [
'app.kubernetes.io/instance' => $this->wiki->domain,
'app.kubernetes.io/name' => 'run-transferbot',
],
],
'spec' => [
'ttlSecondsAfterFinished' => 172800, // 1 week
'backoffLimit' => 0,
'template' => [
'metadata' => [
'name' => 'run-entity-import',
],
'spec' => [
'containers' => [
0 => [
'hostNetwork' => true,
'name' => 'run-entity-import',
'image' => $this->transferbotImageRepo . ':' . $this->transferbotImageVersion,
'env' => [
...$this->creds->marshalEnv(),
[
'name' => 'CALLBACK_ON_FAILURE',
'value' => 'curl -sS -H "Accept: application/json" -H "Content-Type: application/json" --data \'{"wiki_entity_import":' . $this->importId . ',"status":"failed"}\' -XPATCH http://api-app-backend.default.svc.cluster.local/backend/wiki/updateEntityImport',
],
[
'name' => 'CALLBACK_ON_SUCCESS',
'value' => 'curl -sS -H "Accept: application/json" -H "Content-Type: application/json" --data \'{"wiki_entity_import":' . $this->importId . ',"status":"success"}\' -XPATCH http://api-app-backend.default.svc.cluster.local/backend/wiki/updateEntityImport',
],
],
'command' => [
'transferbot',
$this->sourceWikiUrl,
$this->targetWikiUrl,
...$this->entityIds,
],
'resources' => [
'requests' => [
'cpu' => '0.25',
'memory' => '250Mi',
],
'limits' => [
'cpu' => '0.5',
'memory' => '500Mi',
],
],
],
],
'restartPolicy' => 'Never',
],
],
],
];
}
}
class OAuthCredentials {
public function __construct(
public string $consumerToken,
public string $consumerSecret,
public string $accessToken,
public string $accessSecret,
) {}
public static function unmarshalMediaWikiResponse(array $response): OAuthCredentials {
$data = $response['wbstackPlatformOauthGet']['data'];
return new OAuthCredentials(
consumerToken: $data['consumerKey'],
consumerSecret: $data['consumerSecret'],
accessToken: $data['accessKey'],
accessSecret: $data['accessSecret'],
);
}
public function marshalEnv(string $prefix = 'TARGET_WIKI_OAUTH'): array {
return [
[
'name' => $prefix . '_CONSUMER_TOKEN',
'value' => $this->consumerToken,
],
[
'name' => $prefix . '_CONSUMER_SECRET',
'value' => $this->consumerSecret,
],
[
'name' => $prefix . '_ACCESS_TOKEN',
'value' => $this->accessToken,
],
[
'name' => $prefix . '_ACCESS_SECRET',
'value' => $this->accessSecret,
],
];
}
}