forked from Azure/azure-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom.py
More file actions
6861 lines (5561 loc) · 222 KB
/
custom.py
File metadata and controls
6861 lines (5561 loc) · 222 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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=C0302
from enum import Enum
import calendar
from datetime import datetime
from dateutil.parser import parse
from azure.cli.core.util import (
CLIError,
sdk_no_wait,
)
from azure.mgmt.sql.models import (
AdministratorName,
AdministratorType,
AdvancedThreatProtectionName,
AdvancedThreatProtectionState,
AuthenticationName,
BlobAuditingPolicyState,
CapabilityGroup,
CapabilityStatus,
ConnectionPolicyName,
CreateMode,
EncryptionProtector,
EncryptionProtectorName,
FailoverGroup,
FailoverGroupReadOnlyEndpoint,
FailoverGroupReadWriteEndpoint,
FailoverGroupReplicationRole,
FirewallRule,
InstanceFailoverGroup,
InstanceFailoverGroupReadOnlyEndpoint,
InstanceFailoverGroupReadWriteEndpoint,
IPv6FirewallRule,
LedgerDigestUploadsName,
LongTermRetentionPolicyName,
ManagedDatabaseCreateMode,
ManagedInstanceAzureADOnlyAuthentication,
ManagedInstanceEncryptionProtector,
ManagedInstanceExternalAdministrator,
ManagedInstanceKey,
ManagedInstanceLongTermRetentionPolicyName,
ManagedInstancePairInfo,
ManagedShortTermRetentionPolicyName,
OutboundFirewallRule,
PartnerInfo,
PartnerRegionInfo,
PerformanceLevelUnit,
ResourceIdentity,
RestoreDetailsName,
SecurityAlertPolicyName,
SecurityAlertPolicyState,
SensitivityLabel,
SensitivityLabelSource,
ServerAzureADOnlyAuthentication,
ServerConnectionPolicy,
ServerExternalAdministrator,
ServerInfo,
ServerKey,
ServerKeyType,
ServerNetworkAccessFlag,
ServerTrustGroup,
ServicePrincipal,
ShortTermRetentionPolicyName,
Sku,
StorageKeyType,
TransparentDataEncryptionName,
UserIdentity,
VirtualNetworkRule,
DatabaseUserIdentity,
DatabaseKey
)
from azure.cli.core.profiles import ResourceType
from azure.cli.core.commands.client_factory import get_mgmt_service_client
from azure.cli.command_modules.monitor._client_factory import cf_monitor
from azure.cli.command_modules.monitor.operations.diagnostics_settings import create_diagnostics_settings
from knack.log import get_logger
from knack.prompting import prompt_y_n
from ._util import (
get_sql_capabilities_operations,
get_sql_servers_operations,
get_sql_managed_instances_operations,
get_sql_restorable_dropped_database_managed_backup_short_term_retention_policies_operations,
get_sql_managed_database_restore_details_operations,
get_sql_replication_links_operations,
get_sql_elastic_pools_operations,
)
logger = get_logger(__name__)
###############################################
# Common funcs #
###############################################
def _get_server_location(cli_ctx, server_name, resource_group_name):
'''
Returns the location (i.e. Azure region) that the specified server is in.
'''
server_client = get_sql_servers_operations(cli_ctx, None)
# pylint: disable=no-member
return server_client.get(
server_name=server_name,
resource_group_name=resource_group_name).location
def _get_managed_restorable_dropped_database_backup_short_term_retention_client(cli_ctx):
'''
Returns client for managed restorable dropped databases.
'''
server_client = \
get_sql_restorable_dropped_database_managed_backup_short_term_retention_policies_operations(cli_ctx, None)
# pylint: disable=no-member
return server_client
def _get_managed_instance_location(cli_ctx, managed_instance_name, resource_group_name):
'''
Returns the location (i.e. Azure region) that the specified managed instance is in.
'''
managed_instance_client = get_sql_managed_instances_operations(cli_ctx, None)
# pylint: disable=no-member
return managed_instance_client.get(
managed_instance_name=managed_instance_name,
resource_group_name=resource_group_name).location
def _get_location_capability(cli_ctx, location, group):
'''
Gets the location capability for a location and verifies that it is available.
'''
capabilities_client = get_sql_capabilities_operations(cli_ctx, None)
location_capability = capabilities_client.list_by_location(location, group)
_assert_capability_available(location_capability)
return location_capability
def _any_sku_values_specified(sku):
'''
Returns True if the sku object has any properties that are specified
(i.e. not None).
'''
return any(val for key, val in sku.__dict__.items())
def _compute_model_matches(sku_name, compute_model):
'''
Returns True if sku name matches the compute model.
Please update is function if compute_model has more than 2 enums.
'''
if (_is_serverless_slo(sku_name) and compute_model == ComputeModelType.serverless):
return True
if (not _is_serverless_slo(sku_name) and compute_model != ComputeModelType.serverless):
return True
return False
def _is_serverless_slo(sku_name):
'''
Returns True if the sku name is a serverless sku.
'''
return "_S_" in sku_name
def _get_default_server_version(location_capabilities):
'''
Gets the default server version capability from the full location
capabilities response.
If none have 'default' status, gets the first capability that has
'available' status.
If there is no default or available server version, falls back to
server version 12.0 in order to maintain compatibility with older
Azure CLI releases (2.0.25 and earlier).
'''
server_versions = location_capabilities.supported_server_versions
def is_v12(capability):
return capability.name == "12.0"
return _get_default_capability(server_versions, fallback_predicate=is_v12)
def _get_default_capability(capabilities, fallback_predicate=None):
'''
Gets the first capability in the collection that has 'default' status.
If none have 'default' status, gets the first capability that has 'available' status.
'''
logger.debug('_get_default_capability: %s', capabilities)
# Get default capability
r = next((c for c in capabilities if c.status == CapabilityStatus.DEFAULT), None)
if r:
logger.debug('_get_default_capability found default: %s', r)
return r
# No default capability, so fallback to first available capability
r = next((c for c in capabilities if c.status == CapabilityStatus.AVAILABLE), None)
if r:
logger.debug('_get_default_capability found available: %s', r)
return r
# No available capability, so use custom fallback
if fallback_predicate:
logger.debug('_get_default_capability using fallback')
r = next((c for c in capabilities if fallback_predicate(c)), None)
if r:
logger.debug('_get_default_capability found fallback: %s', r)
return r
# No custom fallback, so we have to throw an error.
logger.debug('_get_default_capability failed')
raise CLIError('Provisioning is restricted in this region. Please choose a different region.')
def _assert_capability_available(capability):
'''
Asserts that the capability is available (or default). Throws CLIError if the
capability is unavailable.
'''
logger.debug('_assert_capability_available: %s', capability)
if not is_available(capability.status):
raise CLIError(capability.reason)
def is_available(status):
'''
Returns True if the capability status is available (including default).
There are three capability statuses:
VISIBLE: customer can see the slo but cannot use it
AVAILABLE: customer can see the slo and can use it
DEFAULT: customer can see the slo and can use it
Thus, only check whether status is not VISIBLE would return the correct value.
'''
return status not in CapabilityStatus.VISIBLE
def _filter_available(capabilities):
'''
Filters out the capabilities by removing values that are not available.
'''
return [c for c in capabilities if is_available(c.status)]
def _find_edition_capability(sku, supported_editions):
'''
Finds the DB edition capability in the collection of supported editions
that matches the requested sku.
If the sku has no edition specified, returns the default edition.
(Note: tier and edition mean the same thing.)
'''
logger.debug('_find_edition_capability: %s; %s', sku, supported_editions)
if sku.tier:
# Find requested edition capability
try:
return next(e for e in supported_editions if e.name == sku.tier)
except StopIteration:
candidate_editions = [e.name for e in supported_editions]
raise CLIError('Could not find tier {}. Supported tiers are: {}'.format(
sku.tier, candidate_editions
))
else:
# Find default edition capability
return _get_default_capability(supported_editions)
def _find_family_capability(sku, supported_families):
'''
Finds the family capability in the collection of supported families
that matches the requested sku.
If the edition has no family specified, returns the default family.
'''
logger.debug('_find_family_capability: %s; %s', sku, supported_families)
if sku.family:
# Find requested family capability
try:
return next(f for f in supported_families if f.name == sku.family)
except StopIteration:
candidate_families = [e.name for e in supported_families]
raise CLIError('Could not find family {}. Supported families are: {}'.format(
sku.family, candidate_families
))
else:
# Find default family capability
return _get_default_capability(supported_families)
def _find_performance_level_capability(sku, supported_service_level_objectives, allow_reset_family, compute_model=None):
'''
Finds the DB or elastic pool performance level (i.e. service objective) in the
collection of supported service objectives that matches the requested sku's
family and capacity.
If the sku has no capacity or family specified, returns the default service
objective.
'''
logger.debug('_find_performance_level_capability: %s, %s, allow_reset_family: %s, compute_model: %s',
sku, supported_service_level_objectives, allow_reset_family, compute_model)
if sku.capacity:
try:
# Find requested service objective based on capacity & family.
# Note that for non-vcore editions, family is None.
return next(slo for slo in supported_service_level_objectives
if ((slo.sku.family == sku.family) or
(slo.sku.family is None and allow_reset_family)) and
int(slo.sku.capacity) == int(sku.capacity) and
_compute_model_matches(slo.sku.name, compute_model))
except StopIteration:
if allow_reset_family:
raise CLIError(
"Could not find sku in tier '{tier}' with capacity {capacity}."
" Supported capacities for '{tier}' are: {capacities}."
" Please specify one of these supported values for capacity.".format(
tier=sku.tier,
capacity=sku.capacity,
capacities=[slo.sku.capacity for slo in supported_service_level_objectives]
))
raise CLIError(
"Could not find sku in tier '{tier}' with family '{family}', capacity {capacity}."
" Supported families & capacities for '{tier}' are: {skus}. Please specify one of these"
" supported combinations of family and capacity."
" And ensure that the sku supports '{compute_model}' compute model.".format(
tier=sku.tier,
family=sku.family,
capacity=sku.capacity,
skus=[(slo.sku.family, slo.sku.capacity)
for slo in supported_service_level_objectives],
compute_model=compute_model
))
elif sku.family:
# Error - cannot find based on family alone.
raise CLIError('If --family is specified, --capacity must also be specified.')
else:
# Find default service objective
return _get_default_capability(supported_service_level_objectives)
def _db_elastic_pool_update_sku(
cmd,
instance,
service_objective,
tier,
family,
capacity,
find_sku_from_capabilities_func,
compute_model=None):
'''
Updates the sku of a DB or elastic pool.
'''
# Set sku name
if service_objective:
instance.sku = Sku(name=service_objective)
# Set tier
allow_reset_family = False
if tier:
if not service_objective:
# Wipe out old sku name so that it does not conflict with new tier
instance.sku.name = None
instance.sku.tier = tier
if instance.sku.family and not family:
# If we are changing tier and old sku has family but
# new family is unspecified, allow sku search to wipe out family.
#
# This is needed so that tier can be successfully changed from
# a tier that has family (e.g. GeneralPurpose) to a tier that has
# no family (e.g. Standard).
allow_reset_family = True
# Set family
if family:
if not service_objective:
# Wipe out old sku name so that it does not conflict with new family
instance.sku.name = None
instance.sku.family = family
# Set capacity
if capacity:
instance.sku.capacity = capacity
# Wipe out sku name if serverless vs provisioned db offerings changed,
# only if sku name has not be wiped by earlier logic, and new compute model has been requested.
if instance.sku.name and compute_model:
if not _compute_model_matches(instance.sku.name, compute_model):
instance.sku.name = None
# If sku name was wiped out by any of the above, resolve the requested sku name
# using capabilities.
if not instance.sku.name:
instance.sku = find_sku_from_capabilities_func(
cmd.cli_ctx, instance.location, instance.sku,
allow_reset_family=allow_reset_family, compute_model=compute_model)
def _get_tenant_id():
'''
Gets tenantId from current subscription.
'''
from azure.cli.core._profile import Profile
profile = Profile()
sub = profile.get_subscription()
return sub['tenantId']
def _get_service_principal_object_from_type(servicePrincipalType):
'''
Gets the service principal object from type.
'''
servicePrincipalResult = None
if (servicePrincipalType is not None and
(servicePrincipalType == ServicePrincipalType.system_assigned.value or
servicePrincipalType == ServicePrincipalType.none.value)):
servicePrincipalResult = ServicePrincipal(type=servicePrincipalType)
return servicePrincipalResult
def _get_identity_object_from_type(
assignIdentityIsPresent,
resourceIdentityType,
userAssignedIdentities,
existingResourceIdentity):
'''
Gets the resource identity type.
'''
identityResult = None
if resourceIdentityType is not None and resourceIdentityType == ResourceIdType.none.value:
identityResult = ResourceIdentity(type=ResourceIdType.none.value)
return identityResult
if assignIdentityIsPresent and resourceIdentityType is not None:
# When UMI is of type SystemAssigned,UserAssigned
if resourceIdentityType == ResourceIdType.system_assigned_user_assigned.value:
umiDict = None
if userAssignedIdentities is None:
raise CLIError('"The list of user assigned identity ids needs to be passed if the'
'IdentityType is UserAssigned or SystemAssignedUserAssigned.')
if existingResourceIdentity is not None and existingResourceIdentity.user_assigned_identities is not None:
identityResult = _get_sys_assigned_user_assigned_identity(userAssignedIdentities,
existingResourceIdentity)
# Create scenarios
else:
for identity in userAssignedIdentities:
if umiDict is None:
umiDict = {identity: UserIdentity()}
else:
umiDict[identity] = UserIdentity() # pylint: disable=unsupported-assignment-operation
identityResult = ResourceIdentity(type=ResourceIdType.system_assigned_user_assigned.value,
user_assigned_identities=umiDict)
# When UMI is of type UserAssigned
if resourceIdentityType == ResourceIdType.user_assigned.value:
umiDict = None
if userAssignedIdentities is None:
raise CLIError('"The list of user assigned identity ids needs to be passed if the '
'IdentityType is UserAssigned or SystemAssignedUserAssigned.')
if existingResourceIdentity is not None and existingResourceIdentity.user_assigned_identities is not None:
identityResult = _get__user_assigned_identity(userAssignedIdentities, existingResourceIdentity)
else:
for identity in userAssignedIdentities:
if umiDict is None:
umiDict = {identity: UserIdentity()}
else:
umiDict[identity] = UserIdentity() # pylint: disable=unsupported-assignment-operation
identityResult = ResourceIdentity(type=ResourceIdType.user_assigned.value,
user_assigned_identities=umiDict)
if resourceIdentityType == ResourceIdType.system_assigned.value:
identityResult = ResourceIdentity(type=ResourceIdType.system_assigned.value)
elif assignIdentityIsPresent:
identityResult = ResourceIdentity(type=ResourceIdType.system_assigned.value)
if assignIdentityIsPresent is False and existingResourceIdentity is not None:
identityResult = existingResourceIdentity
return identityResult
def _get_sys_assigned_user_assigned_identity(
userAssignedIdentities,
existingResourceIdentity):
for identity in userAssignedIdentities:
existingResourceIdentity.user_assigned_identities.update({identity: UserIdentity()})
identityResult = ResourceIdentity(type=ResourceIdType.system_assigned_user_assigned.value)
return identityResult
def _get__user_assigned_identity(
userAssignedIdentities,
existingResourceIdentity):
for identity in userAssignedIdentities:
existingResourceIdentity.user_assigned_identities.update({identity: UserIdentity()})
identityResult = ResourceIdentity(type=ResourceIdType.user_assigned.value)
return identityResult
def _get_database_identity(
userAssignedIdentities):
'''
Gets the resource identity type for the database.
'''
databaseIdentity = None
if userAssignedIdentities is None:
raise CLIError('The list of user assigned identity ids needs to be passed for database CMK')
umiDict = None
for umi in userAssignedIdentities:
if umiDict is None:
umiDict = {umi: DatabaseUserIdentity()}
else:
umiDict[umi] = DatabaseUserIdentity() # pylint: disable=unsupported-assignment-operation
from azure.mgmt.sql.models import DatabaseIdentity # pylint: disable=redefined-outer-name
databaseIdentity = DatabaseIdentity(type=ResourceIdType.user_assigned.value, user_assigned_identities=umiDict)
return databaseIdentity
_DEFAULT_SERVER_VERSION = "12.0"
def _failover_group_update_common(
instance,
failover_policy=None,
grace_period=None,):
'''
Updates the failover group grace period and failover policy. Common logic for both Sterling and Managed Instance
'''
if failover_policy is not None:
instance.read_write_endpoint.failover_policy = failover_policy
if instance.read_write_endpoint.failover_policy == FailoverPolicyType.manual.value:
grace_period = None
instance.read_write_endpoint.failover_with_data_loss_grace_period_minutes = grace_period
if grace_period is not None:
grace_period = int(grace_period) * 60
instance.read_write_endpoint.failover_with_data_loss_grace_period_minutes = grace_period
def _complete_maintenance_configuration_id(cli_ctx, argument_value=None):
'''
Completes maintenance configuration id from short to full type if needed
'''
from azure.mgmt.core.tools import resource_id, is_valid_resource_id
from azure.cli.core.commands.client_factory import get_subscription_id
if argument_value and not is_valid_resource_id(argument_value):
return resource_id(
subscription=get_subscription_id(cli_ctx),
namespace='Microsoft.Maintenance',
type='publicMaintenanceConfigurations',
name=argument_value)
return argument_value
###############################################
# sql db #
###############################################
# pylint: disable=too-few-public-methods
class ClientType(Enum):
'''
Types of SQL clients whose connection strings we can generate.
'''
ado_net = 'ado.net'
sqlcmd = 'sqlcmd'
jdbc = 'jdbc'
php_pdo = 'php_pdo'
php = 'php'
odbc = 'odbc'
class ClientAuthenticationType(Enum):
'''
Types of SQL client authentication mechanisms for connection strings
that we can generate.
'''
sql_password = 'SqlPassword'
active_directory_password = 'ADPassword'
active_directory_integrated = 'ADIntegrated'
class FailoverPolicyType(Enum):
automatic = 'Automatic'
manual = 'Manual'
class FailoverGroupDatabasesSecondaryType(Enum):
geo = 'Geo'
standby = 'Standby'
class SqlServerMinimalTlsVersionType(Enum):
tls_1_0 = "1.0"
tls_1_1 = "1.1"
tls_1_2 = "1.2"
tls_1_3 = "1.3"
class ResourceIdType(Enum):
'''
Gets the type of resource identity.
'''
system_assigned = 'SystemAssigned'
user_assigned = 'UserAssigned'
system_assigned_user_assigned = 'SystemAssigned,UserAssigned'
none = 'None'
class ServicePrincipalType(Enum):
'''
Types of service principal.
'''
system_assigned = 'SystemAssigned'
none = 'None'
class SqlManagedInstanceMinimalTlsVersionType(Enum):
no_tls = "None"
tls_1_0 = "1.0"
tls_1_1 = "1.1"
tls_1_2 = "1.2"
class ComputeModelType(str, Enum):
provisioned = "Provisioned"
serverless = "Serverless"
class FreeLimitExhaustionBehavior(str, Enum):
auto_pause = "AutoPause"
bill_over_usage = "BillOverUsage"
class AlwaysEncryptedEnclaveType(str, Enum):
default = "Default"
vbs = "VBS"
class DatabaseEdition(str, Enum):
web = "Web"
business = "Business"
basic = "Basic"
standard = "Standard"
premium = "Premium"
premium_rs = "PremiumRS"
free = "Free"
stretch = "Stretch"
data_warehouse = "DataWarehouse"
system = "System"
system2 = "System2"
general_purpose = "GeneralPurpose"
business_critical = "BusinessCritical"
hyperscale = "Hyperscale"
class AuthenticationType(str, Enum):
sql = "SQL"
ad_password = "ADPassword"
managed_identity = "ManagedIdentity"
class FreemiumType(str, Enum):
Regular = "Regular"
Freemium = "Freemium"
def _get_server_dns_suffx(cli_ctx):
'''
Gets the DNS suffix for servers in this Azure environment.
'''
# Allow dns suffix to be overridden by environment variable for testing purposes
from os import getenv
return getenv('_AZURE_CLI_SQL_DNS_SUFFIX', default=cli_ctx.cloud.suffixes.sql_server_hostname)
def _get_managed_db_resource_id(
cli_ctx,
resource_group_name,
managed_instance_name,
database_name,
subscription_id=None):
'''
Gets the Managed db resource id in this Azure environment.
'''
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.mgmt.core.tools import resource_id
return resource_id(
subscription=subscription_id if subscription_id else get_subscription_id(cli_ctx),
resource_group=resource_group_name,
namespace='Microsoft.Sql', type='managedInstances',
name=managed_instance_name,
child_type_1='databases',
child_name_1=database_name)
def _to_filetimeutc(dateTime):
'''
Changes given datetime to filetimeutc string
'''
NET_epoch = datetime(1601, 1, 1)
UNIX_epoch = datetime(1970, 1, 1)
epoch_delta = UNIX_epoch - NET_epoch
log_time = parse(dateTime)
net_ts = calendar.timegm((log_time + epoch_delta).timetuple())
# units of seconds since NET epoch
filetime_utc_ts = net_ts * (10**7) + log_time.microsecond * 10
return filetime_utc_ts
def _get_managed_dropped_db_resource_id(
cli_ctx,
resource_group_name,
managed_instance_name,
database_name,
deleted_time,
subscription_id=None):
'''
Gets the Managed db resource id in this Azure environment.
'''
from urllib.parse import quote
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.mgmt.core.tools import resource_id
return (resource_id(
subscription=subscription_id if subscription_id else get_subscription_id(cli_ctx),
resource_group=resource_group_name,
namespace='Microsoft.Sql', type='managedInstances',
name=managed_instance_name,
child_type_1='restorableDroppedDatabases',
child_name_1='{},{}'.format(
quote(database_name),
_to_filetimeutc(deleted_time))))
def _get_managed_instance_resource_id(
cli_ctx,
resource_group_name,
managed_instance_name,
subscription_id=None):
'''
Gets managed instance resource id in this Azure environment.
'''
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.mgmt.core.tools import resource_id
return (resource_id(
subscription=subscription_id if subscription_id else get_subscription_id(cli_ctx),
resource_group=resource_group_name,
namespace='Microsoft.Sql', type='managedInstances',
name=managed_instance_name))
def _get_managed_instance_pool_resource_id(
cli_ctx,
resource_group_name,
instance_pool_name,
subscription_id=None):
'''
Gets instance pool resource id in this Azure environment.
'''
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.mgmt.core.tools import resource_id
if instance_pool_name:
return (resource_id(
subscription=subscription_id if subscription_id else get_subscription_id(cli_ctx),
resource_group=resource_group_name,
namespace='Microsoft.Sql', type='instancePools',
name=instance_pool_name))
return instance_pool_name
def db_show_conn_str(
cmd,
client_provider,
database_name='<databasename>',
server_name='<servername>',
auth_type=ClientAuthenticationType.sql_password.value):
'''
Builds a SQL connection string for a specified client provider.
'''
server_suffix = _get_server_dns_suffx(cmd.cli_ctx)
conn_str_props = {
'server': server_name,
'server_fqdn': '{}{}'.format(server_name, server_suffix),
'server_suffix': server_suffix,
'db': database_name
}
formats = {
ClientType.ado_net.value: {
ClientAuthenticationType.sql_password.value:
'Server=tcp:{server_fqdn},1433;Initial Catalog={db};Persist Security Info=False;'
'User ID=<username>;Password=<password>;MultipleActiveResultSets=False;Encrypt=true;'
'TrustServerCertificate=False;Connection Timeout=30;',
ClientAuthenticationType.active_directory_password.value:
'Server=tcp:{server_fqdn},1433;Initial Catalog={db};Persist Security Info=False;'
'User ID=<username>;Password=<password>;MultipleActiveResultSets=False;Encrypt=true;'
'TrustServerCertificate=False;Authentication="Active Directory Password"',
ClientAuthenticationType.active_directory_integrated.value:
'Server=tcp:{server_fqdn},1433;Initial Catalog={db};Persist Security Info=False;'
'User ID=<username>;MultipleActiveResultSets=False;Encrypt=true;'
'TrustServerCertificate=False;Authentication="Active Directory Integrated"'
},
ClientType.sqlcmd.value: {
ClientAuthenticationType.sql_password.value:
'sqlcmd -S tcp:{server_fqdn},1433 -d {db} -U <username> -P <password> -N -l 30',
ClientAuthenticationType.active_directory_password.value:
'sqlcmd -S tcp:{server_fqdn},1433 -d {db} -U <username> -P <password> -G -N -l 30',
ClientAuthenticationType.active_directory_integrated.value:
'sqlcmd -S tcp:{server_fqdn},1433 -d {db} -G -N -l 30',
},
ClientType.jdbc.value: {
ClientAuthenticationType.sql_password.value:
'jdbc:sqlserver://{server_fqdn}:1433;database={db};user=<username>@{server};'
'password=<password>;encrypt=true;trustServerCertificate=false;'
'hostNameInCertificate=*{server_suffix};loginTimeout=30',
ClientAuthenticationType.active_directory_password.value:
'jdbc:sqlserver://{server_fqdn}:1433;database={db};user=<username>;'
'password=<password>;encrypt=true;trustServerCertificate=false;'
'hostNameInCertificate=*{server_suffix};loginTimeout=30;'
'authentication=ActiveDirectoryPassword',
ClientAuthenticationType.active_directory_integrated.value:
'jdbc:sqlserver://{server_fqdn}:1433;database={db};'
'encrypt=true;trustServerCertificate=false;'
'hostNameInCertificate=*{server_suffix};loginTimeout=30;'
'authentication=ActiveDirectoryIntegrated',
},
ClientType.php_pdo.value: {
# pylint: disable=line-too-long
ClientAuthenticationType.sql_password.value:
'$conn = new PDO("sqlsrv:server = tcp:{server_fqdn},1433; Database = {db}; LoginTimeout = 30; Encrypt = 1; TrustServerCertificate = 0;", "<username>", "<password>");',
ClientAuthenticationType.active_directory_password.value:
CLIError('PHP Data Object (PDO) driver only supports SQL Password authentication.'),
ClientAuthenticationType.active_directory_integrated.value:
CLIError('PHP Data Object (PDO) driver only supports SQL Password authentication.'),
},
ClientType.php.value: {
# pylint: disable=line-too-long
ClientAuthenticationType.sql_password.value:
'$connectionOptions = array("UID"=>"<username>@{server}", "PWD"=>"<password>", "Database"=>{db}, "LoginTimeout" => 30, "Encrypt" => 1, "TrustServerCertificate" => 0); $serverName = "tcp:{server_fqdn},1433"; $conn = sqlsrv_connect($serverName, $connectionOptions);',
ClientAuthenticationType.active_directory_password.value:
CLIError('PHP sqlsrv driver only supports SQL Password authentication.'),
ClientAuthenticationType.active_directory_integrated.value:
CLIError('PHP sqlsrv driver only supports SQL Password authentication.'),
},
ClientType.odbc.value: {
ClientAuthenticationType.sql_password.value:
'Driver={{ODBC Driver 13 for SQL Server}};Server=tcp:{server_fqdn},1433;'
'Database={db};Uid=<username>@{server};Pwd=<password>;Encrypt=yes;'
'TrustServerCertificate=no;',
ClientAuthenticationType.active_directory_password.value:
'Driver={{ODBC Driver 13 for SQL Server}};Server=tcp:{server_fqdn},1433;'
'Database={db};Uid=<username>@{server};Pwd=<password>;Encrypt=yes;'
'TrustServerCertificate=no;Authentication=ActiveDirectoryPassword',
ClientAuthenticationType.active_directory_integrated.value:
'Driver={{ODBC Driver 13 for SQL Server}};Server=tcp:{server_fqdn},1433;'
'Database={db};Encrypt=yes;TrustServerCertificate=no;'
'Authentication=ActiveDirectoryIntegrated',
}
}
f = formats[client_provider][auth_type]
if isinstance(f, Exception):
# Error
raise f
# Success
return f.format(**conn_str_props)
class DatabaseIdentity: # pylint: disable=too-few-public-methods
'''
Helper class to bundle up database identity properties and generate
database resource id.
'''
def __init__(self, cli_ctx, database_name, server_name, resource_group_name):
self.database_name = database_name
self.server_name = server_name
self.resource_group_name = resource_group_name
self.cli_ctx = cli_ctx
def id(self):
from urllib.parse import quote
from azure.cli.core.commands.client_factory import get_subscription_id
return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Sql/servers/{}/databases/{}'.format(
quote(get_subscription_id(self.cli_ctx)),
quote(self.resource_group_name),
quote(self.server_name),
quote(self.database_name))
def _find_db_sku_from_capabilities(cli_ctx, location, sku, allow_reset_family=False, compute_model=None):
'''
Given a requested sku which may have some properties filled in
(e.g. tier and capacity), finds the canonical matching sku
from the given location's capabilities.
'''
logger.debug('_find_db_sku_from_capabilities input: %s', sku)
if sku.name:
# User specified sku.name, so nothing else needs to be resolved.
logger.debug('_find_db_sku_from_capabilities return sku as is')
return sku
if not _any_sku_values_specified(sku):
# User did not request any properties of sku, so just wipe it out.
# Server side will pick a default.
logger.debug('_find_db_sku_from_capabilities return None')
return None
# Some properties of sku are specified, but not name. Use the requested properties
# to find a matching capability and copy the sku from there.
# Get location capability
loc_capability = _get_location_capability(cli_ctx, location, CapabilityGroup.SUPPORTED_EDITIONS)
# Get default server version capability
server_version_capability = _get_default_server_version(loc_capability)