def infrastructure_destroy(name, version):
    try:
        infrastructures = service.infrastructure.search_instances(name, version)

        if len(infrastructures):
            infrastructure = infrastructures[0]

            for instance in infrastructure['cloudServers']:
                maccli.view.view_generic.showc("Instance %s marked as deleted" % instance['id'], GREEN)
                maccli.view.view_generic.show("")
                maccli.service.instance.destroy_instance(instance['id'])

            if len(infrastructure['cloudServers']):
                time.sleep(5)  # give some time to instances to free resources

            for resource in infrastructure['resources']:
                try:
                    maccli.facade.macfile.destroy_resource(resource, infrastructure['cloudServers'], infrastructure['resources'])
                except MacJsonException as e:
                    maccli.view.view_generic.showc("\nError while destroying resource %s\n\n" % resource['name'], RED)
                    maccli.view.view_generic.showc("Error while navigating json! %s\n" % e.message, RED)

        else:
            maccli.view.view_generic.show("Infrastructure '%s' version '%s' not found" % (name, version))

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            traceback.print_exc(file=sys.stdout)
        else:
            show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def instance_ssh(raw_ids, command):

    if raw_ids == ["all"]:  # run in all instances
        ids = service.instance.list_instances()
    else:
        ids = service.instance.list_instances(name_or_ids=raw_ids)

    try:
        # array for job list
        jobs = []

        for id in ids:
            if command is None:
                service.instance.ssh_interactive_instance(id['id'])
            else:
                # define and add job
                t = threading.Thread(target=_run_cmd_simple,args=(id["servername"], id["id"], command))
                jobs.append(t)

        for j in jobs:
            j.start()
        for j in jobs:
            j.join()

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def infrastructure_ssh_keys(name, version, known_host):
    """
    Diplays ssh keys or adds it to known_hosts

    :param name:
    :param version:
    :param known_host:
    :return:
    """
    try:
        ssh_keys = service.infrastructure.keys(name, version, known_host)
        if not maccli.quiet:
            if known_host:
                for ssh_key in ssh_keys:
                    show("%s processed" % ssh_key['cloudServer']['ipv4'])

            else:
                for ssh_key in ssh_keys:
                    show(ssh_key['stdout'])

    except KeyboardInterrupt:
       show_error("Aborting")
    except Exception as e:
       show_error(e)
       sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #4
0
def instance_update(raw_ids, cookbook_tag, bootstrap):
    try:
        if raw_ids == ["all"]:  # run in all instances
            ids = service.instance.list_instances()
        else:
            ids = service.instance.list_instances(name_or_ids=raw_ids)

        instances = []
        for id in ids:
            maccli.logger.debug("Updating instance %s " % id['id'])
            instance = service.instance.update_configuration(cookbook_tag, bootstrap, id['id'])
            instances.append(instance)

        if instances is not None:
            view.view_instance.show_instances(instances)

        view.view_generic.show("")
        view.view_generic.show("To track configuration changes")
        view.view_generic.show("")
        for id in ids:
            view.view_generic.show("    mac instance log -f %s" % id['id'])

        view.view_generic.show("")

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def instance_update(raw_ids, cookbook_tag, bootstrap):
    try:
        if raw_ids == ["all"]:  # run in all instances
            ids = service.instance.list_instances()
        else:
            ids = service.instance.list_instances(name_or_ids=raw_ids)

        instances = []
        for id in ids:
            maccli.logger.debug("Updating instance %s " % id['id'])
            instance = service.instance.update_configuration(cookbook_tag, bootstrap, id['id'])
            instances.append(instance)

        if instances is not None:
            view.view_instance.show_instances(instances)

        view.view_generic.show("")
        view.view_generic.show("To track configuration changes")
        view.view_generic.show("")
        for id in ids:
            view.view_generic.show("    mac instance log -f %s" % id['id'])

        view.view_generic.show("")

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #6
0
def infrastructure_update(name, version, cookbook_tag):
    try:
        infrastructures = service.infrastructure.search_instances(name, version)

        if len(infrastructures):
            infrastructure = infrastructures[0]

            instances = []
            for instance in infrastructure['cloudServers']:
                instance_updated = service.instance.update_configuration(cookbook_tag, "", instance['id'])
                instances.append(instance_updated)

            if instances is not None:
                view.view_instance.show_instances(instances)
        else:
            maccli.view.view_generic.show("Infrastructure '%s' version '%s' not found" % (name, version))

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            traceback.print_exc(file=sys.stdout)
        else:
            show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #7
