def wait_for_completion(op_uri, timeout, allowed_states,
                        complete_states, config):
    module = config.module
    client = config.client(get_region(module), "vpc", "project")

    def _refresh_status():
        r = None
        try:
            r = fetch_resource(module, client, op_uri)
        except Exception:
            return None, ""

        status = ""
        try:
            status = navigate_value(r, ['vpc', 'status'])
        except Exception:
            return None, ""

        return r, status

    try:
        return wait_to_finish(complete_states, allowed_states,
                              _refresh_status, timeout)
    except Exception as ex:
        module.fail_json(msg=str(ex))
def get_resource_id(config):
    module = config.module
    client = config.client(get_region(module), "smn", "project")

    link = "notifications/topics"
    query_link = "?offset={offset}&limit=10"
    link += query_link

    p = {'offset': 0}
    v = module.params.get('name')
    ids = set()
    while True:
        r = None
        try:
            r = client.get(link.format(**p))
        except Exception:
            pass
        if r is None:
            break
        r = r.get('topics', [])
        if r == []:
            break
        for i in r:
            if i.get('name') == v:
                ids.add(i.get('topic_urn'))
        if len(ids) >= 2:
            module.fail_json(msg="Multiple resources are found")

        p['offset'] += 1

    return ids.pop() if ids else None
def main():
    """Main function"""

    module = HwcModule(
        argument_spec=dict(state=dict(default='present',
                                      choices=['present', 'absent'],
                                      type='str'),
                           display_name=dict(type='str'),
                           name=dict(required=True, type='str')),
        supports_check_mode=True,
    )

    config = Config(module, "smn")

    state = module.params['state']

    if not module.params.get("id"):
        module.params['id'] = get_resource_id(config)

    fetch = None
    link = self_link(module)
    # the link will include Nones if required format parameters are missed
    if not re.search('/None/|/None$', link):
        client = config.client(get_region(module), "smn", "project")
        fetch = fetch_resource(module, client, link)
    changed = False

    if fetch:
        if state == 'present':
            expect = _get_resource_editable_properties(module)
            current_state = response_to_hash(module, fetch)
            current = {'display_name': current_state['display_name']}
            if are_different_dicts(expect, current):
                if not module.check_mode:
                    fetch = update(config)
                    fetch = response_to_hash(module, fetch)
                changed = True
            else:
                fetch = current_state
        else:
            if not module.check_mode:
                delete(config)
                fetch = {}
            changed = True
    else:
        if state == 'present':
            if not module.check_mode:
                fetch = create(config)
                fetch = response_to_hash(module, fetch)
            changed = True
        else:
            fetch = {}

    fetch.update({'changed': changed})

    module.exit_json(**fetch)
def get_id_by_name(config):
    module = config.module
    client = config.client(get_region(module), "vpc", "project")
    name = module.params.get("name")
    link = "vpcs"
    query_link = "?marker={marker}&limit=10"
    link += query_link
    not_format_keys = re.findall("={marker}", link)
    none_values = re.findall("=None", link)

    if not (not_format_keys or none_values):
        r = None
        try:
            r = client.get(link)
        except Exception:
            pass
        if r is None:
            return None
        r = r.get('vpcs', [])
        ids = [
            i.get('id') for i in r if i.get('name', '') == name
        ]
        if not ids:
            return None
        elif len(ids) == 1:
            return ids[0]
        else:
            module.fail_json(
                msg="Multiple resources with same name are found.")
    elif none_values:
        module.fail_json(
            msg="Can not find id by name because url includes None.")
    else:
        p = {'marker': ''}
        ids = set()
        while True:
            r = None
            try:
                r = client.get(link.format(**p))
            except Exception:
                pass
            if r is None:
                break
            r = r.get('vpcs', [])
            if r == []:
                break
            for i in r:
                if i.get('name') == name:
                    ids.add(i.get('id'))
            if len(ids) >= 2:
                module.fail_json(
                    msg="Multiple resources with same name are found.")

            p['marker'] = r[-1].get('id')

        return ids.pop() if ids else None
def delete(config):
    module = config.module
    client = config.client(get_region(module), "smn", "project")

    link = self_link(module)
    try:
        client.delete(link)
    except HwcClientException as ex:
        msg = ("module(jctanner.cloud_huawei.hwc_smn_topic): error deleting "
               "resource, error: %s" % str(ex))
        module.fail_json(msg=msg)
def delete(config, link):
    module = config.module
    client = config.client(get_region(module), "vpc", "project")

    try:
        client.delete(link)
    except HwcClientException as ex:
        msg = ("module(jctanner.cloud_huawei.hwc_network_vpc): error deleting "
               "resource, error: %s" % str(ex))
        module.fail_json(msg=msg)

    wait_for_delete(module, client, link)
def update(config):
    module = config.module
    client = config.client(get_region(module), "smn", "project")

    link = self_link(module)
    try:
        client.put(link, update_resource_opts(module))
    except HwcClientException as ex:
        msg = ("module(jctanner.cloud_huawei.hwc_smn_topic): error updating "
               "resource, error: %s" % str(ex))
        module.fail_json(msg=msg)

    return fetch_resource(module, client, link)
def get_resource(config, result):
    module = config.module
    client = config.client(get_region(module), "smn", "project")

    v = ""
    try:
        v = navigate_value(result, ['topic_urn'])
    except Exception as ex:
        module.fail_json(msg=str(ex))

    d = {'topic_urn': v}
    url = build_path(module, 'notifications/topics/{topic_urn}', d)

    return fetch_resource(module, client, url)
def create(config):
    module = config.module
    client = config.client(get_region(module), "smn", "project")

    link = "notifications/topics"
    r = None
    try:
        r = client.post(link, create_resource_opts(module))
    except HwcClientException as ex:
        msg = ("module(jctanner.cloud_huawei.hwc_smn_topic): error creating "
               "resource, error: %s" % str(ex))
        module.fail_json(msg=msg)

    return get_resource(config, r)
def update(config, link):
    module = config.module
    client = config.client(get_region(module), "vpc", "project")

    r = None
    try:
        r = client.put(link, resource_to_update(module))
    except HwcClientException as ex:
        msg = ("module(jctanner.cloud_huawei.hwc_network_vpc): error updating "
               "resource, error: %s" % str(ex))
        module.fail_json(msg=msg)

    wait_for_operation(config, 'update', r)

    return fetch_resource(module, client, link)
def create(config, link):
    module = config.module
    client = config.client(get_region(module), "vpc", "project")

    r = None
    try:
        r = client.post(link, resource_to_create(module))
    except HwcClientException as ex:
        msg = ("module(jctanner.cloud_huawei.hwc_network_vpc): error creating "
               "resource, error: %s" % str(ex))
        module.fail_json(msg=msg)

    wait_done = wait_for_operation(config, 'create', r)
    v = ""
    try:
        v = navigate_value(wait_done, ['vpc', 'id'])
    except Exception as ex:
        module.fail_json(msg=str(ex))

    url = build_path(module, 'vpcs/{op_id}', {'op_id': v})
    return fetch_resource(module, client, url)