sql_cmd 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (56) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +201 -0
  3. data/lib/optional_dependencies.rb +30 -0
  4. data/lib/sql_cmd/agent.rb +32 -0
  5. data/lib/sql_cmd/always_on.rb +267 -0
  6. data/lib/sql_cmd/azure.rb +80 -0
  7. data/lib/sql_cmd/backups.rb +276 -0
  8. data/lib/sql_cmd/config.rb +62 -0
  9. data/lib/sql_cmd/database.rb +618 -0
  10. data/lib/sql_cmd/format.rb +124 -0
  11. data/lib/sql_cmd/query.rb +350 -0
  12. data/lib/sql_cmd/security.rb +21 -0
  13. data/lib/sql_cmd/sql_helper.ps1 +89 -0
  14. data/lib/sql_cmd.rb +44 -0
  15. data/sql_scripts/Agent/CreateSQLJob.sql +81 -0
  16. data/sql_scripts/Agent/JobLastRunInfo.sql +70 -0
  17. data/sql_scripts/Agent/JobRunStatus.sql +21 -0
  18. data/sql_scripts/Agent/SQLAgentStatus.sql +8 -0
  19. data/sql_scripts/AlwaysOn/AddDatabaseToAvailabilityGroupOnSecondary.sql +72 -0
  20. data/sql_scripts/AlwaysOn/AddDatabaseToPrimaryAvailabilityGroup.sql +16 -0
  21. data/sql_scripts/AlwaysOn/AutomaticSeedingProgress.sql +34 -0
  22. data/sql_scripts/AlwaysOn/ConfigurePrimaryForAutomaticSeeding.sql +2 -0
  23. data/sql_scripts/AlwaysOn/ConfigurePrimaryForManualSeeding.sql +2 -0
  24. data/sql_scripts/AlwaysOn/ConfigureSecondaryForAutomaticSeeding.sql +1 -0
  25. data/sql_scripts/AlwaysOn/DropSecondary.sql +58 -0
  26. data/sql_scripts/AlwaysOn/RemoveDatabaseFromGroup.sql +2 -0
  27. data/sql_scripts/AlwaysOn/SynchronizationState.sql +14 -0
  28. data/sql_scripts/Database/BackupDatabase.sql +95 -0
  29. data/sql_scripts/Database/CompressAllTables.sql +100 -0
  30. data/sql_scripts/Database/CreateLogin.sql +16 -0
  31. data/sql_scripts/Database/DropDatabase.sql +51 -0
  32. data/sql_scripts/Database/GetBackupFiles.sql +31 -0
  33. data/sql_scripts/Database/GetBackupHeaders.sql +94 -0
  34. data/sql_scripts/Database/GetFileInfoFromBackup.sql +9 -0
  35. data/sql_scripts/Database/RestoreDatabase.sql +185 -0
  36. data/sql_scripts/Database/SetFullRecovery.sql +19 -0
  37. data/sql_scripts/Database/SetSQLCompatibility.sql +33 -0
  38. data/sql_scripts/Security/AssignDatabaseRoles.sql +44 -0
  39. data/sql_scripts/Security/CreateOrUpdateCredential.sql +11 -0
  40. data/sql_scripts/Security/CreateSqlLogin.sql +20 -0
  41. data/sql_scripts/Security/ExportDatabasePermissions.sql +757 -0
  42. data/sql_scripts/Security/GenerateCreateLoginsScript.sql +144 -0
  43. data/sql_scripts/Security/GenerateValidateLoginsScript.sql +83 -0
  44. data/sql_scripts/Security/GetUserSID.sql +3 -0
  45. data/sql_scripts/Security/UpdateSqlPassword.sql +24 -0
  46. data/sql_scripts/Security/ValidateDatabaseRoles.sql +12 -0
  47. data/sql_scripts/Status/ANSINullsOffTableCount.sql +13 -0
  48. data/sql_scripts/Status/ANSINullsOffTables.sql +9 -0
  49. data/sql_scripts/Status/BackupProgress.sql +17 -0
  50. data/sql_scripts/Status/DatabaseInfo.sql +199 -0
  51. data/sql_scripts/Status/DatabaseSize.sql +26 -0
  52. data/sql_scripts/Status/DiskSpace.sql +14 -0
  53. data/sql_scripts/Status/RestoreProgress.sql +17 -0
  54. data/sql_scripts/Status/SQLSettings.sql +182 -0
  55. data/sql_scripts/Status/UncompressedTableCount.sql +27 -0
  56. metadata +224 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 266298d96407b2fb372453d3989ef5fb21047f1a364c857c3c559e1826257d5a
