forked from singlestore-labs/singlestoredb-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkspace.py
More file actions
1995 lines (1686 loc) · 62.5 KB
/
workspace.py
File metadata and controls
1995 lines (1686 loc) · 62.5 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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""SingleStoreDB Workspace Management."""
from __future__ import annotations
import datetime
import glob
import io
import os
import re
import time
from collections.abc import Mapping
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from .. import config
from .. import connection
from ..exceptions import ManagementError
from .billing_usage import BillingUsageItem
from .files import FileLocation
from .files import FilesObject
from .files import FilesObjectBytesReader
from .files import FilesObjectBytesWriter
from .files import FilesObjectTextReader
from .files import FilesObjectTextWriter
from .manager import Manager
from .organization import Organization
from .region import Region
from .utils import camel_to_snake_dict
from .utils import from_datetime
from .utils import NamedList
from .utils import PathLike
from .utils import snake_to_camel
from .utils import snake_to_camel_dict
from .utils import to_datetime
from .utils import ttl_property
from .utils import vars_to_str
def get_organization() -> Organization:
"""Get the organization."""
return manage_workspaces().organization
def get_secret(name: str) -> Optional[str]:
"""Get a secret from the organization."""
return get_organization().get_secret(name).value
def get_workspace_group(
workspace_group: Optional[Union[WorkspaceGroup, str]] = None,
) -> WorkspaceGroup:
"""Get the stage for the workspace group."""
if isinstance(workspace_group, WorkspaceGroup):
return workspace_group
elif workspace_group:
return manage_workspaces().workspace_groups[workspace_group]
elif 'SINGLESTOREDB_WORKSPACE_GROUP' in os.environ:
return manage_workspaces().workspace_groups[
os.environ['SINGLESTOREDB_WORKSPACE_GROUP']
]
raise RuntimeError('no workspace group specified')
def get_stage(
workspace_group: Optional[Union[WorkspaceGroup, str]] = None,
) -> Stage:
"""Get the stage for the workspace group."""
return get_workspace_group(workspace_group).stage
def get_workspace(
workspace_group: Optional[Union[WorkspaceGroup, str]] = None,
workspace: Optional[Union[Workspace, str]] = None,
) -> Workspace:
"""Get the workspaces for a workspace_group."""
if isinstance(workspace, Workspace):
return workspace
wg = get_workspace_group(workspace_group)
if workspace:
return wg.workspaces[workspace]
elif 'SINGLESTOREDB_WORKSPACE' in os.environ:
return wg.workspaces[
os.environ['SINGLESTOREDB_WORKSPACE']
]
raise RuntimeError('no workspace group specified')
class Stage(FileLocation):
"""
Stage manager.
This object is not instantiated directly.
It is returned by ``WorkspaceGroup.stage`` or ``StarterWorkspace.stage``.
"""
def __init__(self, deployment_id: str, manager: WorkspaceManager):
self._deployment_id = deployment_id
self._manager = manager
def open(
self,
stage_path: PathLike,
mode: str = 'r',
encoding: Optional[str] = None,
) -> Union[io.StringIO, io.BytesIO]:
"""
Open a Stage path for reading or writing.
Parameters
----------
stage_path : Path or str
The stage path to read / write
mode : str, optional
The read / write mode. The following modes are supported:
* 'r' open for reading (default)
* 'w' open for writing, truncating the file first
* 'x' create a new file and open it for writing
The data type can be specified by adding one of the following:
* 'b' binary mode
* 't' text mode (default)
encoding : str, optional
The string encoding to use for text
Returns
-------
FilesObjectBytesReader - 'rb' or 'b' mode
FilesObjectBytesWriter - 'wb' or 'xb' mode
FilesObjectTextReader - 'r' or 'rt' mode
FilesObjectTextWriter - 'w', 'x', 'wt' or 'xt' mode
"""
if '+' in mode or 'a' in mode:
raise ValueError('modifying an existing stage file is not supported')
if 'w' in mode or 'x' in mode:
exists = self.exists(stage_path)
if exists:
if 'x' in mode:
raise FileExistsError(f'stage path already exists: {stage_path}')
self.remove(stage_path)
if 'b' in mode:
return FilesObjectBytesWriter(b'', self, stage_path)
return FilesObjectTextWriter('', self, stage_path)
if 'r' in mode:
content = self.download_file(stage_path)
if isinstance(content, bytes):
if 'b' in mode:
return FilesObjectBytesReader(content)
encoding = 'utf-8' if encoding is None else encoding
return FilesObjectTextReader(content.decode(encoding))
if isinstance(content, str):
return FilesObjectTextReader(content)
raise ValueError(f'unrecognized file content type: {type(content)}')
raise ValueError(f'must have one of create/read/write mode specified: {mode}')
def upload_file(
self,
local_path: Union[PathLike, io.IOBase],
stage_path: PathLike,
*,
overwrite: bool = False,
) -> FilesObject:
"""
Upload a local file.
Parameters
----------
local_path : Path or str or file-like
Path to the local file or an open file object
stage_path : Path or str
Path to the stage file
overwrite : bool, optional
Should the ``stage_path`` be overwritten if it exists already?
"""
if isinstance(local_path, io.IOBase):
pass
elif not os.path.isfile(local_path):
raise IsADirectoryError(f'local path is not a file: {local_path}')
if self.exists(stage_path):
if not overwrite:
raise OSError(f'stage path already exists: {stage_path}')
self.remove(stage_path)
if isinstance(local_path, io.IOBase):
return self._upload(local_path, stage_path, overwrite=overwrite)
return self._upload(open(local_path, 'rb'), stage_path, overwrite=overwrite)
def upload_folder(
self,
local_path: PathLike,
stage_path: PathLike,
*,
overwrite: bool = False,
recursive: bool = True,
include_root: bool = False,
ignore: Optional[Union[PathLike, List[PathLike]]] = None,
) -> FilesObject:
"""
Upload a folder recursively.
Only the contents of the folder are uploaded. To include the
folder name itself in the target path use ``include_root=True``.
Parameters
----------
local_path : Path or str
Local directory to upload
stage_path : Path or str
Path of stage folder to upload to
overwrite : bool, optional
If a file already exists, should it be overwritten?
recursive : bool, optional
Should nested folders be uploaded?
include_root : bool, optional
Should the local root folder itself be uploaded as the top folder?
ignore : Path or str or List[Path] or List[str], optional
Glob patterns of files to ignore, for example, '**/*.pyc` will
ignore all '*.pyc' files in the directory tree
"""
if not os.path.isdir(local_path):
raise NotADirectoryError(f'local path is not a directory: {local_path}')
if self.exists(stage_path) and not self.is_dir(stage_path):
raise NotADirectoryError(f'stage path is not a directory: {stage_path}')
ignore_files = set()
if ignore:
if isinstance(ignore, list):
for item in ignore:
ignore_files.update(glob.glob(str(item), recursive=recursive))
else:
ignore_files.update(glob.glob(str(ignore), recursive=recursive))
parent_dir = os.path.basename(os.getcwd())
files = glob.glob(os.path.join(local_path, '**'), recursive=recursive)
for src in files:
if ignore_files and src in ignore_files:
continue
target = os.path.join(parent_dir, src) if include_root else src
self.upload_file(src, target, overwrite=overwrite)
return self.info(stage_path)
def _upload(
self,
content: Union[str, bytes, io.IOBase],
stage_path: PathLike,
*,
overwrite: bool = False,
) -> FilesObject:
"""
Upload content to a stage file.
Parameters
----------
content : str or bytes or file-like
Content to upload to stage
stage_path : Path or str
Path to the stage file
overwrite : bool, optional
Should the ``stage_path`` be overwritten if it exists already?
"""
if self.exists(stage_path):
if not overwrite:
raise OSError(f'stage path already exists: {stage_path}')
self.remove(stage_path)
self._manager._put(
f'stage/{self._deployment_id}/fs/{stage_path}',
files={'file': content},
headers={'Content-Type': None},
)
return self.info(stage_path)
def mkdir(self, stage_path: PathLike, overwrite: bool = False) -> FilesObject:
"""
Make a directory in the stage.
Parameters
----------
stage_path : Path or str
Path of the folder to create
overwrite : bool, optional
Should the stage path be overwritten if it exists already?
Returns
-------
FilesObject
"""
stage_path = re.sub(r'/*$', r'', str(stage_path)) + '/'
if self.exists(stage_path):
if not overwrite:
return self.info(stage_path)
self.remove(stage_path)
self._manager._put(
f'stage/{self._deployment_id}/fs/{stage_path}?isFile=false',
)
return self.info(stage_path)
mkdirs = mkdir
def rename(
self,
old_path: PathLike,
new_path: PathLike,
*,
overwrite: bool = False,
) -> FilesObject:
"""
Move the stage file to a new location.
Paraemeters
-----------
old_path : Path or str
Original location of the path
new_path : Path or str
New location of the path
overwrite : bool, optional
Should the ``new_path`` be overwritten if it exists already?
"""
if not self.exists(old_path):
raise OSError(f'stage path does not exist: {old_path}')
if self.exists(new_path):
if not overwrite:
raise OSError(f'stage path already exists: {new_path}')
if str(old_path).endswith('/') and not str(new_path).endswith('/'):
raise OSError('original and new paths are not the same type')
if str(new_path).endswith('/'):
self.removedirs(new_path)
else:
self.remove(new_path)
self._manager._patch(
f'stage/{self._deployment_id}/fs/{old_path}',
json=dict(newPath=new_path),
)
return self.info(new_path)
def info(self, stage_path: PathLike) -> FilesObject:
"""
Return information about a stage location.
Parameters
----------
stage_path : Path or str
Path to the stage location
Returns
-------
FilesObject
"""
res = self._manager._get(
re.sub(r'/+$', r'/', f'stage/{self._deployment_id}/fs/{stage_path}'),
params=dict(metadata=1),
).json()
return FilesObject.from_dict(res, self)
def exists(self, stage_path: PathLike) -> bool:
"""
Does the given stage path exist?
Parameters
----------
stage_path : Path or str
Path to stage object
Returns
-------
bool
"""
try:
self.info(stage_path)
return True
except ManagementError as exc:
if exc.errno == 404:
return False
raise
def is_dir(self, stage_path: PathLike) -> bool:
"""
Is the given stage path a directory?
Parameters
----------
stage_path : Path or str
Path to stage object
Returns
-------
bool
"""
try:
return self.info(stage_path).type == 'directory'
except ManagementError as exc:
if exc.errno == 404:
return False
raise
def is_file(self, stage_path: PathLike) -> bool:
"""
Is the given stage path a file?
Parameters
----------
stage_path : Path or str
Path to stage object
Returns
-------
bool
"""
try:
return self.info(stage_path).type != 'directory'
except ManagementError as exc:
if exc.errno == 404:
return False
raise
def _listdir(self, stage_path: PathLike, *, recursive: bool = False) -> List[str]:
"""
Return the names of files in a directory.
Parameters
----------
stage_path : Path or str
Path to the folder in Stage
recursive : bool, optional
Should folders be listed recursively?
"""
res = self._manager._get(
f'stage/{self._deployment_id}/fs/{stage_path}',
).json()
if recursive:
out = []
for item in res['content'] or []:
out.append(item['path'])
if item['type'] == 'directory':
out.extend(self._listdir(item['path'], recursive=recursive))
return out
return [x['path'] for x in res['content'] or []]
def listdir(
self,
stage_path: PathLike = '/',
*,
recursive: bool = False,
) -> List[str]:
"""
List the files / folders at the given path.
Parameters
----------
stage_path : Path or str, optional
Path to the stage location
Returns
-------
List[str]
"""
stage_path = re.sub(r'^(\./|/)+', r'', str(stage_path))
stage_path = re.sub(r'/+$', r'', stage_path) + '/'
if self.is_dir(stage_path):
out = self._listdir(stage_path, recursive=recursive)
if stage_path != '/':
stage_path_n = len(stage_path.split('/')) - 1
out = ['/'.join(x.split('/')[stage_path_n:]) for x in out]
return out
raise NotADirectoryError(f'stage path is not a directory: {stage_path}')
def download_file(
self,
stage_path: PathLike,
local_path: Optional[PathLike] = None,
*,
overwrite: bool = False,
encoding: Optional[str] = None,
) -> Optional[Union[bytes, str]]:
"""
Download the content of a stage path.
Parameters
----------
stage_path : Path or str
Path to the stage file
local_path : Path or str
Path to local file target location
overwrite : bool, optional
Should an existing file be overwritten if it exists?
encoding : str, optional
Encoding used to convert the resulting data
Returns
-------
bytes or str - ``local_path`` is None
None - ``local_path`` is a Path or str
"""
if local_path is not None and not overwrite and os.path.exists(local_path):
raise OSError('target file already exists; use overwrite=True to replace')
if self.is_dir(stage_path):
raise IsADirectoryError(f'stage path is a directory: {stage_path}')
out = self._manager._get(
f'stage/{self._deployment_id}/fs/{stage_path}',
).content
if local_path is not None:
with open(local_path, 'wb') as outfile:
outfile.write(out)
return None
if encoding:
return out.decode(encoding)
return out
def download_folder(
self,
stage_path: PathLike,
local_path: PathLike = '.',
*,
overwrite: bool = False,
) -> None:
"""
Download a Stage folder to a local directory.
Parameters
----------
stage_path : Path or str
Path to the stage file
local_path : Path or str
Path to local directory target location
overwrite : bool, optional
Should an existing directory / files be overwritten if they exist?
"""
if local_path is not None and not overwrite and os.path.exists(local_path):
raise OSError(
'target directory already exists; '
'use overwrite=True to replace',
)
if not self.is_dir(stage_path):
raise NotADirectoryError(f'stage path is not a directory: {stage_path}')
for f in self.listdir(stage_path, recursive=True):
if self.is_dir(f):
continue
target = os.path.normpath(os.path.join(local_path, f))
os.makedirs(os.path.dirname(target), exist_ok=True)
self.download_file(f, target, overwrite=overwrite)
def remove(self, stage_path: PathLike) -> None:
"""
Delete a stage location.
Parameters
----------
stage_path : Path or str
Path to the stage location
"""
if self.is_dir(stage_path):
raise IsADirectoryError(
'stage path is a directory, '
f'use rmdir or removedirs: {stage_path}',
)
self._manager._delete(f'stage/{self._deployment_id}/fs/{stage_path}')
def removedirs(self, stage_path: PathLike) -> None:
"""
Delete a stage folder recursively.
Parameters
----------
stage_path : Path or str
Path to the stage location
"""
stage_path = re.sub(r'/*$', r'', str(stage_path)) + '/'
self._manager._delete(f'stage/{self._deployment_id}/fs/{stage_path}')
def rmdir(self, stage_path: PathLike) -> None:
"""
Delete a stage folder.
Parameters
----------
stage_path : Path or str
Path to the stage location
"""
stage_path = re.sub(r'/*$', r'', str(stage_path)) + '/'
if self.listdir(stage_path):
raise OSError(f'stage folder is not empty, use removedirs: {stage_path}')
self._manager._delete(f'stage/{self._deployment_id}/fs/{stage_path}')
def __str__(self) -> str:
"""Return string representation."""
return vars_to_str(self)
def __repr__(self) -> str:
"""Return string representation."""
return str(self)
StageObject = FilesObject # alias for backward compatibility
class Workspace(object):
"""
SingleStoreDB workspace definition.
This object is not instantiated directly. It is used in the results
of API calls on the :class:`WorkspaceManager`. Workspaces are created using
:meth:`WorkspaceManager.create_workspace`, or existing workspaces are
accessed by either :attr:`WorkspaceManager.workspaces` or by calling
:meth:`WorkspaceManager.get_workspace`.
See Also
--------
:meth:`WorkspaceManager.create_workspace`
:meth:`WorkspaceManager.get_workspace`
:attr:`WorkspaceManager.workspaces`
"""
name: str
id: str
group_id: str
size: str
state: str
created_at: Optional[datetime.datetime]
terminated_at: Optional[datetime.datetime]
endpoint: Optional[str]
auto_suspend: Optional[Dict[str, Any]]
cache_config: Optional[int]
deployment_type: Optional[str]
resume_attachments: Optional[List[Dict[str, Any]]]
scaling_progress: Optional[int]
last_resumed_at: Optional[datetime.datetime]
def __init__(
self,
name: str,
workspace_id: str,
workspace_group: Union[str, 'WorkspaceGroup'],
size: str,
state: str,
created_at: Union[str, datetime.datetime],
terminated_at: Optional[Union[str, datetime.datetime]] = None,
endpoint: Optional[str] = None,
auto_suspend: Optional[Dict[str, Any]] = None,
cache_config: Optional[int] = None,
deployment_type: Optional[str] = None,
resume_attachments: Optional[List[Dict[str, Any]]] = None,
scaling_progress: Optional[int] = None,
last_resumed_at: Optional[Union[str, datetime.datetime]] = None,
):
#: Name of the workspace
self.name = name
#: Unique ID of the workspace
self.id = workspace_id
#: Unique ID of the workspace group
if isinstance(workspace_group, WorkspaceGroup):
self.group_id = workspace_group.id
else:
self.group_id = workspace_group
#: Size of the workspace in workspace size notation (S-00, S-1, etc.)
self.size = size
#: State of the workspace: PendingCreation, Transitioning, Active,
#: Terminated, Suspended, Resuming, Failed
self.state = state.strip()
#: Timestamp of when the workspace was created
self.created_at = to_datetime(created_at)
#: Timestamp of when the workspace was terminated
self.terminated_at = to_datetime(terminated_at)
#: Hostname (or IP address) of the workspace database server
self.endpoint = endpoint
#: Current auto-suspend settings
self.auto_suspend = camel_to_snake_dict(auto_suspend)
#: Multiplier for the persistent cache
self.cache_config = cache_config
#: Deployment type of the workspace
self.deployment_type = deployment_type
#: Database attachments
self.resume_attachments = [
camel_to_snake_dict(x) # type: ignore
for x in resume_attachments or []
if x is not None
]
#: Current progress percentage for scaling the workspace
self.scaling_progress = scaling_progress
#: Timestamp when workspace was last resumed
self.last_resumed_at = to_datetime(last_resumed_at)
self._manager: Optional[WorkspaceManager] = None
def __str__(self) -> str:
"""Return string representation."""
return vars_to_str(self)
def __repr__(self) -> str:
"""Return string representation."""
return str(self)
@classmethod
def from_dict(cls, obj: Dict[str, Any], manager: 'WorkspaceManager') -> 'Workspace':
"""
Construct a Workspace from a dictionary of values.
Parameters
----------
obj : dict
Dictionary of values
manager : WorkspaceManager, optional
The WorkspaceManager the Workspace belongs to
Returns
-------
:class:`Workspace`
"""
out = cls(
name=obj['name'],
workspace_id=obj['workspaceID'],
workspace_group=obj['workspaceGroupID'],
size=obj.get('size', 'Unknown'),
state=obj['state'],
created_at=obj['createdAt'],
terminated_at=obj.get('terminatedAt'),
endpoint=obj.get('endpoint'),
auto_suspend=obj.get('autoSuspend'),
cache_config=obj.get('cacheConfig'),
deployment_type=obj.get('deploymentType'),
last_resumed_at=obj.get('lastResumedAt'),
resume_attachments=obj.get('resumeAttachments'),
scaling_progress=obj.get('scalingProgress'),
)
out._manager = manager
return out
def update(
self,
auto_suspend: Optional[Dict[str, Any]] = None,
cache_config: Optional[int] = None,
deployment_type: Optional[str] = None,
size: Optional[str] = None,
) -> None:
"""
Update the workspace definition.
Parameters
----------
auto_suspend : Dict[str, Any], optional
Auto-suspend mode for the workspace: IDLE, SCHEDULED, DISABLED
cache_config : int, optional
Specifies the multiplier for the persistent cache associated
with the workspace. If specified, it enables the cache configuration
multiplier. It can have one of the following values: 1, 2, or 4.
deployment_type : str, optional
The deployment type that will be applied to all the workspaces
within the group
size : str, optional
Size of the workspace (in workspace size notation), such as "S-1".
"""
if self._manager is None:
raise ManagementError(
msg='No workspace manager is associated with this object.',
)
data = {
k: v for k, v in dict(
autoSuspend=snake_to_camel_dict(auto_suspend),
cacheConfig=cache_config,
deploymentType=deployment_type,
size=size,
).items() if v is not None
}
self._manager._patch(f'workspaces/{self.id}', json=data)
self.refresh()
def refresh(self) -> Workspace:
"""Update the object to the current state."""
if self._manager is None:
raise ManagementError(
msg='No workspace manager is associated with this object.',
)
new_obj = self._manager.get_workspace(self.id)
for name, value in vars(new_obj).items():
if isinstance(value, Mapping):
setattr(self, name, snake_to_camel_dict(value))
else:
setattr(self, name, value)
return self
def terminate(
self,
wait_on_terminated: bool = False,
wait_interval: int = 10,
wait_timeout: int = 600,
force: bool = False,
) -> None:
"""
Terminate the workspace.
Parameters
----------
wait_on_terminated : bool, optional
Wait for the workspace to go into 'Terminated' mode before returning
wait_interval : int, optional
Number of seconds between each server check
wait_timeout : int, optional
Total number of seconds to check server before giving up
force : bool, optional
Should the workspace group be terminated even if it has workspaces?
Raises
------
ManagementError
If timeout is reached
"""
if self._manager is None:
raise ManagementError(
msg='No workspace manager is associated with this object.',
)
force_str = 'true' if force else 'false'
self._manager._delete(f'workspaces/{self.id}?force={force_str}')
if wait_on_terminated:
self._manager._wait_on_state(
self._manager.get_workspace(self.id),
'Terminated', interval=wait_interval, timeout=wait_timeout,
)
self.refresh()
def connect(self, **kwargs: Any) -> connection.Connection:
"""
Create a connection to the database server for this workspace.
Parameters
----------
**kwargs : keyword-arguments, optional
Parameters to the SingleStoreDB `connect` function except host
and port which are supplied by the workspace object
Returns
-------
:class:`Connection`
"""
if not self.endpoint:
raise ManagementError(
msg='An endpoint has not been set in this workspace configuration',
)
kwargs['host'] = self.endpoint
return connection.connect(**kwargs)
def suspend(
self,
wait_on_suspended: bool = False,
wait_interval: int = 20,
wait_timeout: int = 600,
) -> None:
"""
Suspend the workspace.
Parameters
----------
wait_on_suspended : bool, optional
Wait for the workspace to go into 'Suspended' mode before returning
wait_interval : int, optional
Number of seconds between each server check
wait_timeout : int, optional
Total number of seconds to check server before giving up
Raises
------
ManagementError
If timeout is reached
"""
if self._manager is None:
raise ManagementError(
msg='No workspace manager is associated with this object.',
)
self._manager._post(f'workspaces/{self.id}/suspend')
if wait_on_suspended:
self._manager._wait_on_state(
self._manager.get_workspace(self.id),
'Suspended', interval=wait_interval, timeout=wait_timeout,
)
self.refresh()
def resume(
self,
disable_auto_suspend: bool = False,
wait_on_resumed: bool = False,
wait_interval: int = 20,
wait_timeout: int = 600,
) -> None:
"""
Resume the workspace.
Parameters
----------
disable_auto_suspend : bool, optional
Should auto-suspend be disabled?
wait_on_resumed : bool, optional
Wait for the workspace to go into 'Resumed' or 'Active' mode before returning
wait_interval : int, optional
Number of seconds between each server check
wait_timeout : int, optional
Total number of seconds to check server before giving up
Raises
------
ManagementError
If timeout is reached
"""
if self._manager is None:
raise ManagementError(
msg='No workspace manager is associated with this object.',
)
self._manager._post(
f'workspaces/{self.id}/resume',
json=dict(disableAutoSuspend=disable_auto_suspend),
)
if wait_on_resumed:
self._manager._wait_on_state(
self._manager.get_workspace(self.id),
['Resumed', 'Active'], interval=wait_interval, timeout=wait_timeout,
)
self.refresh()
class WorkspaceGroup(object):
"""
SingleStoreDB workspace group definition.
This object is not instantiated directly. It is used in the results
of API calls on the :class:`WorkspaceManager`. Workspace groups are created using
:meth:`WorkspaceManager.create_workspace_group`, or existing workspace groups are
accessed by either :attr:`WorkspaceManager.workspace_groups` or by calling
:meth:`WorkspaceManager.get_workspace_group`.
See Also
--------
:meth:`WorkspaceManager.create_workspace_group`