/
system.py
1501 lines (1251 loc) · 55.8 KB
/
system.py
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
# Copyright 2016 Google LLC
#
# 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.
import datetime
import operator
import os
import time
import unittest
import pytest
from google.api_core.datetime_helpers import DatetimeWithNanoseconds
from google.api_core.exceptions import DeadlineExceeded
from google.api_core.exceptions import TooManyRequests
from google.cloud.environment_vars import BIGTABLE_EMULATOR
from test_utils.retry import RetryErrors
from test_utils.retry import RetryResult
# from test_utils.system import EmulatorCreds
from test_utils.system import unique_resource_id
from google.cloud._helpers import _datetime_from_microseconds
from google.cloud._helpers import _microseconds_from_datetime
from google.cloud._helpers import UTC
from google.cloud.bigtable.client import Client
from google.cloud.bigtable.column_family import MaxVersionsGCRule
from google.cloud.bigtable.policy import Policy
from google.cloud.bigtable.policy import BIGTABLE_ADMIN_ROLE
from google.cloud.bigtable.row_filters import ApplyLabelFilter
from google.cloud.bigtable.row_filters import ColumnQualifierRegexFilter
from google.cloud.bigtable.row_filters import RowFilterChain
from google.cloud.bigtable.row_filters import RowFilterUnion
from google.cloud.bigtable.row_data import Cell
from google.cloud.bigtable.row_data import PartialRowData
from google.cloud.bigtable.row_set import RowSet
from google.cloud.bigtable.row_set import RowRange
# from google.cloud.bigtable_admin_v2.gapic import (
# bigtable_table_admin_client_config as table_admin_config,
# )
UNIQUE_SUFFIX = unique_resource_id("-")
LOCATION_ID = "us-central1-c"
INSTANCE_ID = "g-c-p" + UNIQUE_SUFFIX
INSTANCE_ID_DATA = "g-c-p-d" + UNIQUE_SUFFIX
TABLE_ID = "google-cloud-python-test-table"
CLUSTER_ID = INSTANCE_ID + "-cluster"
CLUSTER_ID_DATA = INSTANCE_ID_DATA + "-cluster"
SERVE_NODES = 3
COLUMN_FAMILY_ID1 = "col-fam-id1"
COLUMN_FAMILY_ID2 = "col-fam-id2"
COL_NAME1 = b"col-name1"
COL_NAME2 = b"col-name2"
COL_NAME3 = b"col-name3-but-other-fam"
CELL_VAL1 = b"cell-val"
CELL_VAL2 = b"cell-val-newer"
CELL_VAL3 = b"altcol-cell-val"
CELL_VAL4 = b"foo"
ROW_KEY = b"row-key"
ROW_KEY_ALT = b"row-key-alt"
EXISTING_INSTANCES = []
LABEL_KEY = "python-system"
label_stamp = (
datetime.datetime.utcnow()
.replace(microsecond=0, tzinfo=UTC)
.strftime("%Y-%m-%dt%H-%M-%S")
)
LABELS = {LABEL_KEY: str(label_stamp)}
KMS_KEY_NAME = os.environ.get("KMS_KEY_NAME", None)
class Config(object):
"""Run-time configuration to be modified at set-up.
This is a mutable stand-in to allow test set-up to modify
global state.
"""
CLIENT = None
INSTANCE = None
INSTANCE_DATA = None
CLUSTER = None
CLUSTER_DATA = None
IN_EMULATOR = False
def _retry_on_unavailable(exc):
"""Retry only errors whose status code is 'UNAVAILABLE'."""
from grpc import StatusCode
return exc.code() == StatusCode.UNAVAILABLE
retry_429 = RetryErrors(TooManyRequests, max_tries=9)
def setUpModule():
from google.cloud.exceptions import GrpcRendezvous
from google.cloud.bigtable.enums import Instance
# See: https://github.com/googleapis/google-cloud-python/issues/5928
# interfaces = table_admin_config.config["interfaces"]
# iface_config = interfaces["google.bigtable.admin.v2.BigtableTableAdmin"]
# methods = iface_config["methods"]
# create_table = methods["CreateTable"]
# create_table["timeout_millis"] = 90000
Config.IN_EMULATOR = os.getenv(BIGTABLE_EMULATOR) is not None
# Previously we created clients using a mock EmulatorCreds when targeting
# an emulator.
Config.CLIENT = Client(admin=True)
Config.INSTANCE = Config.CLIENT.instance(INSTANCE_ID, labels=LABELS)
Config.CLUSTER = Config.INSTANCE.cluster(
CLUSTER_ID, location_id=LOCATION_ID, serve_nodes=SERVE_NODES,
)
Config.INSTANCE_DATA = Config.CLIENT.instance(
INSTANCE_ID_DATA, instance_type=Instance.Type.DEVELOPMENT, labels=LABELS
)
Config.CLUSTER_DATA = Config.INSTANCE_DATA.cluster(
CLUSTER_ID_DATA, location_id=LOCATION_ID,
)
if not Config.IN_EMULATOR:
retry = RetryErrors(GrpcRendezvous, error_predicate=_retry_on_unavailable)
instances, failed_locations = retry(Config.CLIENT.list_instances)()
if len(failed_locations) != 0:
raise ValueError("List instances failed in module set up.")
EXISTING_INSTANCES[:] = instances
# After listing, create the test instances.
admin_op = Config.INSTANCE.create(clusters=[Config.CLUSTER])
admin_op.result(timeout=10)
data_op = Config.INSTANCE_DATA.create(clusters=[Config.CLUSTER_DATA])
data_op.result(timeout=10)
def tearDownModule():
if not Config.IN_EMULATOR:
retry_429(Config.INSTANCE.delete)()
retry_429(Config.INSTANCE_DATA.delete)()
class TestInstanceAdminAPI(unittest.TestCase):
def setUp(self):
if Config.IN_EMULATOR:
self.skipTest("Instance Admin API not supported in emulator")
self.instances_to_delete = []
def tearDown(self):
for instance in self.instances_to_delete:
retry_429(instance.delete)()
def test_list_instances(self):
instances, failed_locations = Config.CLIENT.list_instances()
self.assertEqual(failed_locations, [])
found = set([instance.name for instance in instances])
self.assertTrue(Config.INSTANCE.name in found)
def test_reload(self):
from google.cloud.bigtable import enums
# Use same arguments as Config.INSTANCE (created in `setUpModule`)
# so we can use reload() on a fresh instance.
alt_instance = Config.CLIENT.instance(INSTANCE_ID)
# Make sure metadata unset before reloading.
alt_instance.display_name = None
alt_instance.reload()
self.assertEqual(alt_instance.display_name, Config.INSTANCE.display_name)
self.assertEqual(alt_instance.labels, Config.INSTANCE.labels)
self.assertEqual(alt_instance.type_, enums.Instance.Type.PRODUCTION)
def test_create_instance_defaults(self):
from google.cloud.bigtable import enums
ALT_INSTANCE_ID = "ndef" + UNIQUE_SUFFIX
instance = Config.CLIENT.instance(ALT_INSTANCE_ID, labels=LABELS)
ALT_CLUSTER_ID = ALT_INSTANCE_ID + "-cluster"
serve_nodes = 1
cluster = instance.cluster(
ALT_CLUSTER_ID, location_id=LOCATION_ID, serve_nodes=serve_nodes
)
operation = instance.create(clusters=[cluster])
# Make sure this instance gets deleted after the test case.
self.instances_to_delete.append(instance)
# We want to make sure the operation completes.
operation.result(timeout=10)
# Create a new instance instance and make sure it is the same.
instance_alt = Config.CLIENT.instance(ALT_INSTANCE_ID)
instance_alt.reload()
self.assertEqual(instance, instance_alt)
self.assertEqual(instance.display_name, instance_alt.display_name)
# Make sure that by default a PRODUCTION type instance is created
self.assertIsNone(instance.type_)
self.assertEqual(instance_alt.type_, enums.Instance.Type.PRODUCTION)
def test_create_instance(self):
from google.cloud.bigtable import enums
_DEVELOPMENT = enums.Instance.Type.DEVELOPMENT
ALT_INSTANCE_ID = "new" + UNIQUE_SUFFIX
instance = Config.CLIENT.instance(
ALT_INSTANCE_ID, instance_type=_DEVELOPMENT, labels=LABELS
)
ALT_CLUSTER_ID = ALT_INSTANCE_ID + "-cluster"
cluster = instance.cluster(ALT_CLUSTER_ID, location_id=LOCATION_ID)
operation = instance.create(clusters=[cluster])
# Make sure this instance gets deleted after the test case.
self.instances_to_delete.append(instance)
# We want to make sure the operation completes.
operation.result(timeout=10)
# Create a new instance instance and make sure it is the same.
instance_alt = Config.CLIENT.instance(ALT_INSTANCE_ID)
instance_alt.reload()
self.assertEqual(instance, instance_alt)
self.assertEqual(instance.display_name, instance_alt.display_name)
self.assertEqual(instance.type_, instance_alt.type_)
self.assertEqual(instance_alt.labels, LABELS)
self.assertEqual(instance_alt.state, enums.Instance.State.READY)
def test_cluster_exists(self):
NONEXISTING_CLUSTER_ID = "cluster-id"
cluster = Config.INSTANCE.cluster(CLUSTER_ID)
alt_cluster = Config.INSTANCE.cluster(NONEXISTING_CLUSTER_ID)
self.assertTrue(cluster.exists())
self.assertFalse(alt_cluster.exists())
def test_instance_exists(self):
NONEXISTING_INSTANCE_ID = "instancer-id"
alt_instance = Config.CLIENT.instance(NONEXISTING_INSTANCE_ID)
self.assertTrue(Config.INSTANCE.exists())
self.assertFalse(alt_instance.exists())
def test_create_instance_w_two_clusters(self):
from google.cloud.bigtable import enums
from google.cloud.bigtable.table import ClusterState
_PRODUCTION = enums.Instance.Type.PRODUCTION
ALT_INSTANCE_ID = "dif" + UNIQUE_SUFFIX
instance = Config.CLIENT.instance(
ALT_INSTANCE_ID, instance_type=_PRODUCTION, labels=LABELS
)
ALT_CLUSTER_ID_1 = ALT_INSTANCE_ID + "-c1"
ALT_CLUSTER_ID_2 = ALT_INSTANCE_ID + "-c2"
LOCATION_ID_2 = "us-central1-f"
STORAGE_TYPE = enums.StorageType.HDD
serve_nodes = 1
cluster_1 = instance.cluster(
ALT_CLUSTER_ID_1,
location_id=LOCATION_ID,
serve_nodes=serve_nodes,
default_storage_type=STORAGE_TYPE,
)
cluster_2 = instance.cluster(
ALT_CLUSTER_ID_2,
location_id=LOCATION_ID_2,
serve_nodes=serve_nodes,
default_storage_type=STORAGE_TYPE,
)
operation = instance.create(clusters=[cluster_1, cluster_2])
# Make sure this instance gets deleted after the test case.
self.instances_to_delete.append(instance)
# We want to make sure the operation completes.
operation.result(timeout=120)
# Create a new instance instance and make sure it is the same.
instance_alt = Config.CLIENT.instance(ALT_INSTANCE_ID)
instance_alt.reload()
self.assertEqual(instance, instance_alt)
self.assertEqual(instance.display_name, instance_alt.display_name)
self.assertEqual(instance.type_, instance_alt.type_)
clusters, failed_locations = instance_alt.list_clusters()
self.assertEqual(failed_locations, [])
clusters.sort(key=lambda x: x.name)
alt_cluster_1, alt_cluster_2 = clusters
self.assertEqual(cluster_1.location_id, alt_cluster_1.location_id)
self.assertEqual(alt_cluster_1.state, enums.Cluster.State.READY)
self.assertEqual(cluster_1.serve_nodes, alt_cluster_1.serve_nodes)
self.assertEqual(
cluster_1.default_storage_type, alt_cluster_1.default_storage_type
)
self.assertEqual(cluster_2.location_id, alt_cluster_2.location_id)
self.assertEqual(alt_cluster_2.state, enums.Cluster.State.READY)
self.assertEqual(cluster_2.serve_nodes, alt_cluster_2.serve_nodes)
self.assertEqual(
cluster_2.default_storage_type, alt_cluster_2.default_storage_type
)
# Test list clusters in project via 'client.list_clusters'
clusters, failed_locations = Config.CLIENT.list_clusters()
self.assertFalse(failed_locations)
found = set([cluster.name for cluster in clusters])
self.assertTrue(
{alt_cluster_1.name, alt_cluster_2.name, Config.CLUSTER.name}.issubset(
found
)
)
temp_table_id = "test-get-cluster-states"
temp_table = instance.table(temp_table_id)
temp_table.create()
encryption_info = temp_table.get_encryption_info()
self.assertEqual(
encryption_info[ALT_CLUSTER_ID_1][0].encryption_type,
enums.EncryptionInfo.EncryptionType.GOOGLE_DEFAULT_ENCRYPTION,
)
self.assertEqual(
encryption_info[ALT_CLUSTER_ID_2][0].encryption_type,
enums.EncryptionInfo.EncryptionType.GOOGLE_DEFAULT_ENCRYPTION,
)
result = temp_table.get_cluster_states()
ReplicationState = enums.Table.ReplicationState
expected_results = [
ClusterState(ReplicationState.STATE_NOT_KNOWN),
ClusterState(ReplicationState.INITIALIZING),
ClusterState(ReplicationState.PLANNED_MAINTENANCE),
ClusterState(ReplicationState.UNPLANNED_MAINTENANCE),
ClusterState(ReplicationState.READY),
]
cluster_id_list = result.keys()
self.assertEqual(len(cluster_id_list), 2)
self.assertIn(ALT_CLUSTER_ID_1, cluster_id_list)
self.assertIn(ALT_CLUSTER_ID_2, cluster_id_list)
for clusterstate in result.values():
self.assertIn(clusterstate, expected_results)
# Test create app profile with multi_cluster_routing policy
app_profiles_to_delete = []
description = "routing policy-multy"
app_profile_id_1 = "app_profile_id_1"
routing = enums.RoutingPolicyType.ANY
self._test_create_app_profile_helper(
app_profile_id_1,
instance,
routing_policy_type=routing,
description=description,
ignore_warnings=True,
)
app_profiles_to_delete.append(app_profile_id_1)
# Test list app profiles
self._test_list_app_profiles_helper(instance, [app_profile_id_1])
# Test modify app profile app_profile_id_1
# routing policy to single cluster policy,
# cluster -> ALT_CLUSTER_ID_1,
# allow_transactional_writes -> disallowed
# modify description
description = "to routing policy-single"
routing = enums.RoutingPolicyType.SINGLE
self._test_modify_app_profile_helper(
app_profile_id_1,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_1,
allow_transactional_writes=False,
)
# Test modify app profile app_profile_id_1
# cluster -> ALT_CLUSTER_ID_2,
# allow_transactional_writes -> allowed
self._test_modify_app_profile_helper(
app_profile_id_1,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_2,
allow_transactional_writes=True,
ignore_warnings=True,
)
# Test create app profile with single cluster routing policy
description = "routing policy-single"
app_profile_id_2 = "app_profile_id_2"
routing = enums.RoutingPolicyType.SINGLE
self._test_create_app_profile_helper(
app_profile_id_2,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_2,
allow_transactional_writes=False,
)
app_profiles_to_delete.append(app_profile_id_2)
# Test list app profiles
self._test_list_app_profiles_helper(
instance, [app_profile_id_1, app_profile_id_2]
)
# Test modify app profile app_profile_id_2 to
# allow transactional writes
# Note: no need to set ``ignore_warnings`` to True
# since we are not restrictings anything with this modification.
self._test_modify_app_profile_helper(
app_profile_id_2,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_2,
allow_transactional_writes=True,
)
# Test modify app profile app_profile_id_2 routing policy
# to multi_cluster_routing policy
# modify description
description = "to routing policy-multy"
routing = enums.RoutingPolicyType.ANY
self._test_modify_app_profile_helper(
app_profile_id_2,
instance,
routing_policy_type=routing,
description=description,
allow_transactional_writes=False,
ignore_warnings=True,
)
# Test delete app profiles
for app_profile_id in app_profiles_to_delete:
self._test_delete_app_profile_helper(app_profile_id, instance)
@pytest.mark.skipif(
not KMS_KEY_NAME, reason="requires KMS_KEY_NAME environment variable"
)
def test_create_instance_w_two_clusters_cmek(self):
from google.cloud.bigtable import enums
from google.cloud.bigtable.table import ClusterState
_PRODUCTION = enums.Instance.Type.PRODUCTION
ALT_INSTANCE_ID = "dif-cmek" + UNIQUE_SUFFIX
instance = Config.CLIENT.instance(
ALT_INSTANCE_ID, instance_type=_PRODUCTION, labels=LABELS
)
ALT_CLUSTER_ID_1 = ALT_INSTANCE_ID + "-c1"
ALT_CLUSTER_ID_2 = ALT_INSTANCE_ID + "-c2"
LOCATION_ID_2 = "us-central1-f"
STORAGE_TYPE = enums.StorageType.HDD
serve_nodes = 1
cluster_1 = instance.cluster(
ALT_CLUSTER_ID_1,
location_id=LOCATION_ID,
serve_nodes=serve_nodes,
default_storage_type=STORAGE_TYPE,
kms_key_name=KMS_KEY_NAME,
)
cluster_2 = instance.cluster(
ALT_CLUSTER_ID_2,
location_id=LOCATION_ID_2,
serve_nodes=serve_nodes,
default_storage_type=STORAGE_TYPE,
kms_key_name=KMS_KEY_NAME,
)
operation = instance.create(clusters=[cluster_1, cluster_2])
# Make sure this instance gets deleted after the test case.
self.instances_to_delete.append(instance)
# We want to make sure the operation completes.
operation.result(timeout=120)
# Create a new instance instance and make sure it is the same.
instance_alt = Config.CLIENT.instance(ALT_INSTANCE_ID)
instance_alt.reload()
self.assertEqual(instance, instance_alt)
self.assertEqual(instance.display_name, instance_alt.display_name)
self.assertEqual(instance.type_, instance_alt.type_)
clusters, failed_locations = instance_alt.list_clusters()
self.assertEqual(failed_locations, [])
clusters.sort(key=lambda x: x.name)
alt_cluster_1, alt_cluster_2 = clusters
self.assertEqual(cluster_1.location_id, alt_cluster_1.location_id)
self.assertEqual(alt_cluster_1.state, enums.Cluster.State.READY)
self.assertEqual(cluster_1.serve_nodes, alt_cluster_1.serve_nodes)
self.assertEqual(
cluster_1.default_storage_type, alt_cluster_1.default_storage_type
)
self.assertEqual(cluster_2.location_id, alt_cluster_2.location_id)
self.assertEqual(alt_cluster_2.state, enums.Cluster.State.READY)
self.assertEqual(cluster_2.serve_nodes, alt_cluster_2.serve_nodes)
self.assertEqual(
cluster_2.default_storage_type, alt_cluster_2.default_storage_type
)
# Test list clusters in project via 'client.list_clusters'
clusters, failed_locations = Config.CLIENT.list_clusters()
self.assertFalse(failed_locations)
found = set([cluster.name for cluster in clusters])
self.assertTrue(
{alt_cluster_1.name, alt_cluster_2.name, Config.CLUSTER.name}.issubset(
found
)
)
temp_table_id = "test-get-cluster-states"
temp_table = instance.table(temp_table_id)
temp_table.create()
encryption_info = temp_table.get_encryption_info()
self.assertEqual(
encryption_info[ALT_CLUSTER_ID_1][0].encryption_type,
enums.EncryptionInfo.EncryptionType.CUSTOMER_MANAGED_ENCRYPTION,
)
self.assertEqual(
encryption_info[ALT_CLUSTER_ID_2][0].encryption_type,
enums.EncryptionInfo.EncryptionType.CUSTOMER_MANAGED_ENCRYPTION,
)
result = temp_table.get_cluster_states()
ReplicationState = enums.Table.ReplicationState
expected_results = [
ClusterState(ReplicationState.STATE_NOT_KNOWN),
ClusterState(ReplicationState.INITIALIZING),
ClusterState(ReplicationState.PLANNED_MAINTENANCE),
ClusterState(ReplicationState.UNPLANNED_MAINTENANCE),
ClusterState(ReplicationState.READY),
]
cluster_id_list = result.keys()
self.assertEqual(len(cluster_id_list), 2)
self.assertIn(ALT_CLUSTER_ID_1, cluster_id_list)
self.assertIn(ALT_CLUSTER_ID_2, cluster_id_list)
for clusterstate in result.values():
self.assertIn(clusterstate, expected_results)
# Test create app profile with multi_cluster_routing policy
app_profiles_to_delete = []
description = "routing policy-multy"
app_profile_id_1 = "app_profile_id_1"
routing = enums.RoutingPolicyType.ANY
self._test_create_app_profile_helper(
app_profile_id_1,
instance,
routing_policy_type=routing,
description=description,
ignore_warnings=True,
)
app_profiles_to_delete.append(app_profile_id_1)
# Test list app profiles
self._test_list_app_profiles_helper(instance, [app_profile_id_1])
# Test modify app profile app_profile_id_1
# routing policy to single cluster policy,
# cluster -> ALT_CLUSTER_ID_1,
# allow_transactional_writes -> disallowed
# modify description
description = "to routing policy-single"
routing = enums.RoutingPolicyType.SINGLE
self._test_modify_app_profile_helper(
app_profile_id_1,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_1,
allow_transactional_writes=False,
)
# Test modify app profile app_profile_id_1
# cluster -> ALT_CLUSTER_ID_2,
# allow_transactional_writes -> allowed
self._test_modify_app_profile_helper(
app_profile_id_1,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_2,
allow_transactional_writes=True,
ignore_warnings=True,
)
# Test create app profile with single cluster routing policy
description = "routing policy-single"
app_profile_id_2 = "app_profile_id_2"
routing = enums.RoutingPolicyType.SINGLE
self._test_create_app_profile_helper(
app_profile_id_2,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_2,
allow_transactional_writes=False,
)
app_profiles_to_delete.append(app_profile_id_2)
# Test list app profiles
self._test_list_app_profiles_helper(
instance, [app_profile_id_1, app_profile_id_2]
)
# Test modify app profile app_profile_id_2 to
# allow transactional writes
# Note: no need to set ``ignore_warnings`` to True
# since we are not restrictings anything with this modification.
self._test_modify_app_profile_helper(
app_profile_id_2,
instance,
routing_policy_type=routing,
description=description,
cluster_id=ALT_CLUSTER_ID_2,
allow_transactional_writes=True,
)
# Test modify app profile app_profile_id_2 routing policy
# to multi_cluster_routing policy
# modify description
description = "to routing policy-multy"
routing = enums.RoutingPolicyType.ANY
self._test_modify_app_profile_helper(
app_profile_id_2,
instance,
routing_policy_type=routing,
description=description,
allow_transactional_writes=False,
ignore_warnings=True,
)
# Test delete app profiles
for app_profile_id in app_profiles_to_delete:
self._test_delete_app_profile_helper(app_profile_id, instance)
def test_update_display_name_and_labels(self):
OLD_DISPLAY_NAME = Config.INSTANCE.display_name
NEW_DISPLAY_NAME = "Foo Bar Baz"
n_label_stamp = (
datetime.datetime.utcnow()
.replace(microsecond=0, tzinfo=UTC)
.strftime("%Y-%m-%dt%H-%M-%S")
)
NEW_LABELS = {LABEL_KEY: str(n_label_stamp)}
Config.INSTANCE.display_name = NEW_DISPLAY_NAME
Config.INSTANCE.labels = NEW_LABELS
operation = Config.INSTANCE.update()
# We want to make sure the operation completes.
operation.result(timeout=10)
# Create a new instance instance and reload it.
instance_alt = Config.CLIENT.instance(INSTANCE_ID, labels=LABELS)
self.assertEqual(instance_alt.display_name, OLD_DISPLAY_NAME)
self.assertEqual(instance_alt.labels, LABELS)
instance_alt.reload()
self.assertEqual(instance_alt.display_name, NEW_DISPLAY_NAME)
self.assertEqual(instance_alt.labels, NEW_LABELS)
# Make sure to put the instance back the way it was for the
# other test cases.
Config.INSTANCE.display_name = OLD_DISPLAY_NAME
Config.INSTANCE.labels = LABELS
operation = Config.INSTANCE.update()
# We want to make sure the operation completes.
operation.result(timeout=10)
def test_update_type(self):
from google.cloud.bigtable.enums import Instance
_DEVELOPMENT = Instance.Type.DEVELOPMENT
_PRODUCTION = Instance.Type.PRODUCTION
ALT_INSTANCE_ID = "ndif" + UNIQUE_SUFFIX
instance = Config.CLIENT.instance(
ALT_INSTANCE_ID, instance_type=_DEVELOPMENT, labels=LABELS
)
operation = instance.create(location_id=LOCATION_ID)
# Make sure this instance gets deleted after the test case.
self.instances_to_delete.append(instance)
# We want to make sure the operation completes.
operation.result(timeout=10)
# Unset the display_name
instance.display_name = None
instance.type_ = _PRODUCTION
operation = instance.update()
# We want to make sure the operation completes.
operation.result(timeout=10)
# Create a new instance instance and reload it.
instance_alt = Config.CLIENT.instance(ALT_INSTANCE_ID)
self.assertIsNone(instance_alt.type_)
instance_alt.reload()
self.assertEqual(instance_alt.type_, _PRODUCTION)
def test_update_cluster(self):
NEW_SERVE_NODES = 4
Config.CLUSTER.serve_nodes = NEW_SERVE_NODES
operation = Config.CLUSTER.update()
# We want to make sure the operation completes.
operation.result(timeout=10)
# Create a new cluster instance and reload it.
alt_cluster = Config.INSTANCE.cluster(CLUSTER_ID)
alt_cluster.reload()
self.assertEqual(alt_cluster.serve_nodes, NEW_SERVE_NODES)
# Make sure to put the cluster back the way it was for the
# other test cases.
Config.CLUSTER.serve_nodes = SERVE_NODES
operation = Config.CLUSTER.update()
operation.result(timeout=20)
def test_create_cluster(self):
from google.cloud.bigtable.enums import StorageType
from google.cloud.bigtable.enums import Cluster
ALT_CLUSTER_ID = INSTANCE_ID + "-c2"
ALT_LOCATION_ID = "us-central1-f"
ALT_SERVE_NODES = 2
cluster_2 = Config.INSTANCE.cluster(
ALT_CLUSTER_ID,
location_id=ALT_LOCATION_ID,
serve_nodes=ALT_SERVE_NODES,
default_storage_type=(StorageType.SSD),
)
operation = cluster_2.create()
# We want to make sure the operation completes.
operation.result(timeout=30)
# Create a new object instance, reload and make sure it is the same.
alt_cluster = Config.INSTANCE.cluster(ALT_CLUSTER_ID)
alt_cluster.reload()
self.assertEqual(cluster_2, alt_cluster)
self.assertEqual(cluster_2.location_id, alt_cluster.location_id)
self.assertEqual(alt_cluster.state, Cluster.State.READY)
self.assertEqual(cluster_2.serve_nodes, alt_cluster.serve_nodes)
self.assertEqual(
cluster_2.default_storage_type, alt_cluster.default_storage_type
)
# Delete the newly created cluster and confirm
self.assertTrue(cluster_2.exists())
cluster_2.delete()
self.assertFalse(cluster_2.exists())
def _test_create_app_profile_helper(
self,
app_profile_id,
instance,
routing_policy_type,
description=None,
cluster_id=None,
allow_transactional_writes=None,
ignore_warnings=None,
):
app_profile = instance.app_profile(
app_profile_id=app_profile_id,
routing_policy_type=routing_policy_type,
description=description,
cluster_id=cluster_id,
allow_transactional_writes=allow_transactional_writes,
)
self.assertEqual(
app_profile.allow_transactional_writes, allow_transactional_writes
)
app_profile = app_profile.create(ignore_warnings=ignore_warnings)
# Load a different app_profile objec form the server and
# verrify that it is the same
alt_app_profile = instance.app_profile(app_profile_id)
alt_app_profile.reload()
self.assertEqual(app_profile.app_profile_id, alt_app_profile.app_profile_id)
self.assertEqual(app_profile.routing_policy_type, routing_policy_type)
self.assertEqual(alt_app_profile.routing_policy_type, routing_policy_type)
self.assertEqual(app_profile.description, alt_app_profile.description)
self.assertFalse(app_profile.allow_transactional_writes)
self.assertFalse(alt_app_profile.allow_transactional_writes)
def _test_list_app_profiles_helper(self, instance, app_profile_ids):
app_profiles = instance.list_app_profiles()
found = [app_prof.app_profile_id for app_prof in app_profiles]
for app_profile_id in app_profile_ids:
self.assertTrue(app_profile_id in found)
def _test_modify_app_profile_helper(
self,
app_profile_id,
instance,
routing_policy_type,
description=None,
cluster_id=None,
allow_transactional_writes=None,
ignore_warnings=None,
):
app_profile = instance.app_profile(
app_profile_id=app_profile_id,
routing_policy_type=routing_policy_type,
description=description,
cluster_id=cluster_id,
allow_transactional_writes=allow_transactional_writes,
)
operation = app_profile.update(ignore_warnings)
operation.result(timeout=30)
alt_app_profile = instance.app_profile(app_profile_id)
alt_app_profile.reload()
self.assertEqual(alt_app_profile.description, description)
self.assertEqual(alt_app_profile.routing_policy_type, routing_policy_type)
self.assertEqual(alt_app_profile.cluster_id, cluster_id)
self.assertEqual(
alt_app_profile.allow_transactional_writes, allow_transactional_writes
)
def _test_delete_app_profile_helper(self, app_profile_id, instance):
app_profile = instance.app_profile(app_profile_id)
self.assertTrue(app_profile.exists())
app_profile.delete(ignore_warnings=True)
self.assertFalse(app_profile.exists())
class TestTableAdminAPI(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._table = Config.INSTANCE_DATA.table(TABLE_ID)
cls._table.create()
@classmethod
def tearDownClass(cls):
cls._table.delete()
def setUp(self):
self.tables_to_delete = []
self.backups_to_delete = []
def tearDown(self):
for table in self.tables_to_delete:
table.delete()
for backup in self.backups_to_delete:
backup.delete()
def _skip_if_emulated(self, message):
# NOTE: This method is necessary because ``Config.IN_EMULATOR``
# is set at runtime rather than import time, which means we
# can't use the @unittest.skipIf decorator.
if Config.IN_EMULATOR:
self.skipTest(message)
def test_list_tables(self):
# Since `Config.INSTANCE_DATA` is newly created in `setUpModule`, the
# table created in `setUpClass` here will be the only one.
tables = Config.INSTANCE_DATA.list_tables()
self.assertEqual(tables, [self._table])
def test_exists(self):
retry_until_true = RetryResult(lambda result: result)
retry_until_false = RetryResult(lambda result: not result)
temp_table_id = "test-table_existence"
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
self.assertFalse(temp_table.exists())
temp_table.create()
self.assertTrue(retry_until_true(temp_table.exists)())
temp_table.delete()
self.assertFalse(retry_until_false(temp_table.exists)())
def test_create_table(self):
temp_table_id = "test-create-table"
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
temp_table.create()
self.tables_to_delete.append(temp_table)
# First, create a sorted version of our expected result.
name_attr = operator.attrgetter("name")
expected_tables = sorted([temp_table, self._table], key=name_attr)
# Then query for the tables in the instance and sort them by
# name as well.
tables = Config.INSTANCE_DATA.list_tables()
sorted_tables = sorted(tables, key=name_attr)
self.assertEqual(sorted_tables, expected_tables)
def test_test_iam_permissions(self):
self._skip_if_emulated("Method not implemented in bigtable emulator")
temp_table_id = "test-test-iam-policy-table"
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
temp_table.create()
self.tables_to_delete.append(temp_table)
permissions = ["bigtable.tables.mutateRows", "bigtable.tables.readRows"]
permissions_allowed = temp_table.test_iam_permissions(permissions)
self.assertEqual(permissions, permissions_allowed)
def test_get_iam_policy(self):
self._skip_if_emulated("Method not implemented in bigtable emulator")
temp_table_id = "test-get-iam-policy-table"
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
temp_table.create()
self.tables_to_delete.append(temp_table)
policy = temp_table.get_iam_policy().to_api_repr()
self.assertEqual(policy["etag"], "ACAB")
self.assertEqual(policy["version"], 0)
def test_set_iam_policy(self):
self._skip_if_emulated("Method not implemented in bigtable emulator")
temp_table_id = "test-set-iam-policy-table"
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
temp_table.create()
self.tables_to_delete.append(temp_table)
new_policy = Policy()
service_account_email = Config.CLIENT._credentials.service_account_email
new_policy[BIGTABLE_ADMIN_ROLE] = [
Policy.service_account(service_account_email)
]
policy_latest = temp_table.set_iam_policy(new_policy).to_api_repr()
self.assertEqual(policy_latest["bindings"][0]["role"], "roles/bigtable.admin")
self.assertIn(service_account_email, policy_latest["bindings"][0]["members"][0])
def test_create_table_with_families(self):
temp_table_id = "test-create-table-with-failies"
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
gc_rule = MaxVersionsGCRule(1)
temp_table.create(column_families={COLUMN_FAMILY_ID1: gc_rule})
self.tables_to_delete.append(temp_table)
col_fams = temp_table.list_column_families()
self.assertEqual(len(col_fams), 1)
retrieved_col_fam = col_fams[COLUMN_FAMILY_ID1]
self.assertIs(retrieved_col_fam._table, temp_table)
self.assertEqual(retrieved_col_fam.column_family_id, COLUMN_FAMILY_ID1)
self.assertEqual(retrieved_col_fam.gc_rule, gc_rule)
def test_create_table_with_split_keys(self):
self._skip_if_emulated("Split keys are not supported by Bigtable emulator")
temp_table_id = "foo-bar-baz-split-table"
initial_split_keys = [b"split_key_1", b"split_key_10", b"split_key_20"]
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
temp_table.create(initial_split_keys=initial_split_keys)
self.tables_to_delete.append(temp_table)
# Read Sample Row Keys for created splits
sample_row_keys = temp_table.sample_row_keys()
actual_keys = [srk.row_key for srk in sample_row_keys]
expected_keys = initial_split_keys
expected_keys.append(b"")
self.assertEqual(actual_keys, expected_keys)
def test_create_column_family(self):
temp_table_id = "test-create-column-family"
temp_table = Config.INSTANCE_DATA.table(temp_table_id)
temp_table.create()
self.tables_to_delete.append(temp_table)