def register(options):
    """Registers the machine against the automation agent service.

    Args:
        options : dict, the options dictionary
    """
    registration_endpoint = options.registration_endpoint
    automation_account_key = options.automation_account_key
    hybrid_worker_group_name = options.hybrid_worker_group_name
    workspace_id = options.workspace_id

    # assert workspace exists on the box
    state_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/state/"
    working_directory_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/run/"
    if os.path.exists(state_base_path) is False or os.path.exists(working_directory_base_path) is False:
        raise Exception("Invalid workspace id. Is the specified workspace id registered as the OMSAgent "
                        "primary worksapce?")

    diy_account_id = extract_account_id_from_registration_endpoint(registration_endpoint)
    auto_registered_account_id = get_autoregistered_worker_account_id()
    if auto_registered_account_id != None and auto_registered_account_id != diy_account_id:
        raise Exception("Cannot register, conflicting worker already registered.")

    diy_state_base_path = os.path.join(state_base_path, os.path.join("automationworker", "diy"))
    diy_working_directory_base_path = os.path.join(working_directory_base_path, os.path.join("automationworker", "diy"))
    worker_conf_path = os.path.join(diy_state_base_path, "worker.conf")

    if os.path.isfile(worker_conf_path) is True:
        raise Exception("Unable to register, an existing worker was found. Please deregister any existing worker and "
                        "try again.")

    certificate_path = os.path.join(diy_state_base_path, "worker_diy.crt")
    key_path = os.path.join(diy_state_base_path, "worker_diy.key")
    machine_id = util.generate_uuid()

    # generate state path (certs/conf will be dropped in this path)
    if os.path.isdir(diy_state_base_path) is False:
        os.makedirs(diy_state_base_path)
    generate_self_signed_certificate(certificate_path=certificate_path, key_path=key_path)
    issuer, subject, thumbprint = linuxutil.get_cert_info(certificate_path)

    # try to extract optional metadata
    unknown = "Unknown"
    asset_tag = unknown
    vm_id = unknown
    is_azure_vm = False
    try:
        dmidecode = invoke_dmidecode()
        is_azure_vm = linuxutil.is_azure_vm(dmidecode)
        if is_azure_vm:
            asset_tag = linuxutil.get_azure_vm_asset_tag()
        else:
            asset_tag = False
        vm_id = linuxutil.get_vm_unique_id_from_dmidecode(sys.byteorder, dmidecode)
    except Exception, e:
        print str(e)
        pass
def register(options):
    """Registers the machine against the automation agent service.

    Args:
        options : dict, the options dictionary
    """
    registration_endpoint = options.registration_endpoint
    automation_account_key = options.automation_account_key
    hybrid_worker_group_name = options.hybrid_worker_group_name
    workspace_id = options.workspace_id

    # assert workspace exists on the box
    state_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/state/"
    working_directory_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/run/"
    if os.path.exists(state_base_path) is False or os.path.exists(working_directory_base_path) is False:
        raise Exception("Invalid workspace id. Is the specified workspace id registered as the OMSAgent "
                        "primary worksapce?")

    diy_account_id = extract_account_id_from_registration_endpoint(registration_endpoint)
    auto_registered_account_id = get_autoregistered_worker_account_id()
    if auto_registered_account_id != None and auto_registered_account_id != diy_account_id:
        raise Exception("Cannot register, conflicting worker already registered.")


    worker_conf_path = os.path.join(DIY_STATE_PATH, "worker.conf")

    if os.path.isfile(worker_conf_path) is True:
        raise Exception("Unable to register, an existing worker was found. Please deregister any existing worker and "
                        "try again.")

    certificate_path = os.path.join(DIY_STATE_PATH, "worker_diy.crt")
    key_path = os.path.join(DIY_STATE_PATH, "worker_diy.key")
    machine_id = util.generate_uuid()

    # generate state path (certs/conf will be dropped in this path)
    if os.path.isdir(DIY_STATE_PATH) is False:
        os.makedirs(DIY_STATE_PATH)
    generate_self_signed_certificate(certificate_path=certificate_path, key_path=key_path)
    issuer, subject, thumbprint = linuxutil.get_cert_info(certificate_path)

    # try to extract optional metadata
    unknown = "Unknown"
    asset_tag = unknown
    vm_id = unknown
    is_azure_vm = False
    try:
        dmidecode = invoke_dmidecode()
        is_azure_vm = linuxutil.is_azure_vm(dmidecode)
        if is_azure_vm:
            asset_tag = linuxutil.get_azure_vm_asset_tag()
        else:
            asset_tag = False
        vm_id = linuxutil.get_vm_unique_id_from_dmidecode(sys.byteorder, dmidecode)
    except Exception, e:
        print str(e)
        pass
Example #3
0
def register(options):
    environment_prerequisite_validation()
    """Registers the machine against the automation agent service.

    Args:
        options : dict, the options dictionary
    """
    registration_endpoint = options.registration_endpoint
    automation_account_key = options.automation_account_key
    hybrid_worker_group_name = options.hybrid_worker_group_name
    workspace_id = options.workspace_id

    # assert workspace exists on the box
    state_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/state/"
    working_directory_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/run/"
    if os.path.exists(state_base_path) is False or os.path.exists(working_directory_base_path) is False:
        raise Exception("Invalid workspace id. Is the specified workspace id registered as the OMSAgent "
                        "primary worksapce?")

    diy_account_id = extract_account_id_from_registration_endpoint(registration_endpoint)
    auto_registered_account_id = get_autoregistered_worker_account_id()
    if auto_registered_account_id != None and auto_registered_account_id != diy_account_id:
        raise Exception("Cannot register, conflicting worker already registered.")


    worker_conf_path = os.path.join(DIY_STATE_PATH, "worker.conf")

    if os.path.isfile(worker_conf_path) is True:
        raise Exception("Unable to register, an existing worker was found. Please deregister any existing worker and "
                        "try again.")

    certificate_path = os.path.join(DIY_STATE_PATH, "worker_diy.crt")
    key_path = os.path.join(DIY_STATE_PATH, "worker_diy.key")
    machine_id = util.generate_uuid()

    # generate state path (certs/conf will be dropped in this path)
    if os.path.isdir(DIY_STATE_PATH) is False:
        try:
            os.makedirs(DIY_STATE_PATH)
        except Exception, ex:            
            print("Registration unsuccessful.")
            print("Cannot create directory for certs/conf. Because of the following exception : " + str(ex))
            return