4
+ data.tar.gz: b3053a685e3e0202e1b68bddb20cec62bce549f6d7a8f7164ead4709f355dd9a
5
+ SHA512:
6
+ metadata.gz: 99aab9a7af85a77a7da945aaff55823364b497ef4d91d2551994362d87120c379784b8ff753d4339ac44ca91d14ba1c02f17f07942c03646f956c5c9da609190
7
+ data.tar.gz: 5c6b0287eb928e2356e99b329eee771f5add55af0b13d0ec29e131fee1ab1590c7c726dcfd280d25b96e753b5febc8626841c844e4ae1f122468b8270d19e923
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,30 @@
1
+ module OptionalDepedencies
2
+ module_function
3
+
4
+ def load_azure_blob_storage_dependencies
5
+ azure_blob_storage_dependencies = {
6
+ # 'faraday-excon' => '1.1.0',
7
+ # 'faraday-net_http' => '1.0.1',
8
+ # 'faraday-net_http_persistent' => '1.1.0',
9
+ # 'ruby2_keywords' => '0.0.4',
10
+ # 'faraday' => '1.4.1',
11
+ # 'faraday_middleware' => '1.0.0',
12
+ # 'connection_pool' => '2.2.5'
13
+ # 'net-http-persistent' => '4.0.1',
14
+ # 'racc' => '1.5.2',
15
+ # 'nokogiri' => '1.11.4',
16
+ 'azure/storage/common' => '2.0.2',
17
+ 'azure/storage/blob' => '2.0.1',
18
+ }
19
+ load_gem_list(azure_blob_storage_dependencies)
20
+ end
21
+
22
+ def load_gem_list(gem_list)
23
+ gem_list.each do |current_gem, constraint|
24
+ gem current_gem.tr('/', '-'), constraint
25
+ require current_gem
26
+ end
27
+ rescue Gem::LoadError => e
28
+ raise Gem::LoadError, "You are using functionality requiring the optional gem dependency '#{e.name}', but the gem is not loaded, or is not using a version matching '#{e.requirement}'."
29
+ end
30
+ end
@@ -0,0 +1,32 @@
1
+ module SqlCmd
2
+ module Agent
3
+ module Job
4
+ module_function
5
+
6
+ def exists?(connection_string, job_name)
7
+ status(connection_string, job_name)['LastRunStatus'] != 'NoJob'
8
+ end
9
+
10
+ def running?(connection_string, job_name)
11
+ !run_status(connection_string, job_name).empty?
12
+ end
13
+
14
+ def status(connection_string, job_name)
15
+ raise 'Failed to get job status! The connection_string argument must be specified.' if connection_string.nil? || connection_string.empty?
16
+ raise 'Failed to get job status! The job_name argument must be specified.' if job_name.nil? || job_name.empty?
17
+ return { 'LastRunStatus' => 'Running' } if running?(connection_string, job_name)
18
+ sql_script = ::File.read("#{SqlCmd.sql_script_dir}/Agent/JobLastRunInfo.sql")
19
+ server_connection_string = SqlCmd.remove_connection_string_part(connection_string, :database)
20
+ SqlCmd.execute_query(server_connection_string, sql_script, return_type: :first_row, values: { 'jobname' => job_name }, readonly: true, retries: 3) || { 'LastRunStatus' => 'NoJob' }
21
+ end
22
+
23
+ def run_status(connection_string, job_name)
24
+ raise 'Failed to get job status! The connection_string argument must be specified.' if connection_string.nil? || connection_string.empty?
25
+ raise 'Failed to get job status! The job_name argument must be specified.' if job_name.nil? || job_name.empty?
26
+ sql_script = ::File.read("#{SqlCmd.sql_script_dir}/Agent/JobRunStatus.sql")
27
+ server_connection_string = SqlCmd.remove_connection_string_part(connection_string, :database)
28
+ SqlCmd.execute_query(server_connection_string, sql_script, return_type: :first_row, values: { 'jobname' => job_name }, readonly: true, retries: 3) || {}
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,267 @@
1
+ module SqlCmd
2
+ module AlwaysOn
3
+ module_function
4
+
5
+ # Optionally provide your own lambda for creating a full non-copyonly backup using the full_backup_method parameter
6
+ # Seeding modes: AUTOMATIC (No backup/restore needed to synchronize), MANUAL (traditional backup and restore process)
7
+ # async option is only observed when using automatic seeding
8
+ def add_to_availability_group(connection_string, database_name, options = {}, seeding_mode: nil, full_backup_method: nil, async: false, idempotent: false, start_time: Time.now)
9
+ EasyIO.logger.header 'AlwaysOn Availability'
10
+ start_time = SqlCmd.unify_start_time(start_time)
11
+ EasyIO.logger.info "Checking if server [#{SqlCmd.connection_string_part(connection_string, :server)}] is configured for AlwaysOn High Availability..."
12
+ server_info = SqlCmd.get_sql_server_settings(connection_string)
13
+ if server_info['AvailabilityGroup'].nil? || server_info['SecondaryReplica'].nil?
14
+ EasyIO.logger.info "Server [#{SqlCmd.connection_string_part(connection_string, :server)}] not configured for AlwaysOn High Availability..."
15
+ return
16
+ end
17
+
18
+ seeding_mode ||= server_info['SeedingMode'] || 'MANUAL'
19
+ database_info = SqlCmd::Database.info(connection_string, database_name)
20
+ primary_connection_string = SqlCmd.replace_connection_string_part(connection_string, :database, 'master')
21
+ replica_connection_string = server_info['secondary_replica_connection_string']
22
+ replica_database_info = SqlCmd::Database.info(replica_connection_string, database_name)
23
+ validate_logins_script = SqlCmd.validate_logins_script(connection_string, database_name)
24
+ logins_migrated = SqlCmd.execute_query(replica_connection_string, validate_logins_script, retries: 3)
25
+ unless database_info['AvailabilityGroup'].nil? || replica_database_info['AvailabilityGroup'].nil? || !logins_migrated
26
+ EasyIO.logger.info 'Database already configured for AlwaysOn and synchronized. Skipping...'
27
+ return
28
+ end
29
+
30
+ EasyIO.logger.info "Preparing to add [#{database_name}] to AlwaysOn availability group..."
31
+ always_on_backup_time = EasyTime.yyyymmdd_hhmmss(start_time)
32
+
33
+ full_recovery_script = ::File.read("#{SqlCmd.sql_script_dir}/Database/SetFullRecovery.sql")
34
+
35
+ values = {
36
+ 'databasename' => database_name,
37
+ 'datetime' => always_on_backup_time,
38
+ 'availabilitygroupname' => server_info['AvailabilityGroup'],
39
+ 'secondaryreplica' => server_info['SecondaryReplica'],
40
+ 'primarysqlserver' => server_info['ServerName'],
41
+ 'seedingmode' => seeding_mode.upcase,
42
+ 'backupdir' => SqlCmd.config['sql_cmd']['backups']['always_on_backup_temp_dir'],
43
+ }.merge(options)
44
+
45
+ raise "Could not determine secondary replica for #{server_info['ServerName']}" if server_info['SecondaryReplica'].nil?
46
+
47
+ if database_info['AvailabilityGroup'].nil? || replica_database_info['AvailabilityGroup'].nil?
48
+ EasyIO.logger.header 'AlwaysOn Full Backup'
49
+ EasyIO.logger.info "Ensuring database [#{database_name}] is set to full recovery..."
50
+ recovery_model_updated = SqlCmd.execute_query(connection_string, full_recovery_script, values: values, return_type: :scalar, retries: 3)
51
+ force_backup = recovery_model_updated || !idempotent
52
+ SqlCmd::Database.ensure_full_backup_has_occurred(connection_string, database_name, force_backup: force_backup, database_info: database_info, full_backup_method: full_backup_method)
53
+ if seeding_mode.upcase == 'AUTOMATIC'
54
+ add_to_availability_group_automatically(primary_connection_string, replica_connection_string, database_name, server_info, values: values, async: async)
55
+ else
56
+ add_database_to_replica_using_backups(primary_connection_string, replica_connection_string, server_info, database_info, replica_database_info, values: values, idempotent: idempotent)
57
+ end
58
+ else
59
+ EasyIO.logger.info 'Database already in AlwaysOn Availability group.'
60
+ end
61
+
62
+ EasyIO.logger.header 'AlwaysOn Permissions Migration to Replica'
63
+ EasyIO.logger.debug 'Migrating logins to replica...'
64
+ import_script_filename = SqlCmd.export_logins(start_time, primary_connection_string, database_name)
65
+ EasyIO.logger.info "Importing logins on [#{SqlCmd.connection_string_part(replica_connection_string, :server)}]..."
66
+ SqlCmd.execute_script_file(replica_connection_string, import_script_filename)
67
+ EasyIO.logger.debug 'Running database_status script...'
68
+ database_info = SqlCmd::Database.info(connection_string, database_name)
69
+ replica_database_info = SqlCmd::Database.info(replica_connection_string, database_name)
70
+ raise 'Failed to add database to AlwaysOn Availability Group' if database_info['AvailabilityGroup'].nil? || replica_database_info['AvailabilityGroup'].nil?
71
+ EasyIO.logger.info "AlwaysOn availability for [#{database_name}] is configured and active..."
72
+ end
73
+
74
+ # TODO: idempotent log backups and restores are not stable and need improvement. Use 'idempotent: false' for now
75
+ def add_database_to_replica_using_backups(primary_connection_string, replica_connection_string, server_info, database_info, replica_database_info, values: {}, idempotent: false)
76
+ database_name = database_info['DatabaseName']
77
+ configure_primary_for_manual_seeding_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/ConfigurePrimaryForManualSeeding.sql")
78
+ add_to_primary_availability_group_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/AddDatabaseToPrimaryAvailabilityGroup.sql")
79
+ add_to_availability_group_on_secondary_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/AddDatabaseToAvailabilityGroupOnSecondary.sql")
80
+ backup_url = SqlCmd.config['sql_cmd']['always_on_backup_url']
81
+
82
+ SqlCmd.execute_query(primary_connection_string, configure_primary_for_manual_seeding_script, values: values, retries: 3) if ::Gem::Version.new(server_info['SQLVersion']) >= ::Gem::Version.new('13.0')
83
+
84
+ EasyIO.logger.info "Adding [#{database_name}] to availability group..."
85
+ SqlCmd.execute_query(primary_connection_string, add_to_primary_availability_group_script, values: values, retries: 3)
86
+
87
+ # Backup database on primary replica
88
+ EasyIO.logger.header 'AlwaysOn CopyOnly Full Backup'
89
+ copy_only_full_backup_exists = ::File.exist?("#{values['backupdir']}\\#{database_name}.bak")
90
+ copy_only_backup_start_time = Time.now
91
+ if copy_only_full_backup_exists && idempotent
92
+ copy_only_full_backup_header = SqlCmd.get_sql_backup_headers(primary_connection_string, ["#{values['backupdir']}\\#{database_name}.bak"], values).first
93
+ copy_only_backup_current = !SqlCmd.gap_in_log_backups?(server_info, copy_only_full_backup_header, replica_database_info['LastRestoreLSN'], values['backupdir'], database_name, values)
94
+ copy_only_backup_current &&= (database_info['LastRestoreDate'] || Time.at(0)) < copy_only_full_backup_header['BackupFinishDate'] # Make sure the database hasn't been restored again since the last backup
95
+ EasyIO.logger.debug "LSN of CopyOnly backup: #{copy_only_full_backup_header['DatabaseBackupLSN']}"
96
+ EasyIO.logger.debug "Last restore LSN: #{replica_database_info['LastRestoreLSN']}"
97
+ EasyIO.logger.debug "Copy only backup current?: #{copy_only_backup_current}"
98
+ end
99
+
100
+ if copy_only_full_backup_exists && copy_only_backup_current && idempotent
101
+ EasyIO.logger.info 'CopyOnly Database backup current. Skipping CopyOnly backup...'
102
+ else
103
+ EasyIO.logger.info 'Backing up database on primary server (CopyOnly)...'
104
+ always_on_backup_options = { 'formatbackup' => true, 'init' => true, 'rewind' => true, 'nounload' => true, 'compressbackup' => true, 'splitfiles' => false }
105
+ SqlCmd::Database.backup(copy_only_backup_start_time, primary_connection_string, database_name, backup_folder: values['backupdir'], backup_url: backup_url, backup_basename: database_name, options: always_on_backup_options)
106
+ end
107
+
108
+ # Restore database to secondary replica if it was restored before the copy only backup was created or if it doesn't exist
109
+ EasyIO.logger.header 'AlwaysOn Restore of CopyOnly Backup to Replica'
110
+ if !idempotent || !copy_only_full_backup_exists || !copy_only_backup_current || copy_only_full_backup_header.nil? || replica_database_info['LastRestoreDate'].nil? ||
111
+ replica_database_info['LastRestoreDate'] < database_info['LastCopyOnlyFullBackupDate'] || replica_database_info['LastRestoreLSN'] < database_info['LastCopyOnlyLSN']
112
+ EasyIO.logger.info 'Restoring database to secondary replica...'
113
+ restore_options = { 'recovery' => false, 'unload' => false, 'secondaryreplica' => true, 'datafilelogicalname' => '', 'logfilelogicalname' => '' }
114
+ SqlCmd::Database.restore(copy_only_backup_start_time, replica_connection_string, database_name, backup_folder: values['backupdir'], backup_url: backup_url, backup_basename: database_name, options: restore_options)
115
+ else
116
+ EasyIO.logger.info 'Restore of CopyOnly database backup current. Skipping restore of CopyOnly database backup...'
117
+ end
118
+
119
+ sleep(15) # Give time for database to be in correct state
120
+ # Backup log on primary replica
121
+ EasyIO.logger.header 'AlwaysOn Log Backup'
122
+ log_only_backup_start_time = Time.now
123
+ log_only_options = { 'logonly' => true, 'skip' => false, 'rewind' => true, 'compressbackup' => true, 'splitfiles' => false }
124
+ EasyIO.logger.info 'Backing up log file on primary replica...'
125
+ SqlCmd::Database.backup(log_only_backup_start_time, primary_connection_string, database_name, backup_folder: values['backupdir'], backup_url: backup_url, backup_basename: database_name, options: log_only_options)
126
+
127
+ # Restore log on secondary replica
128
+ EasyIO.logger.header 'AlwaysOn Log Restore to Replica'
129
+ restore_options = { 'recovery' => false, 'unload' => false, 'logonly' => true, 'secondaryreplica' => true }
130
+ SqlCmd::Database.restore(log_only_backup_start_time, replica_connection_string, database_name, backup_folder: values['backupdir'], backup_url: backup_url, backup_basename: database_name, options: restore_options)
131
+
132
+ # Add to availability group on secondary replica
133
+ EasyIO.logger.header 'AlwaysOn Database Sync'
134
+ EasyIO.logger.info 'Waiting for communication and adding to availability group on secondary replica...'
135
+ SqlCmd.execute_query(replica_connection_string, add_to_availability_group_on_secondary_script, values: values, retries: 3)
136
+ raise 'Replica does not appear to be in the correct state!' if SqlCmd::Database.info(replica_connection_string, database_name)['AvailabilityGroup'].nil?
137
+ EasyIO.logger.info "[#{database_name}] added to AlwaysOn availability group successfully..."
138
+ end
139
+
140
+ def add_to_availability_group_automatically(primary_connection_string, replica_connection_string, database_name, server_info, values: {}, async: false)
141
+ EasyIO.logger.header 'AlwaysOn Automatic Seeding'
142
+ configure_primary_for_automatic_seeding_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/ConfigurePrimaryForAutomaticSeeding.sql")
143
+ add_to_primary_availability_group_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/AddDatabaseToPrimaryAvailabilityGroup.sql")
144
+ configure_secondary_for_automatic_seeding_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/ConfigureSecondaryForAutomaticSeeding.sql")
145
+
146
+ SqlCmd.execute_query(primary_connection_string, configure_primary_for_automatic_seeding_script, values: values, retries: 3)
147
+ EasyIO.logger.info "Adding [#{database_name}] to availability group..."
148
+ SqlCmd.execute_query(primary_connection_string, add_to_primary_availability_group_script, values: values, retries: 3)
149
+ SqlCmd.execute_query(replica_connection_string, configure_secondary_for_automatic_seeding_script, values: values, retries: 3)
150
+
151
+ if async
152
+ EasyIO.logger.info "#{database_name} added to availability group #{server_info['AvailabilityGroup']}. AlwaysOn will continue synchronizing in the background."
153
+ return
154
+ end
155
+
156
+ monitor_automatic_seeding(primary_connection_string, database_name)
157
+ raise 'Failed to add to AlwaysOn availability group!' unless database_synchronized?(primary_connection_string, database_name, replica_connection_string: replica_connection_string)
158
+ EasyIO.logger.info "[#{database_name}] added to AlwaysOn availability group successfully..."
159
+ end
160
+
161
+ def monitor_automatic_seeding(connection_string, database_name, retries: 3, retry_delay: 15)
162
+ EasyIO.logger.header 'Monitoring AlwaysOn Seeding'
163
+ progress_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/AutomaticSeedingProgress.sql")
164
+ values = { 'databasename' => database_name }
165
+
166
+ seeding_status = SqlCmd.execute_query(connection_string, progress_script, values: values, return_type: :first_row, retries: 3)
167
+ if seeding_status['current_state'] == 'COMPLETED'
168
+ EasyIO.logger.info 'AlwaysOn seeding complete.'
169
+ return
170
+ end
171
+
172
+ start_time = Time.now
173
+ seeding_start_timeout = 300 # Allow 5 minutes to start the seeding process before failing
174
+ timeout = 86400 # 24 hours
175
+ progress_interval = 4 # seconds
176
+ begin
177
+ while Time.now < start_time + timeout
178
+ seeding_status = SqlCmd.execute_query(connection_string, progress_script, values: values, return_type: :first_row, retries: 3)
179
+
180
+ if seeding_status['current_state'] == 'COMPLETED'
181
+ EasyIO.logger.info 'AlwaysOn seeding complete.'
182
+ return
183
+ end
184
+
185
+ if seeding_status['transferred_size_percent_complete'].nil? || seeding_status['current_state'] == 'FAILED'
186
+ unless Time.now > start_time + seeding_start_timeout
187
+ EasyIO.logger.info 'Waiting for automatic synchronization process...'
188
+ sleep(progress_interval)
189
+ next
190
+ end
191
+ raise "Failed to seed #{database_name} automatically! Check the synchronization status." if seeding_status.empty?
192
+ failure_message = "Failed to seed #{database_name} automatically in availability group [#{seeding_status['ag_name']}]! Check the synchronization status on #{seeding_status['replica_server_name']}.\n"
193
+ failure_message += seeding_status['failure_state_desc'] unless seeding_status['failure_state_desc'].nil?
194
+ raise failure_message
195
+ end
196
+
197
+ percent_complete = seeding_status['transferred_size_percent_complete']
198
+ percent_complete = 0.1 if percent_complete == 0 # Avoid divide by zero
199
+ elapsed_min = (Time.now - start_time) / 60
200
+ eta_min = (elapsed_min / (percent_complete / 100.0)) - elapsed_min
201
+ eta_time = Time.now + (eta_min * 60).round
202
+ EasyIO.logger.info "Percent complete: #{percent_complete.round(1)} / Elapsed min: #{elapsed_min.round(2)} / Min remaining: #{eta_min.round(2)} / ETA: #{eta_time}"
203
+ sleep(progress_interval)
204
+ end
205
+ rescue
206
+ raise if (retries -= 1) < 0
207
+ EasyIO.logger.warn "Failure monitoring AlwaysOn seeding. Retrying in #{retry_delay} seconds..."
208
+ sleep(retry_delay)
209
+ retry
210
+ end
211
+ raise "Automatic seeding timed out after #{timeout / 60 / 60} hours!" # only gets here if status never reached 'COMPLETED'
212
+ end
213
+
214
+ def database_synchronized?(primary_connection_string, database_name, replica_connection_string: nil)
215
+ database_info = SqlCmd::Database.info(primary_connection_string, database_name)
216
+ # TODO: check if AlwaysOn is even enabled on this server
217
+ if replica_connection_string.nil? || replica_connection_string.empty?
218
+ server_info = SqlCmd.get_sql_server_settings(primary_connection_string)
219
+ replica_connection_string = server_info['secondary_replica_connection_string']
220
+ end
221
+ replica_database_info = replica_connection_string.nil? ? {} : SqlCmd::Database.info(replica_connection_string, database_name)
222
+ !database_info['AvailabilityGroup'].nil? && !replica_database_info['AvailabilityGroup'].nil?
223
+ end
224
+
225
+ def remove_from_availability_group(connection_string, database_name)
226
+ EasyIO.logger.header 'AlwaysOn Availability Removal'
227
+ EasyIO.logger.info "Checking if server [#{SqlCmd.connection_string_part(connection_string, :server)}] is configured for AlwaysOn High Availability..."
228
+ server_info = SqlCmd.get_sql_server_settings(connection_string)
229
+ if server_info['AvailabilityGroup'].nil? || server_info['SecondaryReplica'].nil?
230
+ EasyIO.logger.info "Server [#{SqlCmd.connection_string_part(connection_string, :server)}] not configured for AlwaysOn High Availability..."
231
+ return
232
+ end
233
+
234
+ primary_connection_string = SqlCmd.replace_connection_string_part(server_info['direct_connection_string'], :database, 'master')
235
+ replica_connection_string = server_info['secondary_replica_connection_string']
236
+ primary_server_name = SqlCmd.connection_string_part(primary_connection_string, :server)
237
+ database_info = SqlCmd::Database.info(primary_connection_string, database_name)
238
+ replica_database_info = SqlCmd::Database.info(replica_connection_string, database_name)
239
+
240
+ if database_info['DatabaseNotFound']
241
+ EasyIO.logger.info "Skipping removal from availability group: database [#{database_name}] does not exist on [#{primary_server_name}]..."
242
+ return
243
+ end
244
+ if database_info['AvailabilityGroup'].nil? && replica_database_info['DatabaseNotFound']
245
+ EasyIO.logger.info "Skipping removal from availability group: database [#{database_name}] does not belong to an AvailabilityGroup on [#{primary_server_name}]..."
246
+ return
247
+ end
248
+
249
+ remove_database_from_group_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/RemoveDatabaseFromGroup.sql")
250
+ drop_database_from_secondary_script = ::File.read("#{SqlCmd.sql_script_dir}/AlwaysOn/DropSecondary.sql")
251
+
252
+ values = { 'databasename' => database_name, 'availabilitygroupname' => server_info['AvailabilityGroup'] }
253
+
254
+ EasyIO.logger.header 'AlwaysOn Remove From Group'
255
+ EasyIO.logger.info "Removing [#{database_name}] from availability group..."
256
+ SqlCmd.execute_query(primary_connection_string, remove_database_from_group_script, values: values, retries: 3) unless database_info['AvailabilityGroup'].nil?
257
+ EasyIO.logger.header 'AlwaysOn Drop Database on Replica'
258
+ drop_result = SqlCmd.execute_query(replica_connection_string, drop_database_from_secondary_script, return_type: :scalar, values: values, retries: 3)
259
+ EasyIO.logger.debug "Drop secondary replica database result: #{drop_result}"
260
+ raise 'Failed to drop database from secondary replica!' unless drop_result
261
+ database_info = SqlCmd::Database.info(primary_connection_string, database_name)
262
+ replica_database_info = SqlCmd::Database.info(replica_connection_string, database_name)
263
+ raise 'Failed to remove database from AlwaysOn Availability Group' unless database_info['AvailabilityGroup'].nil? && replica_database_info['AvailabilityGroup'].nil?
264
+ EasyIO.logger.info "[#{database_name}] removed from AlwaysOn availability group successfully..."
265
+ end
266
+ end
267
+ end
@@ -0,0 +1,80 @@
1
+ module SqlCmd
2
+ module Azure
3
+ module AttachedStorage
4
+ module_function
5
+
6
+ # Upload a file to blob storage
7
+ # Either container_name or storage_url is required
8
+ def upload(filename, content, storage_account_name, storage_access_key, container_name: nil, storage_url: nil)
9
+ raise 'Either :container_name or :storage_url must be specified for SqlCmd::Azure::AttachedStorage.upload' if container_name.nil? && storage_url.nil?
10
+ OptionalDepedencies.load_azure_blob_storage_dependencies
11
+
12
+ # initialize ::Azure::Storage::Blob::BlobService client
13
+ client = ::Azure::Storage::Blob::BlobService.create(storage_account_name: storage_account_name, storage_access_key: storage_access_key)
14
+ container_name ||= container_name_from_url(storage_url, client: client) || ::File.basename(storage_url)
15
+ relative_path = storage_url.nil? ? filename : storage_file_relative_path(storage_url, filename, container_name)
16
+
17
+ # Add retry filter to the client
18
+ client.with_filter(::Azure::Storage::Common::Core::Filter::ExponentialRetryPolicyFilter.new)
19
+
20
+ client.create_block_blob(container_name, relative_path, content)
21
+ end
22
+
23
+ # Download a file from blob storage
24
+ # Either container_name or storage_url is required
25
+ def download(filename, destination_path, storage_account_name, storage_access_key, container_name: nil, storage_url: nil)
26
+ raise 'Either :container_name or :storage_url must be specified for SqlCmd::Azure::AttachedStorage.download' if container_name.nil? && storage_url.nil?
27
+ OptionalDepedencies.load_azure_blob_storage_dependencies
28
+
29
+ # initialize ::Azure::Storage::Blob::BlobService client
30
+ client = ::Azure::Storage::Blob::BlobService.create(storage_account_name: storage_account_name, storage_access_key: storage_access_key)
31
+ container_name ||= container_name_from_url(storage_url, client: client) || ::File.basename(storage_url)
32
+ relative_path = storage_url.nil? ? filename : storage_file_relative_path(storage_url, filename, container_name)
33
+
34
+ # Add retry filter to the client
35
+ client.with_filter(::Azure::Storage::Common::Core::Filter::ExponentialRetryPolicyFilter.new)
36
+
37
+ FileUtils.mkdir_p(::File.dirname(destination_path))
38
+ _blob, content = client.get_blob(container_name, relative_path)
39
+ ::File.open(destination_path, 'wb') { |f| f.write(content) }
40
+ end
41
+
42
+ # List files that in blob storage
43
+ # Either container_name or storage_url is required
44
+ # Returns hash of file URLs and their properties
45
+ def list(storage_account_name, storage_access_key, container_name: nil, storage_url: nil, filename_prefix: nil)
46
+ raise 'Either :container_name or :storage_url must be specified for SqlCmd::Azure::AttachedStorage.list' if container_name.nil? && storage_url.nil?
47
+ OptionalDepedencies.load_azure_blob_storage_dependencies
48
+
49
+ # initialize ::Azure::Storage::Blob::BlobService client
50
+ client = ::Azure::Storage::Blob::BlobService.create(storage_account_name: storage_account_name, storage_access_key: storage_access_key)
51
+ container_name ||= container_name_from_url(storage_url, client: client) || ::File.basename(storage_url)
52
+ relative_path = storage_url.nil? ? filename_prefix : storage_file_relative_path(storage_url, filename_prefix, container_name)
53
+
54
+ # Add retry filter to the client
55
+ client.with_filter(::Azure::Storage::Common::Core::Filter::ExponentialRetryPolicyFilter.new)
56
+
57
+ # Get list of files matching filename_prefix
58
+ blob_list_options = filename_prefix.nil? ? {} : { prefix: relative_path }
59
+ files = client.list_blobs(container_name, blob_list_options)
60
+ files.nil? ? [] : files.map { |f| [f.name, f.properties] }.to_h
61
+ end
62
+
63
+ def container_name_from_url(storage_url, client: nil)
64
+ if client.nil?
65
+ OptionalDepedencies.load_azure_blob_storage_dependencies
66
+
67
+ # initialize ::Azure::Storage::Blob::BlobService client
68
+ client = ::Azure::Storage::Blob::BlobService.create(storage_account_name: storage_account_name, storage_access_key: storage_access_key)
69
+ end
70
+ client.list_containers.map(&:name).select { |c| storage_url =~ %r{/#{Regexp.escape(c)}(/|$)} }.first
71
+ end
72
+
73
+ def storage_file_relative_path(storage_url, filename, container_name)
74
+ relative_path = storage_url.sub(/.+?#{Regexp.escape(container_name)}/i, '') + "/#{filename}"
75
+ relative_path.gsub!('//', '/')
76
+ relative_path.reverse.chomp('/').reverse
77
+ end
78
+ end
79
+ end
80
+ end