0
def infrastructure_destroy(name, version):
    try:
        infrastructures = service.infrastructure.search_instances(name, version)

        if len(infrastructures):
            infrastructure = infrastructures[0]

            for instance in infrastructure['cloudServers']:
                maccli.view.view_generic.showc("Instance %s marked as deleted" % instance['id'], GREEN)
                maccli.view.view_generic.show("")
                maccli.service.instance.destroy_instance(instance['id'])

            if len(infrastructure['cloudServers']):
                time.sleep(5)  # give some time to instances to free resources

            for resource in infrastructure['resources']:
                try:
                    maccli.facade.macfile.destroy_resource(resource, infrastructure['cloudServers'], infrastructure['resources'])
                except MacJsonException as e:
                    maccli.view.view_generic.showc("\nError while destroying resource %s\n\n" % resource['name'], RED)
                    maccli.view.view_generic.showc("Error while navigating json! %s\n" % e.message, RED)

        else:
            maccli.view.view_generic.show("Infrastructure '%s' version '%s' not found" % (name, version))

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            traceback.print_exc(file=sys.stdout)
        else:
            show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #8
0
def infrastructure_ssh_keys(name, version, known_host):
    """
    Diplays ssh keys or adds it to known_hosts

    :param name:
    :param version:
    :param known_host:
    :return:
    """
    try:
        ssh_keys = service.infrastructure.keys(name, version, known_host)
        if not maccli.quiet:
            if known_host:
                for ssh_key in ssh_keys:
                    show("%s processed" % ssh_key['cloudServer']['ipv4'])

            else:
                for ssh_key in ssh_keys:
                    show(ssh_key['stdout'])

    except KeyboardInterrupt:
       show_error("Aborting")
    except Exception as e:
       show_error(e)
       sys.exit(EXCEPTION_EXIT_CODE)
def infrastructure_update(name, version, cookbook_tag):
    try:
        infrastructures = service.infrastructure.search_instances(name, version)

        if len(infrastructures):
            infrastructure = infrastructures[0]

            instances = []
            for instance in infrastructure['cloudServers']:
                instance_updated = service.instance.update_configuration(cookbook_tag, "", instance['id'])
                instances.append(instance_updated)

            if instances is not None:
                view.view_instance.show_instances(instances)
        else:
            maccli.view.view_generic.show("Infrastructure '%s' version '%s' not found" % (name, version))

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            traceback.print_exc(file=sys.stdout)
        else:
            show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #10
0
def instance_ssh(raw_ids, command):

    if raw_ids == ["all"]:  # run in all instances
        ids = service.instance.list_instances()
    else:
        ids = service.instance.list_instances(name_or_ids=raw_ids)

    try:
        # array for job list
        jobs = []

        for id in ids:
            if command is None:
                service.instance.ssh_interactive_instance(id['id'])
            else:
                # define and add job
                t = threading.Thread(target=_run_cmd_simple,args=(id["servername"], id["id"], command))
                jobs.append(t)

        for j in jobs:
            j.start()
        for j in jobs:
            j.join()

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def instance_list():
    try:
        json = service.instance.list_instances()
        view.view_instance.show_instances(json)

    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #12
0
def instance_list():
    try:
        json = service.instance.list_instances()
        view.view_instance.show_instances(json)

    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #13
