def setUp(self): self.logger = console_logger.ConsoleLogger() self.distro_patcher = patch.GetDistroPatcher(self.logger) self.hutil = HandlerUtil.HandlerUtility(self.logger.log, self.logger.error, "AzureDiskEncryptionForLinux") self.hutil.patching = self.distro_patcher # invoke unit test from within main for setup (to avoid having to change dependencies) # then move cwd to parent to emulate calling convention of guest agent if os.getcwd().endswith('main'): os.chdir(os.path.dirname(os.getcwd())) else: self.logger.log(os.getcwd())
def main(): global MyPatching, backup_logger, hutil HandlerUtil.LoggerInit('/var/log/waagent.log', '/dev/stdout') HandlerUtil.waagent.Log("%s started to handle." % (CommonVariables.extension_name)) hutil = HandlerUtil.HandlerUtility(HandlerUtil.waagent.Log, HandlerUtil.waagent.Error, CommonVariables.extension_name) backup_logger = Backuplogger(hutil) MyPatching = GetMyPatching(logger=backup_logger) hutil.patching = MyPatching for a in sys.argv[1:]: if re.match("^([-/]*)(disable)", a): disable() elif re.match("^([-/]*)(uninstall)", a): uninstall() elif re.match("^([-/]*)(install)", a): install() elif re.match("^([-/]*)(enable)", a): enable() elif re.match("^([-/]*)(update)", a): update()
def get_deployment_type(vsts_url, pat_token): rest_call_url = vsts_url + '/_apis/connectiondata' response = Util.make_http_call(rest_call_url, 'GET', None, None, pat_token) if (response.status == Constants.HTTP_OK): connection_data = json.loads(response.read()) if (connection_data.has_key('deploymentType')): return connection_data['deploymentType'] else: return 'onPremises' else: handler_utility.log( 'Failed to fetch the connection data for the url {0}. Reason : {1} {2}' .format(rest_call_url, str(response.status), response.reason)) return 'hosted'
def enable(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.do_parse_context('Enable') try: _forcibly_reset_chap(hutil) reset_ssh = None remove_user = None protect_settings = hutil.get_protected_settings() if protect_settings: reset_ssh = protect_settings.get('reset_ssh') remove_user = protect_settings.get('remove_user') if remove_user and _is_sshd_config_modified(protect_settings): waagent.AddExtensionEvent(name=hutil.get_name(), op=waagent.WALAEventOperation.Enable, isSuccess=False, message="(03002)Argument error, conflicting operations") raise Exception("Cannot reset sshd_config and remove a user in one operation.") # check port each time the VM boots up if reset_ssh: _open_ssh_port() hutil.log("Succeeded in check and open ssh port.") hutil.exit_if_enabled() if _is_sshd_config_modified(protect_settings): _backup_sshd_config(SshdConfigPath) if reset_ssh: waagent.AddExtensionEvent(name=hutil.get_name(), op="scenario", isSuccess=True, message="reset-ssh") _reset_sshd_config(SshdConfigPath) hutil.log("Succeeded in reset sshd_config.") if remove_user: waagent.AddExtensionEvent(name=hutil.get_name(), op="scenario", isSuccess=True, message="remove-user") _remove_user_account(remove_user, hutil) _set_user_account_pub_key(protect_settings, hutil) if _is_sshd_config_modified(protect_settings): waagent.MyDistro.restartSshService() check_and_repair_disk(hutil) hutil.do_exit(0, 'Enable', 'success', '0', 'Enable succeeded.') except Exception as e: hutil.error(("Failed to enable the extension with error: {0}, " "stack trace: {1}").format(str(e), traceback.format_exc())) hutil.do_exit(1, 'Enable', 'error', '0', "Enable failed: {0}".format(str(e)))
def parse_context(operation): """ Initialize a HandlerUtil object for this operation. If the required modules have not been imported, this will return None. """ hutil = None if 'Utils.WAAgentUtil' in sys.modules and 'Utils.HandlerUtil' in sys.modules: try: hutil = HUtil.HandlerUtility(waagent.Log, waagent.Error) hutil.do_parse_context(operation) # parse_context may throw KeyError if necessary JSON key is not # present in settings except KeyError as e: waagent_log_error('Unable to parse context with error: ' \ '{0}'.format(e.message)) raise OmsAgentParameterMissingError return hutil
def init_globals(): """Initialize all the globals in a function so that we can catch any exceptions that might be raised.""" global hutil, g_ext_dir, g_mdsd_file_resources_prefix, g_lad_pids_filepath global g_diagnostic_py_filepath, g_lad_log_helper waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') waagent.Log("LinuxDiagnostic started to handle.") hutil = Util.HandlerUtility(waagent.Log, waagent.Error) init_extension_settings() init_distro_specific_actions() g_ext_dir = os.getcwd() g_mdsd_file_resources_prefix = os.path.join(g_mdsd_file_resources_dir, g_mdsd_role_name) g_lad_pids_filepath = os.path.join(g_ext_dir, 'lad.pids') g_diagnostic_py_filepath = os.path.join(os.getcwd(), __file__) g_lad_log_helper = LadLogHelper(hutil.log, hutil.error, waagent.AddExtensionEvent, hutil.do_status_report, hutil.get_name(), hutil.get_extension_version())
def get_settings(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error, "bosh-deploy-script") hutil.do_parse_context("enable") settings_path = os.path.join('bosh', 'settings') call("mkdir -p ./bosh", shell=True) if not os.path.isfile(settings_path): settings = hutil.get_public_settings() with open(settings_path, "w") as tmpfile: tmpfile.write(json.dumps(settings, indent=4, sort_keys=True)) else: with open(settings_path) as settings_file: settings = json.load(settings_file) return settings
def parse_account_name(account_name, pat_token): vsts_url = account_name.strip('/') account_name_prefix = Util.get_account_name_prefix(account_name) if (account_name_prefix == ''): vsts_url = 'https://{0}.visualstudio.com'.format(account_name) deployment_type = get_deployment_type(vsts_url, pat_token) if (deployment_type != 'hosted'): Constants.is_on_prem = True vsts_url_without_prefix = vsts_url[len(account_name_prefix):] parts = filter(lambda x: x != '', vsts_url_without_prefix.split('/')) if (len(parts) <= 1): raise Exception( "Invalid value for the input 'Azure DevOps Organization url'. It should be in the format http(s)://<server>/<application>/<collection> for on-premise deployment." ) return vsts_url
def enable(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.do_parse_context('Enable') try: _forcibly_reset_chap(hutil) reset_ssh = None remove_user = None protect_settings = hutil.get_protected_settings() if protect_settings: reset_ssh = protect_settings.get('reset_ssh') remove_user = protect_settings.get('remove_user') # check port each time the VM boots up if reset_ssh: _open_ssh_port() hutil.log("Succeeded in check and open ssh port.") hutil.exit_if_enabled() if _is_sshd_config_modified(protect_settings): _backup_sshd_config(SshdConfigPath) if reset_ssh: _reset_sshd_config(SshdConfigPath) hutil.log("Succeeded in reset sshd_config.") if remove_user: _remove_user_account(remove_user, hutil) _set_user_account_pub_key(protect_settings, hutil) if _is_sshd_config_modified(protect_settings): waagent.MyDistro.restartSshService() check_and_repair_disk(hutil) hutil.do_exit(0, 'Enable', 'success', '0', 'Enable succeeded.') except Exception as e: hutil.error(("Failed to enable the extension with error: {0}, " "stack trace: {1}").format(str(e), traceback.format_exc())) hutil.do_exit(1, 'Enable', 'error', '0', 'Enable failed.')
def main(): waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') waagent.Log("%s started to handle." % (ExtensionShortName)) global hutil hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.try_parse_context() global public_settings public_settings = hutil.get_public_settings() if not public_settings: waagent.AddExtensionEvent(name=ExtensionShortName, op='MainInProgress', isSuccess=True, message="Public settings are NOT provided.") public_settings = {} global protected_settings protected_settings = hutil.get_protected_settings() if not protected_settings: waagent.AddExtensionEvent( name=ExtensionShortName, op='MainInProgress', isSuccess=True, message="protected settings are NOT provided.") protected_settings = {} global distro_category distro_category = get_distro_category() for a in sys.argv[1:]: if re.match("^([-/]*)(disable)", a): disable() elif re.match("^([-/]*)(uninstall)", a): uninstall() elif re.match("^([-/]*)(install)", a): install() elif re.match("^([-/]*)(enable)", a): enable() elif re.match("^([-/]*)(update)", a): update()
def setUp(self): print '\n\n============================================================================================' waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') waagent.Log("%s started to handle." % (ExtensionShortName)) global protect_settings protect_settings = json.loads(contents) global hutil hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) global MyPatching MyPatching = FakePatching(hutil) if MyPatching == None: sys.exit(1) try: os.remove('mrseq') except: pass waagent.SetFileContents(MyPatching.package_downloaded_path, '') waagent.SetFileContents(MyPatching.package_patched_path, '')
def main(): global MyPatching, backup_logger, hutil, run_result, run_status, error_msg, freezer, freeze_result, snapshot_info_array, total_used_size, size_calculation_failed, patch_class_name, orig_distro, configSeqNo try: run_result = CommonVariables.success run_status = 'success' error_msg = '' freeze_result = None snapshot_info_array = None total_used_size = 0 size_calculation_failed = False HandlerUtil.waagent.LoggerInit('/dev/console', '/dev/stdout') hutil = HandlerUtil.HandlerUtility(HandlerUtil.waagent.Log, HandlerUtil.waagent.Error, CommonVariables.extension_name) backup_logger = Backuplogger(hutil) MyPatching, patch_class_name, orig_distro = GetMyPatching( backup_logger) hutil.patching = MyPatching configSeqNo = -1 for a in sys.argv[1:]: if re.match("^([-/]*)(disable)", a): disable() elif re.match("^([-/]*)(uninstall)", a): uninstall() elif re.match("^([-/]*)(install)", a): install() elif re.match("^([-/]*)(enable)", a): enable() elif re.match("^([-/]*)(update)", a): update() elif re.match("^([-/]*)(daemon)", a): daemon() elif re.match("^([-/]*)(seqNo:)", a): try: configSeqNo = int(a.split(':')[1]) except: configSeqNo = -1 except Exception as e: sys.exit(0)
def enable(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) hutil.do_parse_context('Install') try: protect_settings = hutil._context._config['runtimeSettings'][0][ 'handlerSettings'].get('protectedSettings') reset_ssh = protect_settings.get('reset_ssh') # check port each time the VM boots up if reset_ssh: _open_ssh_port() hutil.log("Succeeded in check and open ssh port.") hutil.exit_if_enabled() _set_user_account_pub_key(protect_settings, hutil) if reset_ssh: _reset_sshd_config() hutil.log("Succeeded in reset sshd_config.") hutil.do_exit(0, 'Enable', 'success', '0', 'Enable succeeded.') except Exception, e: hutil.error( "Failed to enable the extension with error: %s, stack trace: %s" % (str(e), traceback.format_exc())) hutil.do_exit(1, 'Enable', 'error', '0', 'Enable failed.')
def main(): waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') waagent.Log("%s started to handle." % (ExtensionShortName)) global hutil hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) global myProvision myProvision = GetMyProvision(hutil) if myProvision == None: sys.exit(1) for a in sys.argv[1:]: if re.match("^([-/]*)(disable)", a): disable() elif re.match("^([-/]*)(uninstall)", a): uninstall() elif re.match("^([-/]*)(install)", a): install() elif re.match("^([-/]*)(enable)", a): enable() elif re.match("^([-/]*)(update)", a): update() elif re.match("^([-/]*)(provision)", a): provision()
def setUp(self): print '\n\n============================================================================================' waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') waagent.Log("%s started to handle." % (ExtensionShortName)) global hutil hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.do_parse_context('TEST') global MyPatching MyPatching = FakePatching(hutil) if MyPatching is None: sys.exit(1) distro = DistInfo()[0] if 'centos' in distro or 'Oracle' in distro or 'redhat' in distro: MyPatching.cron_restart_cmd = 'service crond restart' try: os.remove('mrseq') except: pass waagent.SetFileContents(MyPatching.package_downloaded_path, '') waagent.SetFileContents(MyPatching.package_patched_path, '')
def disable(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.do_parse_context('Disable') hutil.do_exit(0, 'Disable', 'success', '0', 'Disable Succeeded')
def parse_context(operation): hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) hutil.try_parse_context() return
import base64 import xml.dom.minidom import xml.etree.ElementTree as ET from collections import defaultdict import Utils.LadDiagnosticUtil as LadUtil import Utils.XmlUtil as XmlUtil import Utils.ApplicationInsightsUtil as AIUtil ExtensionShortName = 'LinuxAzureDiagnostic' WorkDir = os.getcwd() MDSDPidFile = os.path.join(WorkDir, 'mdsd.pid') OutputSize = 1024 EnableSyslog = True waagent.LoggerInit('/var/log/waagent.log','/dev/stdout') waagent.Log("%s started to handle." %(ExtensionShortName)) hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) hutil.try_parse_context() public_settings = hutil.get_public_settings() private_settings = hutil.get_protected_settings() if not public_settings: public_settings = {} if not private_settings: private_settings = {} def LogRunGetOutPut(cmd): hutil.log("RunCmd "+cmd) error, msg = waagent.RunGetOutput(cmd) hutil.log("Return "+str(error)+":"+msg) return error, msg
def parse_context(operation): hutil = util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName, ExtensionFullName, ExtensionVersion) hutil.do_parse_context(operation) return hutil
import re import json import traceback from subprocess import call from Utils.WAAgentUtil import waagent import Utils.HandlerUtil as Util from azure.storage import BlobService from azure.storage import TableService call("mkdir -p ./bosh", shell=True) call("chmod +x deploy_bosh.sh", shell=True) call("cp deploy_bosh.sh ./bosh/", shell=True) # Get settings from CustomScriptForLinux extension configurations waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') hutil = Util.HandlerUtility(waagent.Log, waagent.Error, "bosh-deploy-script") hutil.do_parse_context("enable") settings = hutil.get_public_settings() with open(os.path.join('bosh', 'settings'), "w") as tmpfile: tmpfile.write(json.dumps(settings, indent=4, sort_keys=True)) username = settings["username"] home_dir = os.path.join("/home", username) install_log = os.path.join(home_dir, "install.log") # Prepare the containers storage_account_name = settings["STORAGE-ACCOUNT-NAME"] storage_access_key = settings["STORAGE-ACCESS-KEY"] blob_service = BlobService(storage_account_name, storage_access_key) blob_service.create_container('bosh') blob_service.create_container(container_name='stemcell', x_ms_blob_public_access='blob')
def get_configuration_from_settings(): try: public_settings = handler_utility.get_public_settings() if (public_settings == None): public_settings = {} handler_utility.verify_public_settings_is_dict(public_settings) protected_settings = handler_utility.get_protected_settings() if (protected_settings == None): protected_settings = {} handler_utility.log("get_configuration_from_settings") #################################################################################################################################### #################################################################################################################################### # If this is a pipelines agent, read the settings and return quickly # Note that the pipelines settings come over as camelCase if (public_settings.has_key('isPipelinesAgent')): handler_utility.log("Is Pipelines Agent") # read pipelines agent settings agentDownloadUrl = public_settings['agentDownloadUrl'] handler_utility.verify_input_not_null('agentDownloadUrl', agentDownloadUrl) agentFolder = public_settings['agentFolder'] handler_utility.verify_input_not_null('agentFolder', agentFolder) enableScriptDownloadUrl = public_settings[ 'enableScriptDownloadUrl'] handler_utility.verify_input_not_null('enableScriptDownloadUrl', enableScriptDownloadUrl) # for testing, first try to get the script parameters from the public settings # in production they will be in the protected settings handler_utility.log("looking for enableScriptParameters") if (protected_settings.has_key('enableScriptParameters')): handler_utility.log("protected enableScriptParameters") enableScriptParameters = protected_settings[ 'enableScriptParameters'] if (public_settings.has_key('enableScriptParameters')): handler_utility.log("public enableScriptParameters") enableScriptParameters = public_settings[ 'enableScriptParameters'] handler_utility.log("validating enableScriptParameters") handler_utility.verify_input_not_null('enableScriptParameters', enableScriptParameters) return { 'IsPipelinesAgent': 'true', 'AgentDownloadUrl': agentDownloadUrl, 'AgentFolder': agentFolder, 'EnableScriptDownloadUrl': enableScriptDownloadUrl, 'EnableScriptParameters': enableScriptParameters } #################################################################################################################################### #################################################################################################################################### # continue with deployment agent settings handler_utility.log("Is Deployment Agent") pat_token = '' if ((protected_settings.__class__.__name__ == 'dict') and protected_settings.has_key('PATToken')): pat_token = protected_settings['PATToken'] if ((pat_token == '') and (public_settings.has_key('PATToken'))): pat_token = public_settings['PATToken'] vsts_account_url = '' if (public_settings.has_key('AzureDevOpsOrganizationUrl')): vsts_account_url = public_settings[ 'AzureDevOpsOrganizationUrl'].strip('/') elif (public_settings.has_key('VSTSAccountUrl')): vsts_account_url = public_settings['VSTSAccountUrl'].strip('/') elif (public_settings.has_key('VSTSAccountName')): vsts_account_url = public_settings['VSTSAccountName'].strip('/') handler_utility.verify_input_not_null('AzureDevOpsOrganizationUrl', vsts_account_url) vsts_url = vsts_account_url vsts_url = parse_account_name(vsts_account_url, pat_token) handler_utility.log( 'Azure DevOps Organization Url : {0}'.format(vsts_url)) team_project_name = '' if (public_settings.has_key('TeamProject')): team_project_name = public_settings['TeamProject'] handler_utility.verify_input_not_null('TeamProject', team_project_name) handler_utility.log('Team Project : {0}'.format(team_project_name)) deployment_group_name = '' if (public_settings.has_key('DeploymentGroup')): deployment_group_name = public_settings['DeploymentGroup'] elif (public_settings.has_key('MachineGroup')): deployment_group_name = public_settings['MachineGroup'] handler_utility.verify_input_not_null('DeploymentGroup', deployment_group_name) handler_utility.log( 'Deployment Group : {0}'.format(deployment_group_name)) agent_name = '' if (public_settings.has_key('AgentName')): agent_name = public_settings['AgentName'] handler_utility.log('Agent Name : {0}'.format(agent_name)) tags_input = [] if (public_settings.has_key('Tags')): tags_input = public_settings['Tags'] handler_utility.log('Tags : {0}'.format(tags_input)) tags = format_tags_input(tags_input) configure_agent_as_username = '' if (public_settings.has_key('UserName')): configure_agent_as_username = public_settings['UserName'] handler_utility.log('Done reading config settings from file...') handler_utility.add_handler_sub_status( Util.HandlerSubStatus('SuccessfullyReadSettings')) return { 'VSTSUrl': vsts_url, 'PATToken': pat_token, 'TeamProject': team_project_name, 'DeploymentGroup': deployment_group_name, 'AgentName': agent_name, 'Tags': tags, 'AgentWorkingFolder': Constants.agent_working_folder, 'ConfigureAgentAsUserName': configure_agent_as_username } except Exception as e: set_error_status_and_error_exit( e, RMExtensionStatus.rm_extension_status['ReadingSettings'] ['operationName'], RMExtensionStatus.rm_extension_status['InputConfigurationError'])
def parse_context(operation, logfile=None): hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) hutil.do_parse_context(operation, logfile) return hutil
def parse_context(operation): hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName, console_logger=waagent.LogToConsole, file_logger=waagent.LogToFile) hutil.do_parse_context(operation) return hutil
def enable_pipelines_agent(config): try: handler_utility.log('Enable Pipelines Agent') handler_utility.add_handler_sub_status( Util.HandlerSubStatus('DownloadPipelinesAgent')) agentFolder = config["AgentFolder"] handler_utility.log(agentFolder) if (not os.path.isdir(agentFolder)): handler_utility.log('Agent folder does not exist. Creating it.') os.makedirs(agentFolder, 0o777) # download the agent tar file handler_utility.add_handler_sub_status( Util.HandlerSubStatus('DownloadPipelinesZip')) handler_utility.log('Download Pipelines Zip') downloadUrl = config["AgentDownloadUrl"] handler_utility.log(downloadUrl) filename = os.path.basename(downloadUrl) agentFile = os.path.join(agentFolder, filename) urllib.urlretrieve(downloadUrl, agentFile) # download the enable script handler_utility.add_handler_sub_status( Util.HandlerSubStatus('DownloadPipelinesScript')) handler_utility.log('Download Pipelines Script') downloadUrl = config["EnableScriptDownloadUrl"] handler_utility.log(downloadUrl) filename = os.path.basename(downloadUrl) enableFile = os.path.join(agentFolder, filename) urllib.urlretrieve(downloadUrl, enableFile) except Exception as e: handler_utility.log(getattr(e, 'message')) handler_utility.log(e) set_error_status_and_error_exit( e, RMExtensionStatus.rm_extension_status[ 'DownloadPipelinesAgentError']['operationName'], getattr(e, 'message')) return try: # grant executable access to the script os.chmod(enableFile, 0o777) # run the enable script handler_utility.add_handler_sub_status( Util.HandlerSubStatus('EnablePipelinesAgent')) handler_utility.log('Run Pipelines Script') handler_utility.log(enableFile) enableParameters = config["EnableScriptParameters"] # run the script and wait for it to complete handler_utility.log("running script") argList = ['/bin/bash', enableFile] + shlex.split(enableParameters) enableProcess = subprocess.Popen(argList) enableProcess.communicate() except Exception as e: handler_utility.log(getattr(e, 'message')) handler_utility.log(e) set_error_status_and_error_exit( e, RMExtensionStatus.rm_extension_status['EnablePipelinesAgentError'] ['operationName'], getattr(e, 'message')) return handler_utility.add_handler_sub_status( Util.HandlerSubStatus('EnablePipelinesAgentSuccess')) handler_utility.set_handler_status(Util.HandlerStatus( 'Enabled', 'success')) handler_utility.log('Pipelines Agent is enabled.')
def update(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.do_parse_context('Update') hutil.do_exit(0, 'Update', 'success', '0', 'Update Succeeded')
import xml.etree.ElementTree as ET import Utils.HandlerUtil as Util import Utils.LadDiagnosticUtil as LadUtil import Utils.XmlUtil as XmlUtil import Utils.ApplicationInsightsUtil as AIUtil from Utils.WAAgentUtil import waagent WorkDir = os.getcwd() MDSDPidFile = os.path.join(WorkDir, 'mdsd.pid') MDSDPidPortFile = os.path.join(WorkDir, 'mdsd.pidport') OutputSize = 1024 EnableSyslog = True waagent.LoggerInit('/var/log/waagent.log','/dev/stdout') waagent.Log("LinuxAzureDiagnostic started to handle.") hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.try_parse_context() hutil.set_verbose_log(False) # Explicitly set verbose flag to False. This is default anyway, but it will be made explicit and logged. public_settings = hutil.get_public_settings() private_settings = hutil.get_protected_settings() if not public_settings: public_settings = {} if not private_settings: private_settings = {} ExtensionOperationType = None # Better deal with the silly waagent typo, in anticipation of a proper fix of the typo later on waagent if not hasattr(waagent.WALAEventOperation, 'Uninstall'): if hasattr(waagent.WALAEventOperation, 'UnIsntall'): waagent.WALAEventOperation.Uninstall = waagent.WALAEventOperation.UnIsntall else: # This shouldn't happen, but just in case... waagent.WALAEventOperation.Uninstall = 'Uninstall'
def install(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.do_parse_context('Install') hutil.do_exit(0, 'Install', 'success', '0', 'Install Succeeded')
def parse_context(operation): hutil = Util.HandlerUtility(waagent.Log, waagent.Error) hutil.try_parse_context() return
def uninstall(): hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) hutil.do_parse_context('Uninstall') hutil.do_exit(0, 'Uninstall', 'success', '0', 'Uninstall succeeded')
def validate_inputs(config): try: invalid_pat_error_message = "Please make sure that the Personal Access Token entered is valid and has 'Deployment Groups - Read & manage' scope." inputs_validation_error_code = RMExtensionStatus.rm_extension_status[ 'InputConfigurationError'] unexpected_error_message = "Some unexpected error occured. Status code : {0}" error_message_initial_part = "Could not verify that the deployment group '" + config[ 'DeploymentGroup'] + "' exists in the project '" + config[ 'TeamProject'] + "' in the specified organization '" + config[ 'VSTSUrl'] + "'. Status: {0} Error: {1}. " # Verify the deployment group exists and the PAT has the required(Deployment Groups - Read & manage) scope # This is the first validation http call, so using Invoke-WebRequest instead of Invoke-RestMethod, because if the PAT provided is not a token at all(not even an unauthorized one) and some random value, then the call # would redirect to sign in page and not throw an exception. So, to handle this case. specific_error_message = "" get_deployment_group_url = "{0}/{1}/_apis/distributedtask/deploymentgroups?name={2}&api-version={3}".format( config['VSTSUrl'], quote(config['TeamProject']), quote(config['DeploymentGroup']), Constants.projectAPIVersion) handler_utility.log( "Get deployment group url - {0}".format(get_deployment_group_url)) response = Util.make_http_call(get_deployment_group_url, 'GET', None, None, config['PATToken']) if (response.status != Constants.HTTP_OK): if (response.status == Constants.HTTP_FOUND): specific_error_message = invalid_pat_error_message elif (response.status == Constants.HTTP_UNAUTHORIZED): specific_error_message = invalid_pat_error_message elif (response.status == Constants.HTTP_FORBIDDEN): specific_error_message = "Please ensure that the user has 'View project-level information' permissions on the project '{0}'.".format( config['TeamProject']) elif (response.status == Constants.HTTP_NOTFOUND): specific_error_message = "Please make sure that you enter the correct organization name and verify that the project exists in the organization." else: specific_error_message = unexpected_error_message.format( response.status) inputs_validation_error_code = RMExtensionStatus.rm_extension_status[ 'GenericError'] error_message = error_message_initial_part.format( response.status, specific_error_message) raise RMExtensionStatus.new_handler_terminating_error( inputs_validation_error_code, error_message) deployment_group_data = json.loads(response.read()) if (('value' not in deployment_group_data) or len(deployment_group_data['value']) == 0): specific_error_message = "Please make sure that the deployment group {0} exists in the project {1}, and the user has 'Manage' permissions on the deployment group.".format( config['DeploymentGroup'], config['TeamProject']) raise RMExtensionStatus.new_handler_terminating_error( inputs_validation_error_code, error_message_initial_part.format(response.status, specific_error_message)) deployment_group_id = deployment_group_data['value'][0]['id'] handler_utility.log( "Validated that the deployment group {0} exists".format( config['DeploymentGroup'])) headers = {} headers['Content-Type'] = 'application/json' body = "{'name': '" + config['DeploymentGroup'] + "'}" patch_deployment_group_url = "{0}/{1}/_apis/distributedtask/deploymentgroups/{2}?api-version={3}".format( config['VSTSUrl'], quote(config['TeamProject']), deployment_group_id, Constants.projectAPIVersion) handler_utility.log("Patch deployment group url - {0}".format( patch_deployment_group_url)) response = Util.make_http_call(patch_deployment_group_url, 'PATCH', body, headers, config['PATToken']) if (response.status != Constants.HTTP_OK): if (response.status == Constants.HTTP_FORBIDDEN): specific_error_message = "Please ensure that the user has 'Manage' permissions on the deployment group {0}".format( config['DeploymentGroup']) else: specific_error_message = unexpected_error_message.format( str(response.status)) inputs_validation_error_code = RMExtensionStatus.rm_extension_status[ 'GenericError'] raise RMExtensionStatus.new_handler_terminating_error( inputs_validation_error_code, error_message_initial_part.format( response.status, response.reason) + specific_error_message) handler_utility.log( "Validated that the user has 'Manage' permissions on the deployment group '{0}'" .format(config['DeploymentGroup'])) handler_utility.log("Done validating inputs...") handler_utility.add_handler_sub_status( Util.HandlerSubStatus('SuccessfullyValidatedInputs')) except Exception as e: set_error_status_and_error_exit( e, RMExtensionStatus.rm_extension_status['ValidatingInputs'] ['operationName'], getattr(e, 'Code'))