Example #1
0
def setup(host, port):
    servers = []

    for p in port:
        # Create a TCP/IP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Bind the socket to the port
        server_address = (host, int(p))
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        click.echo('starting up on {} port {}'.format(*server_address))
        sock.bind(server_address)
        sock.listen(1)

        servers.append(sock)

    while True:
        # Wait for a connection
        click.echo('waiting for a connections')
        readable, _, _ = select.select(servers, [], [])
        ready_server = readable[0]
        while True:
            connection, client_address = sock.accept()
            thread.start_new_thread(on_new_client,
                                    (connection, client_address))

    sock.close()
Example #2
0
 def format_reboot_output(self, result, vm_id):
     if result:
         click.echo("VM %s is rebooting" % vm_id)
     else:
         click.echo(
             "VM %s was unable to reboot (you can try with --force)" %
             vm_id,
             err=True)
Example #3
0
 def format_shutdown_output(self, result, vm_id):
     if result:
         click.echo("VM %s is shutting down" % vm_id)
     else:
         click.echo(
             "VM %s was unable to shut down (you can try with --force)" %
             vm_id,
             err=True)
Example #4
0
def list_templates():
    from management_api import ManagementApi
    mgmt_api = ManagementApi(host)

    result = mgmt_api.list_registry()
    from formatter import Formatter
    formatter = Formatter()
    click.echo(formatter.format_list_of_dicts(result))
Example #5
0
def set_host_variable():
    global host
    host_path = os.path.join(os.path.dirname(__file__), 'host')
    if not os.path.exists(host_path):
        click.echo("Please define a host")
        exit(-1)
    with open(host_path) as f:
        host = f.read().rstrip()
    validate_host(host)
Example #6
0
def terminate_vm(vm_id):
    from management_api import ManagementApi
    mgmt_api = ManagementApi(host)
    result = mgmt_api.terminate_vm(vm_id)
    if result:
        click.echo("\nterminating...\n")
        ctx = click.get_current_context()
        ctx.invoke(show_vm, vm_id=vm_id)
    else:
        click.echo("\nunable to terminate %s\n" % vm_id)
Example #7
0
def show_node(node_id):
    from management_api import ManagementApi
    from management_api import NotFoundException
    mgmt_api = ManagementApi(host)
    try:
        result = mgmt_api.show_node(node_id)
    except NotFoundException:
        click.echo("no such node")
        exit(-1)
    from formatter import Formatter
    formatter = Formatter()
    click.echo(formatter.format_list_of_dicts(result))
Example #8
0
def start_vm(template_id, tag, count, node):
    from management_api import ManagementApi
    from management_api import NotFoundException
    mgmt_api = ManagementApi(host)
    new_ids = None
    try:
        new_ids = mgmt_api.start_vm(template_id, count, tag=tag, node=node)
    except NotFoundException:
        template_id_from_list = mgmt_api.search_template_by_name(template_id)
        if template_id_from_list:
            new_ids = mgmt_api.start_vm(template_id_from_list,
                                        count,
                                        tag=tag,
                                        node=node)
        else:
            click.echo("Template not found")
            exit(-1)
    if new_ids:
        click.echo("\nvms created")
        vms_created = []
        for new_id in new_ids:
            vm_info = mgmt_api.show_vm(new_id)
            info_to_show = {
                'id': new_id,
                'state': vm_info.get('instance_state')
            }
            vms_created.append(info_to_show)
        from formatter import Formatter
        formatter = Formatter()
        click.echo(formatter.format_list_of_dicts(vms_created))
    else:
        click.echo("\ncreate failed")
Example #9
0
def on_new_client(clientsocket, client_address):
    try:
        click.echo("Connection from {} established".format(client_address[0]))
        clientsocket.send(
            'Send "quit" to close the connection\nClient: '.encode())
        while True:
            data = clientsocket.recv(1024)
            if data.decode().lower().rstrip() == 'quit':
                click.echo(
                    'Request to close connection received from {}, closing now'
                    .format(client_address[0]))
                response = "Received quit signal, goodbye!\n"
                clientsocket.send(response.encode())
                break
            elif data:
                click.echo("{}: {}".format(client_address[0],
                                           data.decode().rstrip()))
                response = "Server: {}\nClient: ".format(
                    data.decode().rstrip())
                clientsocket.send(response.encode())
            else:
                click.echo("No data from {}, closing connection".format(
                    client_address[0]))
                break

    finally:
        # Clean up the connection
        clientsocket.close()
Example #10
0
def export(ctx, vm_id, output_file, fmt, silent):
    try:
        if ctx.obj.machine_readable:
            veertu_manager.export_vm(vm_id,
                                     output_file,
                                     fmt=fmt,
                                     silent=silent)
            return
        if os.path.isfile(output_file):
            click.confirm('File exists, do you want to overwrite?',
                          default=False,
                          abort=True)

        handle = veertu_manager.export_vm(vm_id,
                                          output_file,
                                          fmt=fmt,
                                          silent=silent,
                                          do_progress_loop=False)
        if not handle:
            return click.echo('could not export vm')
        if fmt == 'vmz':
            length = 100
        else:
            length = 200
        _do_import_export_progress_bar(handle, length)
    except ImportExportFailedException:
        raise ImportExportFailedException("export failed")