0
def infrastructure_lifespan(amount, name, version):
    try:
        infrastructure = service.infrastructure.lifespan(amount, name, version)
        view.view_infrastructure.show_infrastructure_instances(infrastructure)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def configuration_list():
    try:
        configurations = service.configuration.list_configurations()
        view.view_cookbook.show_configurations(configurations)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def infrastructure_lifespan(amount, name, version):
    try:
        infrastructure = service.infrastructure.lifespan(amount, name, version)
        view.view_infrastructure.show_infrastructure_instances(infrastructure)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #16
0
def configuration_list():
    try:
        configurations = service.configuration.list_configurations()
        view.view_cookbook.show_configurations(configurations)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def instance_fact(instance_id):
    try:
        json = service.instance.facts(instance_id)
        view.view_instance.show_facts(json)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def infrastructure_list():
    try:
        infrastructure = service.infrastructure.list_infrastructure()
        view.view_infrastructure.show_infrastructure(infrastructure)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def instance_lifespan(instance_id, amount):
    try:
        instance = service.instance.lifespan(instance_id, amount)
        view.view_instance.show_instance(instance)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #20
0
def instance_fact(instance_id):
    try:
        json = service.instance.facts(instance_id)
        view.view_instance.show_facts(json)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #21
0
def infrastructure_list():
    try:
        infrastructure = service.infrastructure.list_infrastructure()
        view.view_infrastructure.show_infrastructure(infrastructure)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #22
0
def instance_lifespan(instance_id, amount):
    try:
        instance = service.instance.lifespan(instance_id, amount)
        view.view_instance.show_instance(instance)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #23
0
def instance_create(cookbook_tag, deployment, location, servername, provider, release, branch, hardware, lifespan,
                    environments, hd, port):
    try:
        if cookbook_tag is None:
            view.view_instance.show_instance_create_help()

        elif location is None:
            locations_json = service.provider.list_locations(cookbook_tag, provider, release)
            if locations_json is not None:
                show()
                show("--location parameter not set. You must choose the location.")
                show()
                show("Available locations:")
                show()
                if len(locations_json):
                    view.view_location.show_locations(locations_json)
                    view.view_instance.show_create_example_with_parameters(cookbook_tag, deployment,
                                                                           locations_json[0]['id'], servername,
                                                                           provider, release, branch, hardware)

                else:
                    show("There is not locations available for configuration %s and provider %s" % (
                        cookbook_tag, provider))

                view.view_instance.show_instance_help()
        elif deployment == "production" and hardware is None or \
                                        deployment == "testing" and provider is not "manageacloud" and hardware is None:
            hardwares = service.provider.list_hardwares(provider, location, cookbook_tag, release)
            show()
            show("--hardware not found. You must choose the hardware.")
            show()
            show("Available hardware:")
            show()
            view.view_hardware.show_hardwares(hardwares)
            if (len(hardwares) > 0):
                view.view_instance.show_create_example_with_parameters(cookbook_tag, deployment, location, servername,
                                                                       provider, release, branch, hardwares[0]['id'])
        else:
            """ Execute create instance """
            instance = service.instance.create_instance(cookbook_tag, deployment, location, servername, provider,
                                                        release,
                                                        branch, hardware, lifespan, environments, hd, port)
            if instance is not None:
                view.view_instance.show_instance(instance)

            view.view_generic.show("")
            view.view_generic.show("To monitor the creation progress:")
            view.view_generic.show("")
            view.view_generic.show("watch mac instance list")
            view.view_generic.show("")
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #24
0
def instance_ssh(instance_id, command):
    try:
        if command is None:
            service.instance.ssh_interactive_instance(instance_id)
        else:
            service.instance.ssh_command_instance(instance_id, command)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #25
