-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeleteOwnerlessWorkspaces.php
More file actions
225 lines (203 loc) · 9.26 KB
/
DeleteOwnerlessWorkspaces.php
File metadata and controls
225 lines (203 loc) · 9.26 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
<?php
namespace Keboola\Console\Command;
use Keboola\JobQueueClient\Client as JobQueueClient;
use Keboola\JobQueueClient\JobData;
use Keboola\SandboxesServiceApiClient\ApiClientConfiguration;
use Keboola\SandboxesServiceApiClient\Apps\AppsApiClient;
use Keboola\ServiceClient\ServiceClient;
use Keboola\StorageApi\BranchAwareClient;
use Keboola\StorageApi\Client as StorageApiClient;
use Keboola\StorageApi\ClientException as StorageClientException;
use Keboola\StorageApi\Components;
use Keboola\StorageApi\Options\Components\ListComponentConfigurationsOptions;
use Keboola\StorageApi\Tokens;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
class DeleteOwnerlessWorkspaces extends Command
{
protected function configure(): void
{
$this
->setName('storage:delete-ownerless-workspaces')
->setDescription('Bulk delete workspaces that have inactive owner in this project.')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Use [--force, -f] to do it for real.')
->addOption(
'includeShared',
null,
InputOption::VALUE_NONE,
'Use option --includeShared if you would also like to delete shared workspaces with inactive owner.',
)
->addArgument(
'storageToken',
InputArgument::REQUIRED,
'Keboola Storage API token to use'
)
->addArgument(
'hostnameSuffix',
InputArgument::OPTIONAL,
'Keboola Connection Hostname Suffix',
'keboola.com'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$token = $input->getArgument('storageToken');
assert(is_string($token));
assert($token !== '');
$hostnameSuffix = $input->getArgument('hostnameSuffix');
assert(is_string($hostnameSuffix));
assert($hostnameSuffix !== '');
$serviceClient = new ServiceClient($hostnameSuffix);
$url = $serviceClient->getConnectionServiceUrl();
$editorUrl = $serviceClient->getEditorServiceUrl();
$includeShared = (bool) $input->getOption('includeShared');
$force = (bool) $input->getOption('force');
$storageClient = new StorageApiClient([
'token' => $token,
'url' => $url,
'backoffMaxTries' => 1,
'logger' => new ConsoleLogger($output),
]);
$tokensClient = new Tokens($storageClient);
$editorClient = new EditorServiceClient($editorUrl, $token);
if ($force) {
$output->writeln('Force option is set, doing it for real');
} else {
$output->writeln('This is just a dry-run, nothing will be actually deleted');
}
// Editor sessions are bound to userId (stable for the user's lifetime in the system).
// Sandbox configs are bound to creatorToken.id, which is re-issued on every project leave+rejoin.
$activeUserIds = [];
$activeTokenIds = [];
foreach ($tokensClient->listTokens() as $projectToken) {
$activeTokenIds[$projectToken['id']] = true;
if (isset($projectToken['admin']['id'])) {
$activeUserIds[$projectToken['admin']['id']] = true;
}
}
$totalDeleted = 0;
foreach ($editorClient->listSessions() as $session) {
if (isset($activeUserIds[$session['userId']])) {
continue; // user is still active
}
if (!$includeShared && $session['shared']) {
$output->writeln(sprintf(
'Skipping shared session %s/%s for session %s',
$session['componentId'],
$session['configurationId'],
$session['id'],
));
continue;
}
$branchId = $session['branchId'];
$componentId = $session['componentId'];
$configurationId = $session['configurationId'];
$sessionId = $session['id'];
$output->writeln(sprintf(
'Deleting configuration %s/%s (branch %s) for session %s',
$componentId,
$configurationId,
$branchId,
$sessionId,
));
$totalDeleted++;
if ($force) {
$branchClient = new BranchAwareClient($branchId, [
'token' => $token,
'url' => $url,
]);
$components = new Components($branchClient);
try {
// First call moves the configuration to trash, second call permanently purges it.
$components->deleteConfiguration($componentId, $configurationId);
$components->deleteConfiguration($componentId, $configurationId);
} catch (StorageClientException $e) {
if ($e->getStringCode() !== 'storage.components.cannotDeleteConfiguration') {
throw $e;
}
$editorClient->deleteSession($sessionId);
}
}
}
// Handle Python/R sandboxes via sandbox-service.
// Configs are bound to creatorToken.id, not userId: a user who leaves and rejoins gets a new token,
// so their old sandbox configs are reaped here even if the user is back — intentional, matches original behavior.
$appsClient = new AppsApiClient(new ApiClientConfiguration(
baseUrl: $serviceClient->getSandboxesServiceUrl(),
storageToken: $token,
userAgent: 'Keboola CLI Utils',
));
$storageComponents = new Components($storageClient);
$sandboxConfigMap = [];
foreach ($storageComponents->listComponentConfigurations(
(new ListComponentConfigurationsOptions())->setComponentId('keboola.sandboxes'),
) as $config) {
$sandboxConfigMap[$config['id']] = [
'creatorTokenId' => $config['creatorToken']['id'] ?? null,
'shared' => (bool) ($config['configuration']['runtime']['shared'] ?? false),
];
}
$queueClient = new JobQueueClient($serviceClient->getQueueUrl(), $token);
foreach ($appsClient->listApps(types: ['python', 'r']) as $app) {
$configInfo = $sandboxConfigMap[$app->getConfigId()] ?? null;
$creatorTokenId = $configInfo['creatorTokenId'] ?? null;
if ($creatorTokenId !== null && isset($activeTokenIds[$creatorTokenId])) {
continue;
}
if (!$includeShared && ($configInfo['shared'] ?? false)) {
$output->writeln(sprintf(
'Skipping shared sandbox config keboola.sandboxes/%s for app %s',
$app->getConfigId(),
$app->getId(),
));
continue;
}
$output->writeln(sprintf(
'Deleting sandbox config keboola.sandboxes/%s (branch %s) for app %s',
$app->getConfigId(),
$app->getBranchId() ?? 'default',
$app->getId(),
));
$totalDeleted++;
if ($force) {
try {
$queueClient->createJob(new JobData(
componentId: 'keboola.sandboxes',
configId: $app->getConfigId(),
configData: [
'parameters' => [
'task' => 'delete',
'id' => $app->getId(),
],
],
branchId: $app->getBranchId(),
));
} catch (\Throwable $e) {
// The job normally deletes the app on success; if it fails the app may be partially
// deleted, so finish cleanup directly rather than leaving it in an inconsistent state.
$output->writeln(sprintf(
'WARN: Job creation failed for app %s, falling back to direct deletion: %s',
$app->getId(),
$e->getMessage(),
));
$appsClient->deleteApp($app->getId());
try {
// First call moves the configuration to trash, second call permanently purges it.
$storageComponents->deleteConfiguration('keboola.sandboxes', $app->getConfigId());
$storageComponents->deleteConfiguration('keboola.sandboxes', $app->getConfigId());
} catch (StorageClientException $e) {
if ($e->getStringCode() !== 'storage.components.cannotDeleteConfiguration') {
throw $e;
}
}
}
}
}
$output->writeln(sprintf('%d sessions/apps deleted', $totalDeleted));
return 0;
}
}