def set_token(self): import traceback from knack.log import get_logger logger = get_logger(__name__) from azure.cli.core.azclierror import AzureConnectionError, AzureResponseError try: super(MSIAuthenticationWrapper, self).set_token() except requests.exceptions.ConnectionError as err: logger.debug( 'throw requests.exceptions.ConnectionError when doing MSIAuthentication: \n%s', traceback.format_exc()) raise AzureConnectionError( 'Failed to connect to MSI. Please make sure MSI is configured correctly ' 'and check the network connection.\nError detail: {}'.format( str(err))) except requests.exceptions.HTTPError as err: logger.debug( 'throw requests.exceptions.HTTPError when doing MSIAuthentication: \n%s', traceback.format_exc()) raise AzureResponseError( 'Failed to connect to MSI. Please make sure MSI is configured correctly.\n' 'Get Token request returned http error: {}, reason: {}'.format( err.response.status, err.response.reason)) except TimeoutError as err: logger.debug( 'throw TimeoutError when doing MSIAuthentication: \n%s', traceback.format_exc()) raise AzureConnectionError( 'MSI endpoint is not responding. Please make sure MSI is configured correctly.\n' 'Error detail: {}'.format(str(err)))
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") 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))
def connect_and_send_admin_command(self, command, arg_characters=None): if command == "nmi": func = self.send_nmi success_message = "NMI sent successfully \r\n" failure_message = "Failed to send NMI \r\n" loading_text = "Sending NMI to VM" elif command == "reset": func = self.send_reset success_message = "Successfully Hard Reset VM \r\n" failure_message = "Failed to Hard Reset VM \r\n" loading_text = "Forcing VM to Hard Reset" elif command == "sysrq" and arg_characters is not None: def wrapper(): return self.send_sys_rq(arg_characters) func = wrapper success_message = "Successfully sent SysRq command\r\n" failure_message = "Failed to send SysRq command. Make sure the input only contains numbers and letters.\r\n" loading_text = "Sending SysRq to VM" else: return GV.loading = True th1 = threading.Thread( target=self.send_loading_message, args=(loading_text,)) th1.daemon = True th1.start() if self.load_websocket_url(): def on_message(ws, _): GV.trycount += 1 if func(): GV.loading = False GV.terminating_app = True print(success_message, end="") ws.close() elif GV.trycount >= 2: GV.loading = False GV.terminating_app = True print(failure_message, end="") ws.close() wsapp = websocket.WebSocketApp( self.websocket_url + "?authorization=" + self.access_token, on_message=on_message) wsapp.run_forever() GV.loading = False if GV.trycount == 0: error_message = "Could not establish connection to VM or VMSS." recommendation = 'Try restarting it with "az vm restart".' raise AzureConnectionError( error_message, recommendation=recommendation) else: GV.loading = False error_message = "An unexpected error occured. Could not establish connection to VM or VMSS." recommendation = "Check network connection and try again." raise ResourceNotFoundError( error_message, recommendation=recommendation)
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 = 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_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 check_resource(cli_ctx, resource_group_name, vm_vmss_name, vmss_instanceid): check_serial_console_enabled(cli_ctx) client = _compute_client_factory(cli_ctx) if vmss_instanceid: result = client.virtual_machine_scale_set_vms.get_instance_view( resource_group_name, vm_vmss_name, vmss_instanceid) if 'osName' in result.additional_properties and "windows" in result.additional_properties[ 'osName'].lower(): GV.os_is_windows = True power_state = ','.join([ s.display_status for s in result.statuses if s.code.startswith('PowerState/') ]).lower() if "deallocating" in power_state or "deallocated" in power_state: error_message = "Azure Serial Console requires a virtual machine to be running." recommendation = 'Use "az vmss start" to start the Virtual Machine.' raise AzureConnectionError(error_message, recommendation=recommendation) if result.boot_diagnostics is None: error_message = ( "Azure Serial Console requires boot diagnostics to be enabled." ) recommendation = ( 'Use "az vmss update --name MyScaleSet --resource-group MyResourceGroup --set ' 'virtualMachineProfile.diagnosticsProfile="{\\"bootDiagnostics\\": {\\"Enabled\\" : ' '\\"True\\",\\"StorageUri\\" : null}}"" to enable boot diagnostics. ' 'You can replace "null" with a custom storage account ' '\\"https://mystor.blob.windows.net/"\\. Then run "az vmss update-instances -n ' 'MyScaleSet -g MyResourceGroup --instance-ids *".') raise AzureConnectionError(error_message, recommendation=recommendation) else: try: result = client.virtual_machines.get(resource_group_name, vm_vmss_name, expand='instanceView') except ComputeClientResourceNotFoundError as e: try: client.virtual_machine_scale_sets.get(resource_group_name, vm_vmss_name) except ComputeClientResourceNotFoundError: raise e from e error_message = e.message recommendation = ( "We found that you specified a Virtual Machine Scale Set and not a VM. " "Use the --instance-id parameter to select the VMSS instance you want to connect to." ) raise ResourceNotFoundError(error_message, recommendation=recommendation) from e if (result.instance_view is not None and result.instance_view.os_name is not None and "windows" in result.instance_view.os_name.lower()): GV.os_is_windows = True if (result.storage_profile is not None and result.storage_profile.image_reference is not None and result.storage_profile.image_reference.offer is not None and "windows" in result.storage_profile.image_reference.offer.lower()): GV.os_is_windows = True power_state = ','.join([ s.display_status for s in result.instance_view.statuses if s.code.startswith('PowerState/') ]) if "deallocating" in power_state or "deallocated" in power_state: error_message = "Azure Serial Console requires a virtual machine to be running." recommendation = 'Use "az vm start" to start the Virtual Machine.' raise AzureConnectionError(error_message, recommendation=recommendation) if (result.diagnostics_profile is None or result.diagnostics_profile.boot_diagnostics is None or not result.diagnostics_profile.boot_diagnostics.enabled): error_message = ( "Azure Serial Console requires boot diagnostics to be enabled." ) recommendation = ( 'Use "az vm boot-diagnostics enable --name MyVM --resource-group MyResourceGroup" ' 'to enable boot diagnostics. You can specify a custom storage account with the ' 'parameter "--storage https://mystor.blob.windows.net/".') raise AzureConnectionError(error_message, recommendation=recommendation)