0
def configuration_search(keywords, show_url):
    try:
        configurations = service.configuration.search_configurations(keywords)
        if show_url:
            view.view_cookbook.show_configurations_url(configurations)
        else:
            view.view_cookbook.show_configurations(configurations)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def configuration_search(keywords, show_url):
    try:
        configurations = service.configuration.search_configurations(keywords)
        if show_url:
            view.view_cookbook.show_configurations_url(configurations)
        else:
            view.view_cookbook.show_configurations(configurations)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def infrastructure_search(name, version):
    try:
        infrastructure = service.infrastructure.search_instances(name, version)
        if len(infrastructure):
            view.view_infrastructure.show_infrastructure_instances(infrastructure)
            view.view_generic.show()
            view.view_infrastructure.show_resources_in_infrastructure(infrastructure)
        else:
            view.view_generic.show("There are not active infrastructure")
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #28
0
def infrastructure_search(name, version):
    try:
        infrastructure = service.infrastructure.search_instances(name, version)
        if len(infrastructure):
            view.view_infrastructure.show_infrastructure_instances(infrastructure)
            view.view_generic.show()
            view.view_infrastructure.show_resources_in_infrastructure(infrastructure)
        else:
            view.view_generic.show("There are not active infrastructure")
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #29
0
def credentials(provider, clientid, key_raw, force_file):
    """
    Save the credential's supplier if are correct.

    :param provider:
    :param clientid:
    :param key_raw: This might be a path. If so, the credentials are stored in the file.
    :return:
    """
    try:
        service.provider.save_credentials(provider, clientid, key_raw, force_file)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def instance_destroy(ids):
    try:
        maccli.logger.debug("Destroying instances %s " % ids)
        instances = []
        for instance_id in ids:
            maccli.logger.debug("Destroying instance %s " % instance_id)
            instance = service.instance.destroy_instance(instance_id)
            instances.append(instance)

        if instances is not None:
            view.view_instance.show_instances(instances)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #31
0
def instance_destroy(ids):
    try:
        maccli.logger.debug("Destroying instances %s " % ids)
        instances = []
        for instance_id in ids:
            maccli.logger.debug("Destroying instance %s " % instance_id)
            instance = service.instance.destroy_instance(instance_id)
            instances.append(instance)

        if instances is not None:
            view.view_instance.show_instances(instances)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def credentials(provider, clientid, key_raw, force_file):
    """
    Save the credential's supplier if are correct.

    :param provider:
    :param clientid:
    :param key_raw: This might be a path. If so, the credentials are stored in the file.
    :return:
    """
    try:
        service.provider.save_credentials(provider, clientid, key_raw, force_file)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #33
0
def instance_log(instance_id, follow):
    try:
        if follow:
            while True:
                logs = maccli.service.instance.log(instance_id, follow)
                if logs == "":
                    time.sleep(5)
                else:
                    view.view_generic.show(logs)
                    time.sleep(1)
        else:
            json = service.instance.log(instance_id, False)
            view.view_instance.show_logs(json)

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def instance_log(instance_id, follow):
    try:
        if follow:
            while True:
                logs = maccli.service.instance.log(instance_id, follow)
                if logs == "":
                    time.sleep(5)
                else:
                    view.view_generic.show(logs)
                    time.sleep(1)
        else:
            json = service.instance.log(instance_id, False)
            view.view_instance.show_logs(json)

    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #35