Example #11
0
def import_vm(ctx, input_file, os_family, os_type, name, fmt, n):
    if n:
        suggested_name = _try_guess_name(input_file)
        return click.echo('Suggested VM name "%s"' % suggested_name)
    try:
        if ctx.obj.machine_readable:
            silent = True
            success = veertu_manager.import_vm(input_file,
                                               name,
                                               os_family,
                                               os_type,
                                               fmt,
                                               silent=silent,
                                               do_progress_loop=True)
            return cli_formatter.echo_status_ok(
            ) if success else cli_formatter.echo_status_failure()
        else:
            handle = veertu_manager.import_vm(input_file,
                                              name,
                                              os_family,
                                              os_type,
                                              fmt,
                                              do_progress_loop=False)
            if not handle:
                return cli_formatter.echo_status_failure(
                    message='could not import vm')
            _do_import_export_progress_bar(handle, 100)
    except ImportExportFailedException:
        raise ImportExportFailedException(
            "Veertu failed to import %s, "
            "please check file type and try again" % input_file)
Example #12
0
 def format_properties_changed(self, succeeded, failed):
     if succeeded:
         click.echo("the following properties were set successfully:")
         for k, v in succeeded.iteritems():
             click.echo("{} set to {}".format(k, str(v)))
     if failed:
         click.echo('the following properties failed to set:')
         for k, v in failed.iteritems():
             click.echo("{} to {}".format(k, str(v)))
Example #13
0
def show(ctx, vm_id, state, ip_address, port_forwarding):
    vm_info = veertu_manager.show(vm_id)
    if state:
        click.echo(vm_info.get('status'))
    if ip_address:
        click.echo(vm_info.get('ip'))
    if port_forwarding:
        cli_formatter.format_port_forwarding_info(
            vm_info.get('port_forwarding', []))
    if any([state, ip_address, port_forwarding]):
        return
    if vm_info.get('status',
                   False) != 'running' and not ctx.obj.machine_readable:
        keep_keys = ['id', 'name', 'status']
        for k, v in vm_info.iteritems():
            if k not in keep_keys:
                del vm_info[k]
    cli_formatter.format_show_output(vm_info)
Example #14
0
 def format_start_output(self, result, restart=False, vm_id=None):
     if result:
         if restart:
             click.echo("VM %s successfully restarted" % vm_id)
         else:
             click.echo("VM %s successfully started" % vm_id)
     else:
         if restart:
             click.echo("VM %s failed to restart" % vm_id, err=True)
         else:
             click.echo("VM %s failed to start" % vm_id, err=True)
Example #15
0
def list_vms():
    from management_api import ManagementApi
    mgmt_api = ManagementApi(host)
    list_of_vms = mgmt_api.list()
    click.echo("\nvms:\n")
    from formatter import Formatter
    formatter = Formatter()
    click.echo(formatter.format_list_of_dicts(list_of_vms))
    click.echo("\n")
Example #16
0
def show_vm(vm_id):
    from management_api import ManagementApi
    from management_api import NotFoundException
    mgmt_api = ManagementApi(host)
    try:
        vm = mgmt_api.show_vm(vm_id)
    except NotFoundException:
        click.echo("vm not found")
        exit(-1)
    click.echo("\nshowing vm %s\n" % vm_id)
    from formatter import Formatter
    formatter = Formatter()
    click.echo(formatter.format_dict(vm))
Example #17
0
 def echo_status_ok(self, message=''):
     click.echo('OK')
     if message:
         click.echo(message)
Example #18
0
 def format_add_network_card(self, success):
     if success:
         click.echo('successfully added network card')
     else:
         click.echo('could not add network card')
Example #19
0
 def format_delete_output(self, result, vm_id):
     if result:
         click.echo("VM %s deleted successfully" % vm_id)
     else:
         click.echo("Unable to delete VM %s " % vm_id, err=True)
Example #20
0
 def format_describe(self, vm_dict):
     click.echo(self.format_dict(vm_dict))
Example #21
0
 def format_deleted_port_forwarding_rule(self, result):
     if result:
         click.echo('rule deleted successfully')
     else:
         click.echo('could not delete port forwarding', err=True)
Example #22
0
 def echo_status_failure(self, message=''):
     click.echo('Action Failed')
     if message:
         click.echo(message)
Example #23
0
def set_host(host_string):
    validate_host(host_string)
    with open(os.path.join(os.path.dirname(__file__), 'host'), 'w') as f:
        f.write(host_string)
    click.echo("set host to %s" % host_string)
Example #24
0
 def format_delete_network_card(self, success):
     if success:
         click.echo('successfully deleted network card')
     else:
         click.echo('could not delete network card')
Example #25
0
def show_host():
    set_host_variable()
    click.echo(host)
Example #26
0
 def format_list_output(self, vms_list):
     click.echo('list of vms:')
     output = self.format_list_of_dicts(vms_list)
     click.echo(output)
Example #27
0
def validate_host(host_str):
    url_regex = 'http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    import re
    if not re.match(url_regex, host_str):
        click.echo("Host string should be a valid url")
        exit(-1)
Example #28
0
 def format_show_output(self, vm_info):
     output = self.format_dict(vm_info)
     click.echo(output)
Example #29
0
 def format_create(self, success):
     if success:
         click.echo('vm created successfully new uuid: %s' % success)
     else:
         click.echo('could not create vm')
Example #30
0
 def format_vm_not_exist(self):
     click.echo('vm does not exist')