Example #1
0
File: sell.py Project: shayanb/two1
def stop(ctx, services, all, stop_vm, delete_vm):
    """
Stop selling a containerized service.

\b
Stop selling a single service.
$ 21 sell stop <service_name>

\b
Stop selling all services.
$ 21 sell stop --all
"""

    if len(services) == 0 and all is False and stop_vm is False and delete_vm is False:
        logger.info(ctx.command.get_help(ctx))
        sys.exit()

    # pass Two1SellSell_Client down in context
    manager = ctx.obj['manager']

    if all:
        valid_services = manager.get_all_services_list()
    else:
        valid_services = services

    if manager.status_machine() == VmState.NOEXIST:
        if isinstance(manager.machine, Two1MachineVirtual):
            cli_helpers.print_str("Virtual machine", ["Does not exist"], "TRUE", True)
            sys.exit()
        else:
            if stop_vm or delete_vm:
                logger.info(click.style("Your services are running natively: "
                                        "run 21 sell stop --all to stop services", fg="magenta"))
                sys.exit()

            services_status = manager.status_services(valid_services, 1)
            running_exists = False
            for service in services_status:
                if (services_status[service]["status"].lower() == "running" or
                        services_status[service]["status"].lower() == "unable to contact"):
                    running_exists = True
                    break
            if running_exists:
                stop_stats = cli_helpers.start_long_running("Stopping services",
                                                            manager.stop_services,
                                                            valid_services)
                formatted_stats = cli_helpers.stop_dict_to_list(stop_stats)
                cli_helpers.service_status_check(formatted_stats)
            else:
                cli_helpers.print_str("Services", ["None found running"], "TRUE", True)

    if manager.status_machine() == VmState.STOPPED:
        if stop_vm:
            cli_helpers.print_str("Virtual machine", ["Stopped"], "TRUE", True)
            sys.exit()
        if delete_vm:
            if not isinstance(manager.machine, Two1MachineVirtual):
                logger.info(click.style("There are no VMs to stop or delete: "
                                        "your services are running natively", fg="magenta"))
                sys.exit()
            try:
                cli_helpers.start_long_running("Deleting virtual machine",
                                               manager.delete_machine)
                cli_helpers.print_str("Virtual machine", ["Deleted"], "TRUE", True)
            except Two1MachineDeleteException:
                cli_helpers.print_str("Virtual machine", ["Failed to delete"], "FALSE", False)

    if manager.status_machine() == VmState.RUNNING:
        services_status = manager.status_services(valid_services, 1)
        running_exists = False
        for service in services_status:
            if (services_status[service]["status"].lower() == "running" or
                    services_status[service]["status"].lower() == "unable to contact"):
                running_exists = True
                break
        if running_exists:
            stop_stats = cli_helpers.start_long_running("Stopping services",
                                                        manager.stop_services,
                                                        valid_services)
            formatted_stats = cli_helpers.stop_dict_to_list(stop_stats)
            cli_helpers.service_status_check(formatted_stats)
        else:
            if not stop_vm and not delete_vm:
                cli_helpers.print_str("Services", ["None found running"], "TRUE", True)

        if stop_vm or delete_vm:
            try:
                cli_helpers.start_long_running("Stopping virtual machine",
                                               manager.stop_machine)
                cli_helpers.print_str("Virtual machine", ["Stopped"], "TRUE", True)
            except Two1MachineStopException:
                cli_helpers.print_str("Virtual machine", ["Failed to stop"], "FALSE", False)
                sys.exit()

            if delete_vm:
                try:
                    cli_helpers.start_long_running("Deleting virtual machine",
                                                   manager.delete_machine)
                    cli_helpers.print_str("Virtual machine", ["Deleted"], "TRUE", True)
                except Two1MachineDeleteException:
                    cli_helpers.print_str("Virtual machine", ["Failed to delete"], "FALSE", False)
                    sys.exit()