0
def login():
    try:
        view.view_generic.show("")
        view.view_generic.show("If you are using Manageacloud SaaS and you don't have credentials, please register at https://manageacloud.com")
        view.view_generic.show("")
        view.view_generic.show("If you are using Manageacloud Community please set the following variable:")
        view.view_generic.show("    export MAC=http://my_community_server/api/v1/")
        view.view_generic.show("")
        view.view_generic.show("More information at http://manageacloud/docs/getting-started/install")
        view.view_generic.show("")
        username = raw_input("Username or email: ")
        password = getpass.getpass()

        user, api_key = service.auth.authenticate(username, password)
        if api_key is not None:
            config = ConfigParser.ConfigParser()
            config.add_section(AUTH_SECTION)
            config.set(AUTH_SECTION, USER_OPTION, user)
            config.set(AUTH_SECTION, APIKEY_OPTION, api_key)
            with open(join(expanduser('~'), MAC_FILE), 'w') as cfgfile:
                config.write(cfgfile)
            print("Login succeeded!")

    except KeyboardInterrupt as e:
        show_error("")
        show_error("Authentication cancelled.")

    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def login():
    try:
        view.view_generic.show("")
        view.view_generic.show("If you are using Manageacloud SaaS and you don't have credentials, please register at https://manageacloud.com")
        view.view_generic.show("")
        view.view_generic.show("If you are using Manageacloud Community please set the following variable:")
        view.view_generic.show("    export MAC=http://my_community_server/api/v1/")
        view.view_generic.show("")
        view.view_generic.show("More information at http://manageacloud/docs/getting-started/install")
        view.view_generic.show("")
        username = raw_input("Username or email: ")
        password = getpass.getpass()

        user, api_key = service.auth.authenticate(username, password)
        if api_key is not None:
            config = ConfigParser.ConfigParser()
            config.add_section(AUTH_SECTION)
            config.set(AUTH_SECTION, USER_OPTION, user)
            config.set(AUTH_SECTION, APIKEY_OPTION, api_key)
            with open(join(expanduser('~'), MAC_FILE), 'w') as cfgfile:
                config.write(cfgfile)
            print("Login succeeded!")

    except KeyboardInterrupt as e:
        show_error("")
        show_error("Authentication cancelled.")

    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
def resouce_get_stdout(infrastructure_name, infrastructure_version, resource_name, key):

    try:
        output = service.resource.get_resource_value(infrastructure_name, infrastructure_version, resource_name, key)
        if isinstance(output,basestring):
            sys.stdout.write(output)
        else:
            print(output)

    except KeyError:
        show_error("Key '%s' not found" % key)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #38
0
def resouce_get_stdout(infrastructure_name, infrastructure_version, resource_name, key):

    try:
        output = service.resource.get_resource_value(infrastructure_name, infrastructure_version, resource_name, key)
        if isinstance(output,basestring):
            sys.stdout.write(output)
        else:
            print(output)

    except KeyError:
        show_error("Key '%s' not found" % key)
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #39
0
def login():
    try:
        username = raw_input("Username or email: ")
        password = getpass.getpass()

        user, api_key = service.auth.authenticate(username, password)
        if api_key is not None:
            config = ConfigParser.ConfigParser()
            config.add_section(AUTH_SECTION)
            config.set(AUTH_SECTION, USER_OPTION, user)
            config.set(AUTH_SECTION, APIKEY_OPTION, api_key)
            with open(join(expanduser('~'), MAC_FILE), 'w') as cfgfile:
                config.write(cfgfile)
            print("Login succeeded!")

    except KeyboardInterrupt as e:
        show_error("")
        show_error("Authentication cancelled.")

    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
Beispiel #40
0
                else:
                    view.view_generic.show(infrastructure_error_detail)

                if 'cmd' in infrastructure_error_detail:
                    view.view_generic.show(infrastructure_error_detail['cmd'])

            # if an instance failed, the details of the error are in the log
            view.view_generic.show("")
            view.view_generic.show("Logs available at")
            view.view_generic.show("    mac instance log <instance id or name>")
            exit(12)
        else:
            view.view_generic.showc("Infrastructure created successfully.", GREEN)
            view.view_generic.show("")
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            traceback.print_exc(file=sys.stdout)
        else:
            show_error(e)

        sys.exit(EXCEPTION_EXIT_CODE)


def instance_fact(instance_id):
    try:
        json = service.instance.facts(instance_id)
        view.view_instance.show_facts(json)
    except KeyboardInterrupt:
        show_error("Aborting")
