-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathBackup.php
More file actions
502 lines (465 loc) · 15.4 KB
/
Backup.php
File metadata and controls
502 lines (465 loc) · 15.4 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
<?php
/**
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Spanner;
use Closure;
use DateTimeInterface;
use Google\ApiCore\Options\CallOptions;
use Google\ApiCore\ValidationException;
use Google\Cloud\Core\ApiHelperTrait;
use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\Core\Iterator\ItemIterator;
use Google\Cloud\Core\LongRunning\LongRunningClientConnection;
use Google\Cloud\Core\LongRunning\LongRunningOperation;
use Google\Cloud\Core\OptionsValidator;
use Google\Cloud\Spanner\Admin\Database\V1\Backup\State;
use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;
use Google\Cloud\Spanner\Admin\Database\V1\CopyBackupRequest;
use Google\Cloud\Spanner\Admin\Database\V1\CreateBackupRequest;
use Google\Cloud\Spanner\Admin\Database\V1\DeleteBackupRequest;
use Google\Cloud\Spanner\Admin\Database\V1\GetBackupRequest;
use Google\Cloud\Spanner\Admin\Database\V1\UpdateBackupRequest;
use Google\LongRunning\ListOperationsRequest;
use Google\LongRunning\Operation as OperationProto;
/**
* Represents a Cloud Spanner Backup.
*
* Example:
* ```
* use Google\Cloud\Spanner\SpannerClient;
*
* $spanner = new SpannerClient(['projectId' => 'my-project']);
*
* $backup = $spanner->instance('my-instance')->backup('my-backup');
* ```
*/
class Backup
{
use RequestTrait;
use ApiHelperTrait;
const STATE_READY = State::READY;
const STATE_CREATING = State::CREATING;
private array $info;
/**
* Create an object representing a Backup.
*
* @internal Backup is constructed by the {@see Instance} class.
*
* @param DatabaseAdminClient $databaseAdminClient The database admin client to make backup RPC
* calls.
* @param Serializer $serializer The serializer instance to encode/decode messages.
* @param Instance $instance The instance in which the backup exists.
* @param string $projectId The project ID.
* @param string $name The backup name or ID.
* @param array $options [Optional] {
* Backup options.
* @type array $backup The backup info.
* }
*/
public function __construct(
private DatabaseAdminClient $databaseAdminClient,
private Serializer $serializer,
private Instance $instance,
private string $projectId,
private string $name,
array $options = []
) {
$this->name = $this->fullyQualifiedBackupName($name);
$this->info = $options['info'] ?? [];
$this->optionsValidator = new OptionsValidator($serializer);
}
/**
* Create a Cloud Spanner backup for a database.
*
* Example:
* ```
* $operation = $backup->create('my-database', new \DateTime('+7 hours'));
* ```
*
* @param string $database The name or id of the database that this backup is for.
* @param DateTimeInterface $expireTime The expiration time of the backup,
* with microseconds granularity that must be at least 6 hours and
* at most 366 days. Once the expireTime has passed, the backup is
* eligible to be automatically deleted by Cloud Spanner.
* @param array $options [optional] {
* Configuration Options.
*
* @type DateTimeInterface $versionTime The version time for the externally
* consistent copy of the database. If not present, it will be the same
* as the create time of the backup.
* }
* @return LongRunningOperation
* @throws \InvalidArgumentException
*/
public function create(
string $database,
DateTimeInterface $expireTime,
array $options = []
): LongRunningOperation {
$options += [
'parent' => $this->instance->name(),
'backupId' => DatabaseAdminClient::parseName($this->name)['backup'],
'backup' => [
'database' => $this->instance->database($database)->name(),
'expireTime' => $this->formatTimeAsArray($expireTime),
],
];
if ($versionTime = $this->pluck('versionTime', $options, false)) {
if (!$versionTime instanceof DateTimeInterface) {
throw new \InvalidArgumentException(
'Optional argument `versionTime` must be a DateTimeInterface'
);
}
$options['backup']['versionTime'] = $this->formatTimeAsArray($versionTime);
}
/**
* @var CreateBackupRequest $createBackup
* @var array $callOptions
*/
[$createBackup, $callOptions] = $this->validateOptions(
$options,
new CreateBackupRequest(),
CallOptions::class
);
$operation = $this->databaseAdminClient->createBackup($createBackup, $callOptions + [
'resource-prefix' => $this->instance->name(),
]);
return $this->operationFromOperationResponse($operation);
}
/**
* Create a copy of an existing backup in Cloud Spanner.
*
* Example:
* ```
* $sourceInstance = $spanner->instance('source-instance-id');
* $destInstance = $spanner->instance('destination-instance-id');
* $sourceBackup = $sourceInstance->backup('source-backup-id');
* $destBackup = $destInstance->backup('new-backup-id');
*
* $operation = $sourceBackup->createCopy($destBackup, new \DateTime('+7 hours'));
* ```
*
* @param Backup $newBackup The backup object that needs to be created as a copy.
* @param DateTimeInterface $expireTime The expiration time of the backup,
* with microseconds granularity that must be at least 6 hours and
* at most 366 days. Once the expireTime has passed, the backup is
* eligible to be automatically deleted by Cloud Spanner.
* @param array $options [optional] {
* Configuration Options.
* }
* @return LongRunningOperation
* @throws \InvalidArgumentException
*/
public function createCopy(
Backup $newBackup,
DateTimeInterface $expireTime,
array $options = []
): LongRunningOperation {
$options += [
'parent' => $newBackup->instance->name(),
'backupId' => DatabaseAdminClient::parseName($newBackup->name)['backup'],
'sourceBackup' => $this->fullyQualifiedBackupName($this->name),
'expireTime' => $this->formatTimeAsArray($expireTime)
];
/**
* @var CopyBackupRequest $copyBackup
* @var array $callOptions
*/
[$copyBackup, $callOptions] = $this->validateOptions(
$options,
new CopyBackupRequest(),
CallOptions::class
);
$operation = $this->databaseAdminClient->copyBackup($copyBackup, $callOptions + [
'resource-prefix' => $this->instance->name(),
]);
return $this->operationFromOperationResponse($operation);
}
/**
* Marks this backup for deletion.
*
* Example:
* ```
* $backup->delete();
* ```
*
* @param array $options [optional] Configuration options.
* @return void
*/
public function delete(array $options = []): void
{
$options += [
'name' => $this->name
];
/**
* @var DeleteBackupRequest $deleteBackup
* @var array $callOptions
*/
[$deleteBackup, $callOptions] = $this->validateOptions(
$options,
new DeleteBackupRequest(),
CallOptions::class,
);
$this->databaseAdminClient->deleteBackup($deleteBackup, $callOptions + [
'resource-prefix' => $this->name,
]);
}
/**
* Tests whether this backup exists.
*
* This method sends a service call.
*
* Example:
* ```
* if ($backup->exists()) {
* echo 'Backup exists!';
* }
* ```
*
* @param array $options [optional] Configuration options.
* @return bool
*/
public function exists(array $options = []): bool
{
try {
$this->reload($options);
} catch (NotFoundException $ex) {
return false;
}
return true;
}
/**
* Get info of a Cloud Spanner backup from cache or request.
*
* Example:
* ```
* $info = $backup->info();
* ```
*
* @param array $options [optional] Configuration options.
* @return array
*/
public function info(array $options = []): array
{
if (!$this->info) {
$this->info = $this->reload($options);
}
return $this->info;
}
/**
* Return the backup name.
*
* Example:
* ```
* $name = $backup->name();
* ```
*
* @return string
*/
public function name(): string
{
return $this->name;
}
/**
* Reload the backup info from the Cloud Spanner API.
*
* Example:
* ```
* $info = $backup->reload();
* ```
*
* @param array $options [optional] Configuration options.
* @return array
*/
public function reload(array $options = []): array
{
$options += [
'name' => $this->name
];
/**
* @var GetBackupRequest $getBackup
* @var array $callOptions
*/
[$getBackup, $callOptions] = $this->validateOptions(
$options,
new GetBackupRequest(),
CallOptions::class,
);
$response = $this->databaseAdminClient->getBackup($getBackup, $callOptions + [
'resource-prefix' => $this->name,
]);
return $this->info = $this->handleResponse($response);
}
/**
* Return the backup state.
*
* When backups are created, they may take some time before
* they are ready for use. This method allows for checking whether a
* backup is ready. Note that this value is cached within the class instance,
* so if you are polling it, first call {@see \Google\Cloud\Spanner\Backup::reload()}
* to refresh the cached value.
*
* Example:
* ```
* use Google\Cloud\Spanner\Backup;
*
* if ($backup->state() === Backup::STATE_READY) {
* echo 'Backup is ready!';
* }
* ```
*
* @param array $options [optional] Configuration options.
* @return int|null
*/
public function state(array $options = []): int|null
{
$info = $this->info($options);
return (isset($info['state']))
? $info['state']
: null;
}
/**
* Update the expire time of this backup.
*
* Example:
* ```
* $info = $backup->updateExpireTime(new \DateTime("+ 7 hours"));
* ```
*
* @param DateTimeInterface $newTimestamp New expire time.
* @param array $options [optional] Configuration options.
*
* @return array
*/
public function updateExpireTime(DateTimeInterface $newTimestamp, array $options = []): array
{
$options['expireTime'] = $this->formatTimeAsArray($newTimestamp);
/**
* @var UpdateBackupRequest $updateBackup
* @var array $callOptions
*/
[$updateBackup, $callOptions] = $this->validateOptions(
[
'backup' => $options + ['name' => $this->name()],
'updateMask' => $this->fieldMask($options),
],
new UpdateBackupRequest(),
CallOptions::class,
);
$response = $this->databaseAdminClient->updateBackup($updateBackup, $callOptions + [
'resource-prefix' => $this->name,
]);
return $this->info = $this->handleResponse($response);
}
/**
* Resume a Long Running Operation
*
* Example:
* ```
* $operation = $backup->resumeOperation($operationName);
* ```
*
* @param string $operationName The Long Running Operation name.
* @return LongRunningOperation
*/
public function resumeOperation(string $operationName, array $options = []): LongRunningOperation
{
return new LongRunningOperation(
new LongRunningClientConnection($this->databaseAdminClient, $this->serializer),
$operationName,
[
[
'typeUrl' => 'type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata',
'callable' => $this->backupResultFunction(),
]
],
$options
);
}
/**
* List long running operations.
*
* Example:
* ```
* $operations = $backup->longRunningOperations();
* ```
*
* @param array $options [optional] {
* Configuration Options.
*
* @type string $name The name of the operation collection.
* @type string $filter The standard list filter.
* @type int $pageSize Maximum number of results to return per
* request.
* @type int $resultLimit Limit the number of results returned in total.
* **Defaults to** `0` (return all results).
* @type string $pageToken A previously-returned page token used to
* resume the loading of results from a specific point.
* }
* @return ItemIterator<LongRunningOperation>
*/
public function longRunningOperations(array $options = []): ItemIterator
{
/**
* @var ListOperationsRequest $listOperations
* @var array $callOptions
*/
[$listOperations, $callOptions] = $this->validateOptions(
$options,
new ListOperationsRequest(),
CallOptions::class,
);
$listOperations->setName($this->name . '/operations');
return $this->buildLongRunningIterator(
[$this->databaseAdminClient->getOperationsClient(), 'listOperations'],
$listOperations,
$callOptions,
function (OperationProto $operation) {
return $this->resumeOperation(
$operation->getName(),
$this->handleResponse($operation)
);
}
);
}
/**
* Convert the simple backup name to a fully qualified name.
*
* @return string
*/
private function fullyQualifiedBackupName(string $name): string
{
$instance = DatabaseAdminClient::parseName($this->instance->name())['instance'];
try {
return DatabaseAdminClient::backupName(
$this->projectId,
$instance,
$name
);
//@codeCoverageIgnoreStart
} catch (ValidationException $e) {
return $name;
}
//@codeCoverageIgnoreEnd
}
private function backupResultFunction(): Closure
{
return function (array $backup) {
$name = DatabaseAdminClient::parseName($backup['name']);
return $this->instance->backup($name['backup'], $backup);
};
}
}