-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
custom.py
274 lines (231 loc) · 12.9 KB
/
custom.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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=import-error,too-many-locals,too-many-statements,too-many-nested-blocks
import os
from knack.util import CLIError
from knack.log import get_logger
import psycopg2
import pymysql
from pymysql.constants import CLIENT
from azure.cli.core.azclierror import RequiredArgumentMissingError, AzureConnectionError, ArgumentUsageError
from azure.cli.core.extension import EXTENSIONS_DIR
logger = get_logger(__name__)
DEFAULT_MYSQL_DB_NAME = '' # no default database required
DEFAULT_PG_DB_NAME = 'postgres'
# pylint: disable=raise-missing-from
def connect_to_flexible_server_mysql(cmd, server_name, administrator_login, administrator_login_password=None,
database_name=None, interactive_mode=None, querytext=None):
if querytext:
raise ArgumentUsageError("Use az mysql flexible-server execute command for query execution")
mysql_server_endpoint = cmd.cli_ctx.cloud.suffixes.mysql_server_endpoint
return connect_to_server_helper(server_type="mysql",
endpoint=mysql_server_endpoint,
default_db_name=DEFAULT_MYSQL_DB_NAME,
server_name=server_name,
administrator_login=administrator_login,
administrator_login_password=administrator_login_password,
database_name=database_name,
interactive=interactive_mode)
def connect_to_flexible_server_postgres(cmd, server_name, administrator_login, administrator_login_password=None,
database_name=None, interactive_mode=None, querytext=None):
if querytext:
raise ArgumentUsageError("Use az postgres flexible-server execute command for query execution")
postgresql_server_endpoint = cmd.cli_ctx.cloud.suffixes.postgresql_server_endpoint
return connect_to_server_helper(server_type="postgres",
endpoint=postgresql_server_endpoint,
default_db_name=DEFAULT_PG_DB_NAME,
server_name=server_name,
administrator_login=administrator_login,
administrator_login_password=administrator_login_password,
database_name=database_name,
interactive=interactive_mode)
def execute_flexible_server_mysql(cmd, server_name, administrator_login, administrator_login_password,
database_name=None, querytext=None, file_path=None):
mysql_server_endpoint = cmd.cli_ctx.cloud.suffixes.mysql_server_endpoint
return connect_to_server_helper(server_type="mysql",
endpoint=mysql_server_endpoint,
default_db_name=DEFAULT_MYSQL_DB_NAME,
server_name=server_name,
administrator_login=administrator_login,
administrator_login_password=administrator_login_password,
database_name=database_name,
query_command=querytext,
file_path=file_path)
def execute_flexible_server_postgres(cmd, server_name, administrator_login, administrator_login_password,
database_name=None, querytext=None, file_path=None):
postgresql_server_endpoint = cmd.cli_ctx.cloud.suffixes.postgresql_server_endpoint
return connect_to_server_helper(server_type="postgres",
endpoint=postgresql_server_endpoint,
default_db_name=DEFAULT_PG_DB_NAME,
server_name=server_name,
administrator_login=administrator_login,
administrator_login_password=administrator_login_password,
database_name=database_name,
query_command=querytext,
file_path=file_path)
def connect_to_server_helper(server_type, endpoint, default_db_name, server_name, administrator_login,
administrator_login_password, database_name, query_command=None,
interactive=None, file_path=None):
host = '{}{}'.format(server_name, endpoint)
json_data = None
# setup or validate passed in params:
if database_name is None:
database_name = default_db_name
if database_name: # in mysql scenario default db will be empty string
logger.warning("Connecting to %s database by default.",
database_name)
if administrator_login_password is None and interactive is None:
raise RequiredArgumentMissingError("Please provide password (--admin-password / -p) or "
"run in --interactive mode.")
# run in either interactive or simple connection mode
if interactive is not None:
if query_command is not None:
logger.warning("Ignoring query command passed in. Cannot run a query and interactive mode simultaneously. "
"Please try running either a simple query using -q or run your query in interactive "
"mode using --interactive.")
_connect_interactive(server_type=server_type,
host=host,
server_name=server_name,
database_name=database_name,
login_username=administrator_login)
elif file_path is None:
json_data = _connect_execute_query(server_type=server_type,
host=host,
server_name=server_name,
database_name=database_name,
login_username=administrator_login,
login_pw=administrator_login_password,
query=query_command)
if file_path is not None:
_connect_execute_file(server_type=server_type,
host=host,
server_name=server_name,
database_name=database_name,
login_username=administrator_login,
login_pw=administrator_login_password,
file_path=file_path)
return json_data
def set_environment_paths(extension_directory):
extension_python_path = os.path.join(extension_directory, 'rdbms-connect')
extension_path = os.path.join(extension_python_path, 'bin') # path to exe
# if path names are None then return empty string to allow concatenation
path_var = os.environ.get('PATH', '')
python_path_var = os.environ.get('PYTHONPATH', '')
if path_var:
os.environ["PATH"] += os.pathsep + extension_path
else:
os.environ['PATH'] = path_var
if python_path_var:
os.environ['PYTHONPATH'] += os.pathsep + extension_python_path
else:
os.environ['PYTHONPATH'] = extension_python_path
def _connect_interactive(server_type, host, server_name, database_name, login_username):
# if interactive mode indicated, use pgcli to connect
try:
# setup environment path variable for pgcli and mycli
set_environment_paths(EXTENSIONS_DIR)
if server_type == "postgres":
cmd = "pgcli -h {0} -u {1} -W {2}".format(host, login_username, database_name)
else:
cmd = "mycli -h {0} -u {1} {2} --ssl-verify-server-cert".format(host, login_username,
database_name)
os.system(cmd)
except Exception as e:
raise AzureConnectionError("Unable to open interactive mode to {0}. Error: {1}".format(server_name, e))
def _connect_execute_query(server_type, host, server_name, database_name, login_username, login_pw, query=None):
json_data = None
# connect to server
try:
connection_kwargs = {
'host': host,
'database': database_name,
'user': login_username,
'password': login_pw
}
# depending on server type, use the right connection library to test the connetion
if server_type == "postgres":
connection = psycopg2.connect(**connection_kwargs)
connection.set_session(autocommit=True)
else:
# set ssl param to allow for connection
connection_kwargs['ssl'] = {"fake_flag_to_enable_tls": True}
connection_kwargs['autocommit'] = True
connection = pymysql.connect(**connection_kwargs)
logger.warning('Successfully connected to %s.', server_name)
except Exception as e:
logger.warning("Failed connection to %s. Check error and validate firewall and public access "
"or virtual network settings.", server_name)
raise AzureConnectionError("Unable to connect to flexible server: {}".format(e))
if query is not None:
try:
cursor = connection.cursor()
cursor.execute(query)
logger.warning("Ran Database Query: '%s'", query)
logger.warning("Retrieving first 30 rows of query output, if applicable.")
# only print out if rows were returned
if cursor.description:
result = cursor.fetchmany(30) # limit to 30 rows of output for now
row_headers = [x[0] for x in cursor.description] # this will extract row headers
# format the result for a clean display
json_data = []
for rv in result:
json_data.append(dict(zip(row_headers, rv)))
except Exception as e:
raise CLIError("Unable to execute query '{0}': {1}".format(query, e))
finally:
try:
cursor.close()
logger.warning("Closed the connection to %s", server_name)
except Exception as e: # pylint: disable=broad-except
logger.warning('Unable to close connection cursor.')
raise CLIError(str(e))
return json_data
def _connect_execute_file(server_type, host, server_name, database_name, login_username, login_pw, file_path):
# connect to server
try:
connection_kwargs = {
'host': host,
'database': database_name,
'user': login_username,
'password': login_pw
}
# depending on server type, use the right connection library to test the connetion
if server_type == "postgres":
connection = psycopg2.connect(**connection_kwargs)
connection.set_session(autocommit=True)
else:
# set ssl param to allow for connection
connection_kwargs['ssl'] = {"fake_flag_to_enable_tls": True}
connection_kwargs['client_flag'] = CLIENT.MULTI_STATEMENTS
connection_kwargs['autocommit'] = True
connection = pymysql.connect(**connection_kwargs)
except Exception as e:
logger.warning("Failed connection to %s. Check error and validate firewall and public access "
"or virtual network settings.", server_name)
raise AzureConnectionError("Unable to connect to flexible server: {}".format(e))
# Execute the file
fail_flag = False
try:
logger.warning("Running sql file '%s'...", file_path)
cursor = connection.cursor()
with open(file_path, "r", encoding="utf-8-sig") as sql_file:
cursor.execute(sql_file.read())
if server_type == 'postgres':
logger.warning('Successfully executed the file.')
except Exception as e:
fail_flag = True
logger.warning("Unable to execute the sql file %s", file_path)
raise CLIError(e)
finally:
if cursor is not None:
try:
cursor.close()
if not fail_flag and server_type == 'mysql':
logger.warning('Successfully executed the file.')
logger.warning("Closed the connection to %s", server_name)
except Exception as e: # pylint: disable=broad-except
if server_type == 'postgres':
raise CLIError("Unable to close connection cursor. " + str(e))
raise CLIError(str(e))