Example #2
0
File: sell.py Project: shayanb/two1
def start(ctx, services, all, wait_time, no_vm):
    """
Start selling a containerized service.

\b
Start selling a single service.
$ 21 sell start <service_name>

\b
Start selling all available services.
$ 21 sell start --all
"""

    # display help command if no args
    if len(services) == 0 and all is False:
        logger.info(ctx.command.get_help(ctx))
        sys.exit()

    # no-vm version coming soon
    if no_vm:
        logger.info(click.style("This mode is not yet supported.", fg="magenta"))
        sys.exit()

    # assign manager and installer from context
    manager = ctx.obj['manager']
    installer = ctx.obj['installer']

    logger.info(click.style("Checking dependencies...", fg=cli_helpers.TITLE_COLOR))
    deps_list = installer.check_dependencies()
    all_deps_installed = cli_helpers.package_check(deps_list, True)

    # install virtualbox, docker, and zerotier deps
    if not all_deps_installed:
        if click.confirm(click.style("Would you like to install the missing packages?",
                                     fg=cli_helpers.PROMPT_COLOR)):
            logger.info(click.style("Installing missing dependencies...", fg=cli_helpers.TITLE_COLOR))
            all_installed = cli_helpers.install_missing_dependencies(deps_list,
                                                                     installer)
            if not all_installed:
                sys.exit()
        else:
            sys.exit()

    # pick up docker group permissions by force logout (via user prompt)
    if cli_helpers.check_needs_logout(installer):
        sys.exit()

    # connect to zerotier virtual network
    if not manager.status_networking():
        if click.confirm(click.style(
                "ZeroTier One virtual network service is not running. Would you like to start "
                "the service?", fg=cli_helpers.PROMPT_COLOR)):
            try:
                manager.start_networking()
                cli_helpers.print_str("ZeroTier One", ["Started"], "TRUE", True)
            except Two1MachineNetworkStartException:
                cli_helpers.print_str("ZeroTier One", ["Not started"], "FALSE", False)
        else:
            sys.exit()

    # join the 21market network
    if manager.get_market_address() == "":
        if click.confirm(click.style(
                "21market network not connected. Would you like to join 21market?", fg=cli_helpers.PROMPT_COLOR)):
            logger.info("You might need to enter your superuser password.")
            manager.connect_market(ctx.obj['client'])
            if manager.get_market_address() == "":
                cli_helpers.print_str("21market", ["Joined"], "TRUE", True)
            else:
                cli_helpers.print_str("21market", ["Unable to join"], "FALSE", False)
        else:
            sys.exit()
    else:
        cli_helpers.print_str("21market", ["Joined"], "TRUE", True)

    if isinstance(manager.machine, Two1MachineVirtual):
        logger.info(click.style("Checking virtual machine status...", fg=cli_helpers.TITLE_COLOR))
        just_started = False
        vm_status = manager.status_machine()
        if vm_status == VmState.NOEXIST:
            if click.confirm(click.style("  21 virtual machine does not exist. "
                                         "Would you like to create it?",
                                         fg=cli_helpers.PROMPT_COLOR)):
                vm_config = cli_helpers.get_vm_options()
                try:
                    cli_helpers.start_long_running("Creating machine (this may take a few minutes)",
                                                   manager.create_machine,
                                                   "21",
                                                   vm_config.disk_size,
                                                   vm_config.vm_memory,
                                                   vm_config.server_port,
                                                   vm_config.network_interface)
                    cli_helpers.write_machine_config(vm_config._asdict())
                    cli_helpers.print_str("21 virtual machine", ["Created"], "TRUE", True)

                except Two1MachineCreateException:
                    cli_helpers.print_str("21 virtual machine", ["Not created"], "FALSE", False)

                vm_status = manager.status_machine()
            else:
                sys.exit()

        if vm_status != VmState.RUNNING:
            if not manager.status_networking():
                if click.confirm(click.style(
                        "ZeroTier One virtual network service is not running. "
                        "Would you like to start the service?", fg=cli_helpers.PROMPT_COLOR)):
                    try:
                        manager.start_networking()
                        cli_helpers.print_str("ZeroTier One", ["Started"], "TRUE", True)
                    except Two1MachineNetworkStartException:
                        cli_helpers.print_str("ZeroTier One", ["Not started"], "FALSE", False)
                else:
                    sys.exit()
            try:
                cli_helpers.start_long_running("Starting machine (this may take a few minutes)",
                                               manager.start_machine)
                just_started = True
            except Two1MachineStartException:
                cli_helpers.print_str("21 virtual machine", ["Not started"], "FALSE", False)
                sys.exit()
            vm_status = manager.status_machine()

        # check if machine running
        if vm_status == VmState.RUNNING:
            if just_started:
                cli_helpers.print_str("21 virtual machine", ["Started"], "TRUE", True)
            else:
                cli_helpers.print_str("21 virtual machine", ["Running"], "TRUE", True)
        else:
            sys.exit()
    else:
        server_port = cli_helpers.get_server_port()
        cli_helpers.write_machine_config({"server_port": server_port})

    # write user credentials info to environment file
    username, pw = cli_helpers.get_user_credentials()
    status_env = manager.write_global_services_env(username, pw)

    # build service images
    try:
        payment_wallet = cli_helpers.start_long_running("Building base services (this may take a few minutes)",
                                                        manager.build_base_services)
    except:
        cli_helpers.print_str("Services", ["Not built"], "FALSE", False)
        sys.exit()
    else:
        cli_helpers.print_str("Services", ["Built"], "TRUE", True)

    if payment_wallet["created"]:
        logger.info(click.style("A wallet has been generated for the payment container,\nplease write down its wallet mnemonic and store it in a safe place:\n"
                                "    {}".format(payment_wallet['mnemonic']), fg="magenta"))
        click.pause()

    if all:
        valid_services = manager.get_all_services_list()
    else:
        valid_services = services

    # build service images
    try:
        wallets_dict = cli_helpers.start_long_running("Building market services (this may take a few minutes)",
                                                      manager.build_market_services,
                                                      valid_services)
    except:
        cli_helpers.print_str("Services", ["Not built"], "FALSE", False)
        sys.exit()
    else:
        cli_helpers.print_str("Services", ["Built"], "TRUE", True)

    for service, wallet_template in wallets_dict.items():
        if wallet_template["created"]:
            logger.info(click.style("A wallet has been generated for the service \"{}\",\nplease write down its wallet mnemonic and store it in a safe place:\n"
                                    "    {}".format(service, wallet_template['mnemonic']), fg="magenta"))
            click.pause()

    # start container services
    start_stats = cli_helpers.start_long_running("Starting services (this may take a few minutes)",
                                                 manager.start_services,
                                                 valid_services)
    formatted_stats = cli_helpers.start_dict_to_list(start_stats)
    cli_helpers.service_status_check(formatted_stats, False)
    published_stats = cli_helpers.prompt_to_publish(formatted_stats, manager)
    for stat in published_stats:
        cli_helpers.print_str(stat[0],
                              stat[2],
                              "TRUE" if stat[1] else "FALSE",
                              stat[1])
    # help tip message
    logger.info(click.style("\nTip: run ", fg=cli_helpers.PROMPT_COLOR) +
                click.style("`21 sell status --detail`", bold=True, fg=cli_helpers.PROMPT_COLOR) +
                click.style(" to see your microservice balances.", fg=cli_helpers.PROMPT_COLOR))