Beispiel #41
0
def instance_create(cookbook_tag, bootstrap_raw, deployment, location, servername, provider, release_raw, release_version_raw,
                    branch, hardware, lifespan, environments, hd, port, net):

    # allow format release:release_version, ie ubuntu:trusty
    if ":" in release_raw:
        release, release_version = release_raw.split(":", 1)
    else:
        release = release_raw
        release_version = release_version_raw


    # TODO check if cookbook_tag exists
    # TODO validate bootstrap inputs
    try:
        if cookbook_tag is None and bootstrap_raw is None:
            view.view_instance.show_instance_create_help()

        elif location is None:
            locations_json = service.provider.list_locations(provider, release)
            if locations_json is not None:
                show()
                show("--location parameter not set. You must choose the location.")
                show()
                show("Available locations:")
                show()
                if len(locations_json):
                    view.view_location.show_locations(locations_json)
                    view.view_instance.show_create_example_with_parameters(cookbook_tag, bootstrap_raw, deployment,
                                                                           locations_json[0]['id'], servername,
                                                                           provider, release, release_version,
                                                                           branch, hardware)

                else:
                    type = None
                    if release is not None:
                        type = release

                    if type is None and cookbook_tag is not None:
                        type = cookbook_tag

                    show("There is not locations available for '%s' and provider '%s'" % (type, provider))

                view.view_instance.show_instance_help()

        elif deployment == "production" and hardware is None or \
                                        deployment == "testing" and provider is not "default" and hardware is None:
            hardwares = service.provider.list_hardwares(provider, location, release)
            show()
            show("--hardware not found. You must choose the hardware.")
            show()
            show("Available hardware:")
            show()
            view.view_hardware.show_hardwares(hardwares)
            if (len(hardwares) > 0):
                view.view_instance.show_create_example_with_parameters(cookbook_tag, bootstrap_raw, deployment, location, servername,
                                                                       provider, release, release_version, branch, hardwares[0]['id'])
        else:
            """ Execute create instance """

            # load the bootstrap file properly
            if bootstrap_raw is not None:
                if os.path.exists(bootstrap_raw):  # it is a file
                    # this is going to be the PWD to run commands
                    maccli.pwd = os.path.dirname(os.path.realpath(bootstrap_raw))
                    maccli.logger.info("Path %s exists, trying to open file", bootstrap_raw)
                    stream = open(bootstrap_raw, "r")
                    bootstrap = stream.read()
                elif _is_url(bootstrap_raw):  # try url
                    maccli.logger.info("%s looks like an URL, trying to open URL" % bootstrap_raw)
                    f = urllib2.urlopen(bootstrap_raw)
                    bootstrap = f.read()
                else:  # values are bash executable
                    bootstrap = bootstrap_raw
            else:
                bootstrap = bootstrap_raw

            if cookbook_tag == "" and bootstrap == "":
                show_error("Server contains no configuration")
            else:
                instance = service.instance.create_instance(cookbook_tag, bootstrap, deployment, location,
                                                            servername, provider, release, release_version,
                                                            branch, hardware, lifespan, environments, hd, port, net)
                if instance is not None:
                    view.view_instance.show_instance(instance)

                view.view_generic.show("")
                view.view_generic.show("Monitor the progress of all servers:")
                view.view_generic.show("")
                view.view_generic.show("    watch mac instance list")
                view.view_generic.show("")
                view.view_generic.show("Tail server logs:")
                view.view_generic.show("")
                view.view_generic.show("    mac instance log -f %s" % instance['id'])
                view.view_generic.show("")
    except KeyboardInterrupt:
        show_error("Aborting")
    except URLError:
        show_error("Can't open URL %s" % bootstrap_raw)
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)
                else:
                    view.view_generic.show(infrastructure_error_detail)

                if 'cmd' in infrastructure_error_detail:
                    view.view_generic.show(infrastructure_error_detail['cmd'])

            # if an instance failed, the details of the error are in the log
            view.view_generic.show("")
            view.view_generic.show("Logs available at")
            view.view_generic.show("    mac instance log <instance id or name>")
            exit(12)
        else:
            view.view_generic.showc("Infrastructure created successfully.", GREEN)
            view.view_generic.show("")
    except KeyboardInterrupt:
        show_error("Aborting")
    except Exception as e:
        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            traceback.print_exc(file=sys.stdout)
        else:
            show_error(e)

        sys.exit(EXCEPTION_EXIT_CODE)