Example #4
0
def register(options):
    environment_prerequisite_validation()
    """Registers the machine against the automation agent service.

    Args:
        options : dict, the options dictionary
    """
    registration_endpoint = options.registration_endpoint
    automation_account_key = options.automation_account_key
    hybrid_worker_group_name = options.hybrid_worker_group_name
    workspace_id = options.workspace_id

    # assert workspace exists on the box
    state_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/state/"
    working_directory_base_path = "/var/opt/microsoft/omsagent/" + workspace_id + "/run/"
    if os.path.exists(state_base_path) is False or os.path.exists(
            working_directory_base_path) is False:
        raise Exception(
            "Invalid workspace id. Is the specified workspace id registered as the OMSAgent "
            "primary worksapce?")

    diy_account_id = extract_account_id_from_registration_endpoint(
        registration_endpoint)
    auto_registered_account_id = get_autoregistered_worker_account_id()
    if auto_registered_account_id != None and auto_registered_account_id != diy_account_id:
        raise Exception(
            "Cannot register, conflicting worker already registered.")

    worker_conf_path = os.path.join(DIY_STATE_PATH, "worker.conf")

    if os.path.isfile(worker_conf_path) is True:
        raise Exception(
            "Unable to register, an existing worker was found. Please deregister any existing worker and "
            "try again.")

    certificate_path = os.path.join(DIY_STATE_PATH, "worker_diy.crt")
    key_path = os.path.join(DIY_STATE_PATH, "worker_diy.key")
    machine_id = util.generate_uuid()

    # generate state path (certs/conf will be dropped in this path)
    if os.path.isdir(DIY_STATE_PATH) is False:
        try:
            os.makedirs(DIY_STATE_PATH)
        except Exception as ex:
            print("Registration unsuccessful.")
            print(
                "Cannot create directory for certs/conf. Because of the following exception : "
                + str(ex))
            return
    generate_self_signed_certificate(certificate_path=certificate_path,
                                     key_path=key_path)
    issuer, subject, thumbprint = linuxutil.get_cert_info(certificate_path)

    # try to extract optional metadata
    unknown = "Unknown"
    asset_tag = unknown
    vm_id = unknown
    is_azure_vm = False
    try:
        dmidecode = invoke_dmidecode()
        is_azure_vm = linuxutil.is_azure_vm(dmidecode)
        if is_azure_vm:
            asset_tag = linuxutil.get_azure_vm_asset_tag()
        else:
            asset_tag = False
        vm_id = linuxutil.get_vm_unique_id_from_dmidecode(
            sys.byteorder, dmidecode)
    except Exception as e:
        print(str(e))
        pass

    # generate payload for registration request
    date = datetime.datetime.utcnow().isoformat() + "0-00:00"
    payload = {
        'RunbookWorkerGroup': hybrid_worker_group_name,
        "MachineName": socket.gethostname().split(".")[0],
        "IpAddress": get_ip_address(),
        "Thumbprint": thumbprint,
        "Issuer": issuer,
        "OperatingSystem": 2,
        "SMBIOSAssetTag": asset_tag,
        "VirtualMachineId": vm_id,
        "Subject": subject
    }

    # the signature generation is based on agent service contract
    payload_hash = sha256_digest(payload)
    b64encoded_payload_hash = base64.b64encode(payload_hash)
    signature = generate_hmac(
        b64encoded_payload_hash.decode("utf-8") + "\n" + date,
        automation_account_key)
    b64encoded_signature = base64.b64encode(signature)

    headers = {
        'Authorization': 'Shared ' + b64encoded_signature.decode("utf-8"),
        'ProtocolVersion': "2.0",
        'x-ms-date': date,
        "Content-Type": "application/json"
    }
    is_conf_file_writable = check_if_conf_file_can_be_written()

    if is_conf_file_writable:
        # agent service registration request
        http_client_factory = httpclientfactory.HttpClientFactory(
            certificate_path, key_path, options.test)
        http_client = http_client_factory.create_http_client(sys.version_info)
        url = registration_endpoint + "/HybridV2(MachineId='" + machine_id + "')"
        response = http_client.put(url, headers=headers, data=payload)
        if response.status_code != 200:
            raise Exception("Failed to register worker. [response_status=" +
                            str(response.status_code) + "]")

        response.raw_data = response.raw_data.decode() if isinstance(
            response.raw_data, bytes) else response.raw_data
        registration_response = json.loads(response.raw_data)
        account_id = registration_response["AccountId"]
        create_worker_configuration_file(
            registration_response["jobRuntimeDataServiceUri"], account_id,
            hybrid_worker_group_name, machine_id, DIY_WORKING_DIR,
            DIY_STATE_PATH, certificate_path, key_path, registration_endpoint,
            workspace_id, thumbprint, vm_id, is_azure_vm, options.gpg_keyring,
            options.test)

        # generate working directory path
        diydirs.create_persistent_diy_dirs()

        print("Registration successful!")
    else:
        print(
            "Registration cannot be completed because configuration file could not be written. Please check the file permissions for /home/nxautomation folder"
        )