def instance_fact(instance_id):
    try:
        json = service.instance.facts(instance_id)
        view.view_instance.show_facts(json)
    except KeyboardInterrupt:
        show_error("Aborting")
def instance_create(cookbook_tag, bootstrap_raw, deployment, location, servername, provider, release_raw, release_version_raw,
                    branch, hardware, lifespan, environments, hd, port, net):

    # allow format release:release_version, ie ubuntu:trusty
    if ":" in release_raw:
        release, release_version = release_raw.split(":", 1)
    else:
        release = release_raw
        release_version = release_version_raw


    # TODO check if cookbook_tag exists
    # TODO validate bootstrap inputs
    try:
        if cookbook_tag is None and bootstrap_raw is None:
            view.view_instance.show_instance_create_help()

        elif location is None:
            locations_json = service.provider.list_locations(provider, release)
            if locations_json is not None:
                show()
                show("--location parameter not set. You must choose the location.")
                show()
                show("Available locations:")
                show()
                if len(locations_json):
                    view.view_location.show_locations(locations_json)
                    view.view_instance.show_create_example_with_parameters(cookbook_tag, bootstrap_raw, deployment,
                                                                           locations_json[0]['id'], servername,
                                                                           provider, release, release_version,
                                                                           branch, hardware)

                else:
                    type = None
                    if release is not None:
                        type = release

                    if type is None and cookbook_tag is not None:
                        type = cookbook_tag

                    show("There is not locations available for '%s' and provider '%s'" % (type, provider))

                view.view_instance.show_instance_help()

        elif deployment == "production" and hardware is None or \
                                        deployment == "testing" and provider is not "default" and hardware is None:
            hardwares = service.provider.list_hardwares(provider, location, release)
            show()
            show("--hardware not found. You must choose the hardware.")
            show()
            show("Available hardware:")
            show()
            view.view_hardware.show_hardwares(hardwares)
            if (len(hardwares) > 0):
                view.view_instance.show_create_example_with_parameters(cookbook_tag, bootstrap_raw, deployment, location, servername,
                                                                       provider, release, release_version, branch, hardwares[0]['id'])
        else:
            """ Execute create instance """

            # load the bootstrap file properly
            if bootstrap_raw is not None:
                if os.path.exists(bootstrap_raw):  # it is a file
                    # this is going to be the PWD to run commands
                    maccli.pwd = os.path.dirname(os.path.realpath(bootstrap_raw))
                    maccli.logger.info("Path %s exists, trying to open file", bootstrap_raw)
                    stream = open(bootstrap_raw, "r")
                    bootstrap = stream.read()
                elif _is_url(bootstrap_raw):  # try url
                    maccli.logger.info("%s looks like an URL, trying to open URL" % bootstrap_raw)
                    f = urllib2.urlopen(bootstrap_raw)
                    bootstrap = f.read()
                else:  # values are bash executable
                    bootstrap = bootstrap_raw
            else:
                bootstrap = bootstrap_raw

            if cookbook_tag == "" and bootstrap == "":
                show_error("Server contains no configuration")
            else:
                instance = service.instance.create_instance(cookbook_tag, bootstrap, deployment, location,
                                                            servername, provider, release, release_version,
                                                            branch, hardware, lifespan, environments, hd, port, net)
                if instance is not None:
                    view.view_instance.show_instance(instance)

                view.view_generic.show("")
                view.view_generic.show("Monitor the progress of all servers:")
                view.view_generic.show("")
                view.view_generic.show("    watch mac instance list")
                view.view_generic.show("")
                view.view_generic.show("Tail server logs:")
                view.view_generic.show("")
                view.view_generic.show("    mac instance log -f %s" % instance['id'])
                view.view_generic.show("")
    except KeyboardInterrupt:
        show_error("Aborting")
    except URLError:
        show_error("Can't open URL %s" % bootstrap_raw)
    except Exception as e:
        show_error(e)
        sys.exit(EXCEPTION_EXIT_CODE)