Example #1
0
def _list_deployments(cmd_proc, scoreclient):
    try:
        deployments = scoreclient.deployments.list()
        print_deployments(deployments)
    except exceptions.ClientException as e:
        utils.print_message('No deployments found. Reason %s.' %
                            str(e), cmd_proc)
Example #2
0
def user(cmd_proc, operation, username, user_id, password, new_password,
         first_name, last_name, roles, token):
    """Operations with Users"""
    if cmd_proc.vca.service_type != VCA.VCA_SERVICE_TYPE_VCA:
        utils.print_message('Operation not supported '
                            'in this service type')
        sys.exit(1)
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    try:
        if 'list' == operation:
            headers = ['User Name', 'First', 'Last', 'Email', 'State', 'Id',
                       'Roles']
            table = []
            for u in cmd_proc.vca.get_users():
                roles = []
                for r in u.get('roles').get('roles'):
                    roles.append(str(r.get('name')))
                table.append([u.get('userName'), u.get('givenName'),
                              u.get('familyName'), u.get('email'),
                              u.get('state'),
                              u.get('id'),
                              utils.beautified(roles)])
            sorted_table = sorted(table, key=operator.itemgetter(0),
                                  reverse=False)
            utils.print_table("Available users in instance '%s'"
                              ", profile '%s':" %
                              (cmd_proc.instance, cmd_proc.profile),
                              headers, sorted_table,
                              cmd_proc)
        elif 'info' == operation:
            cmd_proc.error_message = 'not implemented'
            sys.exit(1)
        elif 'create' == operation:
            roles_array = roles.split(',')
            result = cmd_proc.vca.add_user(username, first_name,
                                           last_name, roles_array)
            utils.print_message("User '%s' successfully created" % username)
        elif 'delete' == operation:
            result = cmd_proc.vca.del_user(user_id)
            utils.print_message("Successfully deleted user '%s'" %
                                cmd_proc.vca.username)
        elif 'change-password' == operation:
            result = cmd_proc.vca.change_password(password, new_password)
            utils.print_message("Successfully changed password for user '%s'"
                                % cmd_proc.vca.username)
        elif 'validate' == operation:
            result = cmd_proc.vca.validate_user(username, password, token)
            print result
        elif 'reset-password' == operation:
            result = cmd_proc.vca.reset_password(user_id)
            utils.print_message("Successfully reset password for user id"
                                "'%s', check email to enter new password"
                                % user_id)
    except:
        utils.print_error('An error has ocurred', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()
Example #3
0
def _validate(cmd_proc, operation,
              blueprint_id, blueprint_file,
              include_plan, scoreclient):
    try:
        scoreclient.blueprints.validate(blueprint_file)
        utils.print_message("The blueprint is valid.", cmd_proc)
    except MissingRequiredInputError as mrie:
        utils.print_error('Invalid blueprint: ' +
                          str(mrie)[str(mrie).rfind('}') + 1:].
                          strip())
    except UnknownInputError as uie:
        utils.print_error('Invalid blueprint: ' +
                          str(uie)[str(uie).rfind('}') + 1:].
                          strip())
    except FunctionEvaluationError as fee:
        utils.print_error('Invalid blueprint: ' +
                          str(fee)[str(fee).rfind('}') + 1:].
                          strip())
    except DSLParsingException as dpe:
        utils.print_error('Invalid blueprint: ' +
                          str(dpe)[str(dpe).rfind('}') + 1:].
                          strip())
    except Exception as ex:
        utils.print_error('Failed to validate %s:\n %s' %
                          (blueprint_file, str(ex)))
Example #4
0
def role(cmd_proc, operation):
    """Operations with Roles"""
    if cmd_proc.vca.service_type != VCA.VCA_SERVICE_TYPE_VCA:
        utils.print_message('Operation not supported ' 'in this service type')
        sys.exit(1)
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['Role Name', 'Description', 'Permissions']
        table = []
        for r in cmd_proc.vca.get_roles():
            permissions = []
            if len(r.get('rights')) > 0:
                for p in r.get('rigths'):
                    permissions.append(str(p.get('name')))
            table.append([
                r.get('name'),
                r.get('description'),
                utils.beautified(permissions)
            ])
        sorted_table = sorted(table, key=operator.itemgetter(0), reverse=False)
        utils.print_table(
            "Available roles in instance '%s'"
            ", profile '%s':" % (cmd_proc.instance, cmd_proc.profile), headers,
            sorted_table, cmd_proc)
    cmd_proc.save_current_config()
Example #5
0
def role(cmd_proc, operation):
    """Operations with Roles"""
    if cmd_proc.vca.service_type != VCA.VCA_SERVICE_TYPE_VCA:
        utils.print_message('Operation not supported '
                            'in this service type')
        sys.exit(1)
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['Role Name', 'Description', 'Permissions']
        table = []
        for r in cmd_proc.vca.get_roles():
            permissions = []
            if len(r.get('rights')) > 0:
                for p in r.get('rigths'):
                    permissions.append(str(p.get('name')))
            table.append([r.get('name'),
                          r.get('description'),
                          utils.beautified(permissions)])
        sorted_table = sorted(table, key=operator.itemgetter(0), reverse=False)
        utils.print_table("Available roles in instance '%s'"
                          ", profile '%s':" %
                          (cmd_proc.instance, cmd_proc.profile),
                          headers, sorted_table,
                          cmd_proc)
    cmd_proc.save_current_config()
Example #6
0
def _delete_blueprint(cmd_proc, blueprint_id, scoreclient):
    try:
        scoreclient.blueprints.delete(blueprint_id)
        utils.print_message("successfully deleted blueprint '%s'" %
                            blueprint_id, cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to delete blueprint. Reason: %s." %
                          str(e), cmd_proc)
Example #7
0
def _upload(cmd_proc, blueprint, blueprint_file, scoreclient):
    try:
        b = scoreclient.blueprints.upload(blueprint_file, blueprint)
        utils.print_message("Successfully uploaded blueprint '%s'." %
                            b.get('id'), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to upload blueprint. Reason: %s." %
                          str(e), cmd_proc)
Example #8
0
def _upload(cmd_proc, operation, blueprint_id, blueprint_file, include_plan, scoreclient):
    try:
        b = scoreclient.blueprints.upload(blueprint_file, blueprint_id)
        utils.print_message("Successfully uploaded blueprint '%s'." % b.get("id"), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error(
            "Failed to upload blueprint. Reason: {0}, {1}".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #9
0
def _delete_blueprint(cmd_proc, operation, blueprint_id, blueprint_file, include_plan, scoreclient):
    try:
        scoreclient.blueprints.delete(blueprint_id)
        utils.print_message("successfully deleted blueprint '%s'" % blueprint_id, cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error(
            "Failed to delete blueprint. Reason: {0}, {1}".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #10
0
def _validate(cmd_proc, operation,
              blueprint_id, blueprint_file,
              include_plan, scoreclient):
    try:
        scoreclient.blueprints.validate(blueprint_file)
        utils.print_message("The blueprint is valid.", cmd_proc)
    except Exception as ex:
        utils.print_error('Failed to validate %s:\n %s' %
                          (blueprint_file, str(ex)))
Example #11
0
def _delete_deployment(cmd_proc, scoreclient,
                       deployment_to_delete, force_delete):
    try:
        scoreclient.deployments.delete(deployment_to_delete,
                                       force_delete=force_delete)
        utils.print_message("successfully deleted deployment '%s'" %
                            deployment_to_delete, cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to delete deployment. Reason: %s." %
                          str(e), cmd_proc)
Example #12
0
def _delete_blueprint(cmd_proc, operation,
                      blueprint_id, blueprint_file,
                      include_plan, scoreclient):
    try:
        scoreclient.blueprints.delete(blueprint_id)
        utils.print_message("successfully deleted blueprint '%s'" %
                            blueprint_id, cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to delete blueprint. Reason: {0}, {1}"
                          .format(str(e), scoreclient.response.content),
                          cmd_proc)
Example #13
0
def _upload(cmd_proc, operation,
            blueprint_id, blueprint_file,
            include_plan, scoreclient):
    try:
        b = scoreclient.blueprints.upload(blueprint_file, blueprint_id)
        utils.print_message("Successfully uploaded blueprint '%s'." %
                            b.get('id'), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to upload blueprint. Reason: {0}, {1}"
                          .format(str(e), scoreclient.response.content),
                          cmd_proc)
Example #14
0
def _list_deployments(cmd_proc, operation, deployment_id, blueprint_id,
                      input_file, workflow, show_events, execution_id,
                      force_cancel, force_delete, scoreclient):

    try:
        deployments = scoreclient.deployments.list()
        print_deployments(deployments)
    except exceptions.ClientException as e:
        utils.print_message('No deployments found. Reason {0}, {1}'
                            .format(str(e),
                                    scoreclient.response.content),
                            cmd_proc)
Example #15
0
def _delete_deployment(cmd_proc, operation, deployment_id, blueprint_id,
                       input_file, workflow, show_events, execution_id,
                       force_cancel, force_delete, scoreclient):
    try:
        scoreclient.deployments.delete(deployment_id,
                                       force_delete=force_delete)
        utils.print_message("successfully deleted deployment '{0}'"
                            .format(deployment_id), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to delete deployment. Reason: {0}, {1}"
                          .format(str(e), scoreclient.response.content),
                          cmd_proc)
Example #16
0
def _create_deployment(cmd_proc, blueprint, deployment, input_file,
                       scoreclient):
    try:
        inputs = None
        if input_file:
            inputs = yaml.load(input_file)
        scoreclient.deployments.create(blueprint, deployment, inputs)
        utils.print_message("Successfully created deployment '%s'." %
                            deployment, cmd_proc)
    except exceptions.ClientException as e:
            utils.print_error("Failed to create deployment. Reason: %s" %
                              str(e), cmd_proc)
Example #17
0
def disk(cmd_proc, operation, vdc, disk_name, disk_size, disk_id):
    """Operations with Independent Disks"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if vdc is None:
        vdc = cmd_proc.vdc_name
    the_vdc = cmd_proc.vca.get_vdc(vdc)
    if the_vdc is None:
        utils.print_error("VDC not found '%s'" % vdc, cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['Disk', 'Size GB', 'Id', 'Owner']
        disks = cmd_proc.vca.get_disks(vdc)
        table = cmd_proc.disks_to_table(disks)
        if cmd_proc.json_output:
            json_object = {'disks':
                           utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table("Available independent disks in '%s'"
                              ", profile '%s':" %
                              (vdc, cmd_proc.profile),
                              headers, table, cmd_proc)
    elif 'create' == operation:
        assert disk_name, "Disk name can't be empty"
        size = disk_size * cmd_proc.DISK_SIZE
        result = cmd_proc.vca.add_disk(vdc, disk_name, size)
        if result and len(result) > 0:
            if result[0]:
                utils.print_message('disk %s successfully created'
                                    % disk_name, cmd_proc)
            else:
                utils.print_error('disk %s could not be created'
                                  % disk_name, cmd_proc)
    elif 'delete' == operation:
        result = cmd_proc.vca.delete_disk(vdc, disk_name, disk_id)
        if result and len(result) > 0:
            if result[0]:
                utils.print_message('disk %s successfully deleted'
                                    % (disk_id if disk_id else disk_name),
                                    cmd_proc)
            else:
                utils.print_error('disk %s could not be deleted: %s'
                                  % (disk_name, result[1]),
                                  cmd_proc)
                sys.exit(1)
    else:
        utils.print_error('not implemented', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()
Example #18
0
def disk(cmd_proc, operation, vdc, disk_name, disk_size, disk_id):
    """Operations with Independent Disks"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if vdc is None:
        vdc = cmd_proc.vdc_name
    the_vdc = cmd_proc.vca.get_vdc(vdc)
    if the_vdc is None:
        utils.print_error("VDC not found '%s'" % vdc, cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['Disk', 'Size GB', 'Id', 'Owner']
        disks = cmd_proc.vca.get_disks(vdc)
        table = cmd_proc.disks_to_table(disks)
        if cmd_proc.json_output:
            json_object = {'disks': utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table(
                "Available independent disks in '%s'"
                ", profile '%s':" % (vdc, cmd_proc.profile), headers, table,
                cmd_proc)
    elif 'create' == operation:
        assert disk_name, "Disk name can't be empty"
        size = disk_size * cmd_proc.DISK_SIZE
        result = cmd_proc.vca.add_disk(vdc, disk_name, size)
        if result and len(result) > 0:
            if result[0]:
                utils.print_message('disk %s successfully created' % disk_name,
                                    cmd_proc)
            else:
                utils.print_error('disk %s could not be created' % disk_name,
                                  cmd_proc)
    elif 'delete' == operation:
        result = cmd_proc.vca.delete_disk(vdc, disk_name, disk_id)
        if result and len(result) > 0:
            if result[0]:
                utils.print_message(
                    'disk %s successfully deleted' %
                    (disk_id if disk_id else disk_name), cmd_proc)
            else:
                utils.print_error(
                    'disk %s could not be deleted: %s' %
                    (disk_name, result[1]), cmd_proc)
                sys.exit(1)
    else:
        utils.print_error('not implemented', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()
Example #19
0
def _validate(cmd_proc, operation, blueprint_id, blueprint_file, include_plan, scoreclient):
    try:
        scoreclient.blueprints.validate(blueprint_file)
        utils.print_message("The blueprint is valid.", cmd_proc)
    except MissingRequiredInputError as mrie:
        utils.print_error("Invalid blueprint: " + str(mrie)[str(mrie).rfind("}") + 1 :].strip())
    except UnknownInputError as uie:
        utils.print_error("Invalid blueprint: " + str(uie)[str(uie).rfind("}") + 1 :].strip())
    except FunctionEvaluationError as fee:
        utils.print_error("Invalid blueprint: " + str(fee)[str(fee).rfind("}") + 1 :].strip())
    except DSLParsingException as dpe:
        utils.print_error("Invalid blueprint: " + str(dpe)[str(dpe).rfind("}") + 1 :].strip())
    except Exception as ex:
        utils.print_error("Failed to validate %s:\n %s" % (blueprint_file, str(ex)))
Example #20
0
def _list_blueprints(cmd_proc, operation, blueprint_id, blueprint_file, include_plan, scoreclient):
    try:
        blueprints = scoreclient.blueprints.list()
        headers = ["Id", "Created"]
        table = cmd_proc.blueprints_to_table(blueprints)
        if cmd_proc.json_output:
            json_object = {"blueprints": utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table("Available blueprints, profile '%s':" % cmd_proc.profile, headers, table, cmd_proc)
    except exceptions.ClientException as e:
        utils.print_message(
            "Unable to list blueprints. Reason {0}, {1}".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #21
0
def event(cmd_proc, operation, execution_id, from_event, batch_size, show_logs):
    """Operations with Blueprint Events"""
    scoreclient = _authorize(cmd_proc)

    if "list" == operation:
        try:
            events = scoreclient.events.get(
                execution_id, from_event=from_event, batch_size=batch_size, include_logs=show_logs
            )
            print_events(events)
            utils.print_message("Total events: {}".format(events[-1]), cmd_proc)
        except exceptions.ClientException as e:
            utils.print_error(
                "Can't find events for execution: {0}. " "Reason: {1}.".format(execution_id, str(e)), cmd_proc
            )
Example #22
0
def _create_deployment(cmd_proc, operation, deployment_id, blueprint_id,
                       input_file, workflow, show_events, execution_id,
                       force_cancel, force_delete,
                       scoreclient):
    try:
        inputs = None
        if input_file:
            inputs = yaml.load(input_file)
        scoreclient.deployments.create(blueprint_id, deployment_id, inputs)
        utils.print_message("Successfully created deployment '{0}'.".format(
            deployment_id), cmd_proc)
    except exceptions.ClientException as e:
            utils.print_error("Failed to create deployment. Reason: {0}, {1}"
                              .format(str(e), scoreclient.response.content),
                              cmd_proc)
Example #23
0
def _list_blueprints(cmd_proc, scoreclient):
    try:
        blueprints = scoreclient.blueprints.list()
        headers = ['Id', 'Created']
        table = cmd_proc.blueprints_to_table(blueprints)
        if cmd_proc.json_output:
            json_object = {'blueprints':
                           utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table("Available blueprints, profile '%s':" %
                              cmd_proc.profile,
                              headers, table, cmd_proc)
    except exceptions.ClientException as e:
        utils.print_message('Unable to list blueprints. Reason %s.' %
                            str(e), cmd_proc)
Example #24
0
def firewall(cmd_proc, operation, vdc, gateway):
    """Operations with Edge Gateway Firewall Service"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if vdc is None:
        vdc = cmd_proc.vdc_name
    the_vdc = cmd_proc.vca.get_vdc(vdc)
    if the_vdc is None:
        utils.print_error("VDC not found '%s'" % vdc, cmd_proc)
        sys.exit(1)
    if gateway is None:
        gateway = cmd_proc.gateway
    the_gateway = cmd_proc.vca.get_gateway(vdc, gateway)
    if the_gateway is None:
        utils.print_error("gateway not found '%s'" % gateway, cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = [
            'Source IP', 'Source Port', 'Destination IP', 'Destination Port',
            'Protocol', 'Enabled'
        ]
        table = cmd_proc.firewall_rules_to_table(the_gateway)
        if cmd_proc.json_output:
            json_object = {'fw-rules': utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table(
                "Firewall rules in gateway '%s', "
                "VDC '%s', profile '%s':" % (gateway, vdc, cmd_proc.profile),
                headers, table, cmd_proc)
    elif 'enable' == operation or 'disable' == operation:
        utils.print_message("%s firewall" % operation)
        the_gateway.enable_fw('enable' == operation)
        task = the_gateway.save_services_configuration()
        if task:
            utils.display_progress(
                task, cmd_proc,
                cmd_proc.vca.vcloud_session.get_vcloud_headers())
        else:
            error = parseString(the_gateway.response.content, True)
            utils.print_error(
                "can't '%s' the firewall: " % operation + error.get_message(),
                cmd_proc)
            sys.exit(1)
    cmd_proc.save_current_config()
Example #25
0
def firewall(cmd_proc, operation, vdc, gateway):
    """Operations with Edge Gateway Firewall Service"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if vdc is None:
        vdc = cmd_proc.vdc_name
    the_vdc = cmd_proc.vca.get_vdc(vdc)
    if the_vdc is None:
        utils.print_error("VDC not found '%s'" % vdc, cmd_proc)
        sys.exit(1)
    if gateway is None:
        gateway = cmd_proc.gateway
    the_gateway = cmd_proc.vca.get_gateway(vdc, gateway)
    if the_gateway is None:
        utils.print_error("gateway not found '%s'" % gateway, cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['Source IP', 'Source Port', 'Destination IP',
                   'Destination Port', 'Protocol', 'Enabled']
        table = cmd_proc.firewall_rules_to_table(the_gateway)
        if cmd_proc.json_output:
            json_object = {'fw-rules':
                           utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table("Firewall rules in gateway '%s', "
                              "VDC '%s', profile '%s':" %
                              (gateway, vdc, cmd_proc.profile),
                              headers, table, cmd_proc)
    elif 'enable' == operation or 'disable' == operation:
        utils.print_message("%s firewall" % operation)
        the_gateway.enable_fw('enable' == operation)
        task = the_gateway.save_services_configuration()
        if task:
            utils.display_progress(task,
                                   cmd_proc,
                                   cmd_proc.vca.vcloud_session.
                                   get_vcloud_headers())
        else:
            error = parseString(the_gateway.response.content, True)
            utils.print_error("can't '%s' the firewall: " % operation +
                              error.get_message(), cmd_proc)
            sys.exit(1)
    cmd_proc.save_current_config()
Example #26
0
def _list_blueprints(cmd_proc, operation, blueprint_id,
                     blueprint_file, include_plan, scoreclient):
    try:
        blueprints = scoreclient.blueprints.list()
        headers = ['Id', 'Created']
        table = cmd_proc.blueprints_to_table(blueprints)
        if cmd_proc.json_output:
            json_object = {'blueprints':
                           utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table("Available blueprints, profile '%s':" %
                              cmd_proc.profile,
                              headers, table, cmd_proc)
    except exceptions.ClientException as e:
        utils.print_message('Unable to list blueprints. Reason {0}, {1}'
                            .format(str(e), scoreclient.response.content),
                            cmd_proc)
Example #27
0
def event(cmd_proc, operation, execution, from_event, batch_size, show_logs):
    """Operations with Blueprint Events"""
    scoreclient = _authorize(cmd_proc)

    if 'list' == operation:
        try:
            events = scoreclient.events.get(execution, from_event=from_event,
                                            batch_size=batch_size,
                                            include_logs=show_logs)
            print_table("Status:", 'status', events[0].keys(),
                        [e.values() for e in events[:-1]], None)
            utils.print_message("Total events: {}".format(events[-1]),
                                cmd_proc)
        except exceptions.ClientException as e:
                utils.print_error("Can't find events for execution: {0}. "
                                  "Reason: {1}.".
                                  format(execution, str(e)),
                                  cmd_proc)
Example #28
0
def print_execution(execution, ctx=None):
    if execution:
        headers = ['Workflow', 'Created', 'Status', 'Message']
        table = []
        table.append([
            execution.get('workflow_id'),
            execution.get('created_at')[:-7],
            execution.get('status'),
            execution.get('error')])
        sorted_table = sorted(table,
                              key=operator.itemgetter(1),
                              reverse=False)
        print_table(
            "Workflow execution '%s' for deployment '%s'"
            % (execution.get('id'), execution.get('deployment_id')),
            'execution', headers, sorted_table, ctx)
    else:
        utils.print_message("No execution", ctx)
Example #29
0
def event(cmd_proc, operation, execution_id, from_event, batch_size,
          show_logs):
    """Operations with Blueprint Events"""
    scoreclient = _authorize(cmd_proc)

    if 'list' == operation:
        try:
            events = scoreclient.events.get(execution_id,
                                            from_event=from_event,
                                            batch_size=batch_size,
                                            include_logs=show_logs)
            print_events(events)
            utils.print_message("Total events: {}".format(events[-1]),
                                cmd_proc)
        except exceptions.ClientException as e:
                utils.print_error("Can't find events for execution: {0}. "
                                  "Reason: {1}.".
                                  format(execution_id, str(e)),
                                  cmd_proc)
Example #30
0
def _cancel(cmd_proc, execution, force_cancel, scoreclient):
    if not execution:
        utils.print_error("execution id is not specified")
        return
    try:
        e = scoreclient.executions.cancel(execution, force_cancel)
        print_execution(e, None) if e else utils.print_message(
            str(scoreclient.response.content), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to cancel workflow. Reasons: {0}."
                          .format(str(e)), cmd_proc)
Example #31
0
def _delete_deployment(
    cmd_proc,
    operation,
    deployment_id,
    blueprint_id,
    input_file,
    workflow,
    show_events,
    execution_id,
    force_cancel,
    force_delete,
    scoreclient,
):
    try:
        scoreclient.deployments.delete(deployment_id, force_delete=force_delete)
        utils.print_message("successfully deleted deployment '{0}'".format(deployment_id), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error(
            "Failed to delete deployment. Reason: {0}, {1}".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #32
0
def print_deployment_info(deployment, executions, events, execution_id,
                          ctx=None):
    headers = ['Blueprint Id', 'Deployment Id', 'Created', 'Workflows']
    table = []
    workflows = []
    for workflow in deployment.get('workflows'):
        workflows.append(workflow.get('name').encode('utf-8'))
    table.append(
        [deployment.get('blueprint_id'), deployment.get('id'),
         deployment.get('created_at')[:-7], utils.beautified(workflows)])
    print_table("Deployment information:\n-----------------------",
                'deployment',
                headers, table, ctx)
    print("\n")
    headers = ['Workflow', 'Created', 'Status', 'Execution Id']
    table = []
    if executions is None or len(executions) == 0:
        utils.print_message('no executions found', ctx)
        return
    for e in executions:
        table.append([e.get('workflow_id'),
                      e.get('created_at')[:-7],
                      e.get('status'), e.get('id')])
    sorted_table = sorted(table, key=operator.itemgetter(1), reverse=False)
    print_table("Workflow executions for deployment: '%s'"
                "\n----------------------------------"
                % deployment.get('id'), 'executions', headers, sorted_table,
                ctx)
    if events:
        headers = ['Type', 'Started', 'Message']
        table = []
        for event in events:
            if isinstance(
                    event, collections.Iterable) and 'event_type' in event:
                table.append(
                    [event.get('event_type'), event.get('timestamp')[:-9],
                     event.get('message').get('text')])
        print('\n')
        print_table("Events for execution id '%s'" %
                    execution_id, 'events',
                    headers, table, ctx)
Example #33
0
def _list_deployments(
    cmd_proc,
    operation,
    deployment_id,
    blueprint_id,
    input_file,
    workflow,
    show_events,
    execution_id,
    force_cancel,
    force_delete,
    scoreclient,
):

    try:
        deployments = scoreclient.deployments.list()
        print_deployments(deployments)
    except exceptions.ClientException as e:
        utils.print_message(
            "No deployments found. Reason {0}, {1}".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #34
0
def print_deployment_info(deployment, executions, events, ctx=None):
    headers = ['Blueprint Id', 'Deployment Id', 'Created', 'Workflows']
    table = []
    workflows = []
    for workflow in deployment.get('workflows'):
        workflows.append(workflow.get('name').encode('utf-8'))
    table.append(
        [deployment.get('blueprint_id'), deployment.get('id'),
         deployment.get('created_at')[:-7], utils.beautified(workflows)])
    print_table("Deployment information:\n-----------------------",
                'deployment',
                headers, table, ctx)
    print("\n")
    headers = ['Workflow', 'Created', 'Status', 'Id']
    table = []
    if executions is None or len(executions) == 0:
        utils.print_message('no executions found', ctx)
        return
    for e in executions:
        table.append([e.get('workflow_id'),
                      e.get('created_at')[:-7],
                      e.get('status'), e.get('id')])
    sorted_table = sorted(table, key=operator.itemgetter(1), reverse=False)
    print_table("Workflow executions for deployment: '%s'"
                "\n----------------------------------"
                % deployment.get('id'), 'executions', headers, sorted_table,
                ctx)
    if events:
        headers = ['Type', 'Started', 'Message']
        table = []
        for event in events:
            if isinstance(
                    event, collections.Iterable) and 'event_type' in event:
                table.append(
                    [event.get('event_type'), event.get('timestamp'),
                     event.get('message').get('text')])
        print_table("Events for workflow '%s'" %
                    deployment.get('workflow_id'), 'events',
                    headers, table, ctx)
Example #35
0
def print_deployment_info(deployment, executions, events, execution_id, ctx=None):
    headers = ["Blueprint Id", "Deployment Id", "Created", "Workflows"]
    table = []
    workflows = []
    for workflow in deployment.get("workflows"):
        workflows.append(workflow.get("name").encode("utf-8"))
    table.append(
        [
            deployment.get("blueprint_id"),
            deployment.get("id"),
            deployment.get("created_at")[:-7],
            utils.beautified(workflows),
        ]
    )
    print_table("Deployment information:\n-----------------------", "deployment", headers, table, ctx)
    print("\n")
    headers = ["Workflow", "Created", "Status", "Execution Id"]
    table = []
    if executions is None or len(executions) == 0:
        utils.print_message("no executions found", ctx)
        return
    for e in executions:
        table.append([e.get("workflow_id"), e.get("created_at")[:-7], e.get("status"), e.get("id")])
    sorted_table = sorted(table, key=operator.itemgetter(1), reverse=False)
    print_table(
        "Workflow executions for deployment: '%s'" "\n----------------------------------" % deployment.get("id"),
        "executions",
        headers,
        sorted_table,
        ctx,
    )
    if events:
        headers = ["Type", "Started", "Message"]
        table = []
        for event in events:
            if isinstance(event, collections.Iterable) and "event_type" in event:
                table.append([event.get("event_type"), event.get("timestamp")[:-9], event.get("message").get("text")])
        print("\n")
        print_table("Events for execution id '%s'" % execution_id, "events", headers, table, ctx)
Example #36
0
def print_execution(execution, ctx=None):
    if execution:
        headers = ["Workflow", "Created", "Status", "Message"]
        table = []
        table.append(
            [
                execution.get("workflow_id"),
                execution.get("created_at")[:-7],
                execution.get("status"),
                execution.get("error"),
            ]
        )
        sorted_table = sorted(table, key=operator.itemgetter(1), reverse=False)
        print_table(
            "Workflow execution '%s' for deployment '%s'" % (execution.get("id"), execution.get("deployment_id")),
            "execution",
            headers,
            sorted_table,
            ctx,
        )
    else:
        utils.print_message("No execution", ctx)
Example #37
0
def _create_deployment(
    cmd_proc,
    operation,
    deployment_id,
    blueprint_id,
    input_file,
    workflow,
    show_events,
    execution_id,
    force_cancel,
    force_delete,
    scoreclient,
):
    try:
        inputs = None
        if input_file:
            inputs = yaml.load(input_file)
        scoreclient.deployments.create(blueprint_id, deployment_id, inputs)
        utils.print_message("Successfully created deployment '{0}'.".format(deployment_id), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error(
            "Failed to create deployment. Reason: {0}, {1}".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #38
0
def _execute_workflow(cmd_proc, deployment_for_exection,
                      workflow, scoreclient):
    try:
        if not deployment_for_exection or not workflow:
            utils.print_error("Deployment ID or Workflow ID "
                              "was not specified.")
            return
        e = scoreclient.executions.start(
            deployment_for_exection, workflow)
        print_utils.print_dict(e) if e else utils.print_message(
            str(scoreclient.response.content), cmd_proc)
    except exceptions.ClientException as e:
            utils.print_error("Failed to execute workflow. Reasons: {0}."
                              .format(str(e)), cmd_proc)
Example #39
0
def _cancel(cmd_proc, operation, deployment_id, blueprint_id,
            input_file, workflow, show_events, execution_id,
            force_cancel, force_delete, scoreclient):

    if not execution_id:
        utils.print_error("Execution id is not specified.")
        return
    try:
        e = scoreclient.executions.cancel(execution_id, force_cancel)
        print_execution(e, None) if e else utils.print_message(
            str(scoreclient.response.content), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error("Failed to cancel workflow. Reasons: {0}, {1}."
                          .format(str(e), scoreclient.response.content),
                          cmd_proc)
Example #40
0
def _execute_workflow(cmd_proc, operation, deployment_id, blueprint_id,
                      input_file, workflow, show_events, execution_id,
                      force_cancel, force_delete, scoreclient):
    try:
        if not deployment_id or not workflow:
            utils.print_error("Deployment ID or Workflow ID "
                              "was not specified.")
            return
        e = scoreclient.executions.start(
            deployment_id, workflow)
        print_utils.print_dict(e) if e else utils.print_message(
            str(scoreclient.response.content), cmd_proc)
    except exceptions.ClientException as e:
            utils.print_error("Failed to execute workflow. Reasons: {0}, {1}"
                              .format(str(e), scoreclient.response.content),
                              cmd_proc)
Example #41
0
def _execute_workflow(
    cmd_proc,
    operation,
    deployment_id,
    blueprint_id,
    input_file,
    workflow,
    show_events,
    execution_id,
    force_cancel,
    force_delete,
    scoreclient,
):
    try:
        if not deployment_id or not workflow:
            utils.print_error("Deployment ID or Workflow ID " "was not specified.")
            return
        e = scoreclient.executions.start(deployment_id, workflow)
        print_utils.print_dict(e) if e else utils.print_message(str(scoreclient.response.content), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error(
            "Failed to execute workflow. Reasons: {0}, {1}".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #42
0
def _cancel(
    cmd_proc,
    operation,
    deployment_id,
    blueprint_id,
    input_file,
    workflow,
    show_events,
    execution_id,
    force_cancel,
    force_delete,
    scoreclient,
):

    if not execution_id:
        utils.print_error("Execution id is not specified.")
        return
    try:
        e = scoreclient.executions.cancel(execution_id, force_cancel)
        print_execution(e, None) if e else utils.print_message(str(scoreclient.response.content), cmd_proc)
    except exceptions.ClientException as e:
        utils.print_error(
            "Failed to cancel workflow. Reasons: {0}, {1}.".format(str(e), scoreclient.response.content), cmd_proc
        )
Example #43
0
def vdc(cmd_proc, operation, vdc, template, yes):
    """Operations with Virtual Data Centers"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['Virtual Data Center', "Selected"]
        table = ['', '']
        if cmd_proc.vca.vcloud_session and \
           cmd_proc.vca.vcloud_session.organization:
            links = (cmd_proc.vca.vcloud_session.organization.Link
                     if cmd_proc.vca.vcloud_session.organization else [])
            table1 = [[
                details.get_name(),
                '*' if details.get_name() == cmd_proc.vdc_name else ''
            ] for details in filter(
                lambda info: info.name and
                (info.type_ == 'application/vnd.vmware.vcloud.vdc+xml'), links)
                      ]
            table = sorted(table1, key=operator.itemgetter(0), reverse=False)
        utils.print_table(
            "Available Virtual Data Centers in org '%s', profile '%s':" %
            (cmd_proc.vca.org, cmd_proc.profile), headers, table, cmd_proc)
    elif 'use' == operation:
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc is not None:
            utils.print_message(
                "Using vdc '%s', profile '%s'" % (vdc, cmd_proc.profile),
                cmd_proc)
            cmd_proc.vdc_name = vdc
            cmd_proc.select_default_gateway()
        else:
            utils.print_error(
                "Unable to select vdc '%s' in profile '%s'" %
                (vdc, cmd_proc.profile), cmd_proc)
            sys.exit(1)
    elif 'info' == operation:
        if vdc is None:
            vdc = cmd_proc.vdc_name
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            gateways = cmd_proc.vca.get_gateways(vdc)
            headers1 = ['Type', 'Name']
            table1 = cmd_proc.vdc_to_table(the_vdc, gateways)
            headers2 = [
                'Resource', 'Allocated', 'Limit', 'Reserved', 'Used',
                'Overhead'
            ]
            table2 = cmd_proc.vdc_resources_to_table(the_vdc)
            headers3 = [
                'Name', 'External IPs', 'DHCP', 'Firewall', 'NAT', 'VPN',
                'Routed Networks', 'Syslog', 'Uplinks'
            ]
            table3 = cmd_proc.gateways_to_table(gateways)
            if cmd_proc.json_output:
                json_object = {
                    'vdc_entities': utils.table_to_json(headers1, table1),
                    'vdc_resources': utils.table_to_json(headers2, table2),
                    'gateways': utils.table_to_json(headers3, table3)
                }
                utils.print_json(json_object, cmd_proc=cmd_proc)
            else:
                utils.print_table(
                    "Details of Virtual Data Center '%s', profile '%s':" %
                    (vdc, cmd_proc.profile), headers1, table1, cmd_proc)
                utils.print_table("Compute capacity:", headers2, table2,
                                  cmd_proc)
                utils.print_table('Gateways:', headers3, table3, cmd_proc)
        else:
            utils.print_error(
                "Unable to select VDC %s, profile '%s': "
                "VDC not found" % (vdc, cmd_proc.profile), cmd_proc)
            sys.exit(1)
    elif 'create' == operation:
        if vdc is None:
            utils.print_error('please enter new VDC name')
            sys.exit(1)
        task = cmd_proc.vca.create_vdc(vdc, template)
        if task:
            utils.display_progress(
                task, cmd_proc,
                cmd_proc.vca.vcloud_session.get_vcloud_headers())
        else:
            utils.print_error("can't create the VDC", cmd_proc)
            sys.exit(1)
    elif 'delete' == operation:
        if vdc is None:
            vdc = cmd_proc.vdc_name
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            if not yes:
                confirmed = click.confirm("This will delete the VDC, its "
                                          "edge gateway and all its virtual "
                                          "machines.\n"
                                          "The action can't be undone.\n"
                                          "Do you want to delete VDC '%s'?" %
                                          vdc)
                if not confirmed:
                    utils.print_message('Action cancelled, '
                                        'VDC will not be deleted')
                    sys.exit(0)
            result = cmd_proc.vca.delete_vdc(vdc)
            if result[0]:
                utils.display_progress(
                    result[1], cmd_proc,
                    cmd_proc.vca.vcloud_session.get_vcloud_headers())
            else:
                utils.print_error("can't delete the VDC", cmd_proc)
                sys.exit(1)
        else:
            utils.print_error(
                "Unable to delete VDC '%s', profile '%s': "
                "VDC not found" % (vdc, cmd_proc.profile), cmd_proc)
            sys.exit(1)
    cmd_proc.save_current_config()
Example #44
0
def vapp(cmd_proc, operation, vdc, vapp, catalog, template, network, mode,
         vm_name, cust_file, media, disk_name, count, cpu, ram, ip):
    """Operations with vApps"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if vdc is None:
        vdc = cmd_proc.vdc_name
    the_vdc = cmd_proc.vca.get_vdc(vdc)
    if the_vdc is None:
        utils.print_error("VDC not found '%s'" % vdc, cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['vApp', "VMs", "Status", "Deployed", "Description"]
        table = cmd_proc.vapps_to_table(the_vdc)
        if cmd_proc.json_output:
            json_object = {'vapps': utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table(
                "Available vApps in '%s', profile '%s':" %
                (vdc, cmd_proc.profile), headers, table, cmd_proc)
    elif 'create' == operation:
        for x in xrange(1, count + 1):
            vapp_name = vapp
            if count > 1:
                vapp_name += '-' + str(x)
            utils.print_message(
                "creating vApp '%s' in VDC '%s'"
                " from template '%s' in catalog '%s'" %
                (vapp_name, vdc, template, catalog), cmd_proc)
            task = None
            if ((vm_name is not None) and ((cmd_proc.vca.version == "1.0") or
                                           (cmd_proc.vca.version == "1.5") or
                                           (cmd_proc.vca.version == "5.1") or
                                           (cmd_proc.vca.version == "5.5"))):
                task = cmd_proc.vca.create_vapp(vdc, vapp_name, template,
                                                catalog)
            else:
                task = cmd_proc.vca.create_vapp(vdc,
                                                vapp_name,
                                                template,
                                                catalog,
                                                vm_name=vm_name)
            if task:
                utils.display_progress(
                    task, cmd_proc,
                    cmd_proc.vca.vcloud_session.get_vcloud_headers())
            else:
                utils.print_error("can't create the vApp", cmd_proc)
                sys.exit(1)
            the_vdc = cmd_proc.vca.get_vdc(vdc)
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if ((vm_name is not None) and ((cmd_proc.vca.version == "1.0") or
                                           (cmd_proc.vca.version == "1.5") or
                                           (cmd_proc.vca.version == "5.1") or
                                           (cmd_proc.vca.version == "5.5"))):
                utils.print_message("setting VM name to '%s'" % (vm_name),
                                    cmd_proc)
                task = the_vapp.modify_vm_name(1, vm_name)
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't set VM name", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if vm_name is not None:
                utils.print_message(
                    "setting computer name for VM '%s'" % (vm_name), cmd_proc)
                task = the_vapp.customize_guest_os(vm_name,
                                                   computer_name=vm_name)
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't set computer name", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if cpu is not None:
                utils.print_message(
                    "configuring '%s' vCPUs for VM '%s', vApp '%s'" %
                    (cpu, vm_name, vapp_name), cmd_proc)
                task = the_vapp.modify_vm_cpu(vm_name, cpu)
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't configure virtual CPUs", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if ram is not None:
                utils.print_message(
                    "configuring '%s' MB of memory"
                    " for VM '%s', vApp '%s'" % (ram, vm_name, vapp_name),
                    cmd_proc)
                task = the_vapp.modify_vm_memory(vm_name, ram)
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't configure RAM", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if '' != network:
                utils.print_message(
                    "disconnecting VM from networks"
                    " pre-defined in the template", cmd_proc)
                task = the_vapp.disconnect_vms()
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't disconnect VM from networks",
                                      cmd_proc)
                    sys.exit(1)
                utils.print_message(
                    "disconnecting vApp from networks"
                    " pre-defined in the template", cmd_proc)
                task = the_vapp.disconnect_from_networks()
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't disconnect vApp from networks",
                                      cmd_proc)
                    sys.exit(1)
                nets = filter(lambda n: n.name == network,
                              cmd_proc.vca.get_networks(vdc))
                if len(nets) == 1:
                    utils.print_message(
                        "connecting vApp to network"
                        " '%s' with mode '%s'" % (network, mode), cmd_proc)
                    task = the_vapp.connect_to_network(nets[0].name,
                                                       nets[0].href)
                    if task:
                        utils.display_progress(
                            task, cmd_proc,
                            cmd_proc.vca.vcloud_session.get_vcloud_headers())
                    else:
                        utils.print_error(
                            "can't connect the vApp "
                            "to the network", cmd_proc)
                        sys.exit(1)
                    utils.print_message(
                        "connecting VM to network '%s'"
                        " with mode '%s'" % (network, mode), cmd_proc)
                    task = the_vapp.connect_vms(
                        nets[0].name,
                        connection_index=0,
                        ip_allocation_mode=mode.upper(),
                        mac_address=None,
                        ip_address=ip)
                    if task:
                        utils.display_progress(
                            task, cmd_proc,
                            cmd_proc.vca.vcloud_session.get_vcloud_headers())
                    else:
                        utils.print_error(
                            "can't connect the VM "
                            "to the network", cmd_proc)
                        sys.exit(1)
    elif 'delete' == operation:
        utils.print_message("deleting vApp '%s' from VDC '%s'" % (vapp, vdc),
                            cmd_proc)
        task = cmd_proc.vca.delete_vapp(vdc, vapp)
        if task:
            utils.display_progress(
                task, cmd_proc,
                cmd_proc.vca.vcloud_session.get_vcloud_headers())
        else:
            utils.print_error("can't delete the vApp", cmd_proc)
            sys.exit(1)
    elif 'deploy' == operation:
        utils.print_message("deploying vApp '%s' to VDC '%s'" % (vapp, vdc),
                            cmd_proc)
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
        task = the_vapp.deploy()
        if task:
            utils.display_progress(
                task, cmd_proc,
                cmd_proc.vca.vcloud_session.get_vcloud_headers())
        else:
            utils.print_error("can't deploy vApp", cmd_proc)
            sys.exit(1)
    elif 'undeploy' == operation:
        utils.print_message(
            "undeploying vApp '%s' from VDC '%s'" % (vapp, vdc), cmd_proc)
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
        task = the_vapp.undeploy()
        if task:
            utils.display_progress(
                task, cmd_proc,
                cmd_proc.vca.vcloud_session.get_vcloud_headers())
        else:
            utils.print_error("can't undeploy vApp", cmd_proc)
            sys.exit(1)
    elif ('info' == operation or 'power-off' == operation
          or 'power-on' == operation):
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
            if the_vapp and the_vapp.me:
                if 'info' == operation:
                    headers = ['Entity', 'Attribute', 'Value']
                    table = cmd_proc.vapp_details_to_table(the_vapp)
                    if cmd_proc.json_output:
                        json_object = {
                            'vapp': utils.table_to_json(headers, table)
                        }
                        utils.print_json(json_object, cmd_proc=cmd_proc)
                    else:
                        utils.print_table(
                            "Details of vApp '%s', "
                            "profile '%s':" % (vapp, cmd_proc.profile),
                            headers, table, cmd_proc)
                else:
                    task = None
                    if 'power-on' == operation:
                        task = the_vapp.poweron()
                    elif 'power-off' == operation:
                        task = the_vapp.poweroff()
                    elif 'delete' == operation:
                        task = the_vapp.delete()
                    if task:
                        utils.display_progress(
                            task, cmd_proc,
                            cmd_proc.vca.vcloud_session.get_vcloud_headers())
                    else:
                        utils.print_error("can't operate with the vApp",
                                          cmd_proc)
                        sys.exit(1)
            else:
                utils.print_error("vApp '%s' not found" % vapp, cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("VDC '%s' not found" % vdc, cmd_proc)
            sys.exit(1)
    elif 'customize' == operation:
        utils.print_message("customizing VM '%s'"
                            "in vApp '%s' in VDC '%s'" % (vm_name, vapp, vdc))
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
        if the_vdc and the_vapp and cust_file:
            utils.print_message("uploading customization script", cmd_proc)
            task = the_vapp.customize_guest_os(vm_name, cust_file.read())
            if task:
                utils.display_progress(
                    task, cmd_proc,
                    cmd_proc.vca.vcloud_session.get_vcloud_headers())
                utils.print_message("deploying and starting the vApp",
                                    cmd_proc)
                task = the_vapp.force_customization(vm_name)
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't customize vApp", cmd_proc)
                    sys.exit(1)
            else:
                utils.print_error("can't customize vApp", cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("can't find the resource", cmd_proc)
            sys.exit(1)
    elif 'insert' == operation or 'eject' == operation:
        utils.print_message("%s media '%s', VM '%s'"
                            " in vApp '%s' in VDC '%s'" %
                            (operation, media, vm_name, vapp, vdc))
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
            if the_vapp:
                the_media = cmd_proc.vca.get_media(catalog, media)
                task = the_vapp.vm_media(vm_name, the_media, operation)
                if task:
                    utils.display_progress(
                        task, cmd_proc,
                        cmd_proc.vca.vcloud_session.get_vcloud_headers())
                else:
                    utils.print_error("can't insert or eject media", cmd_proc)
                    sys.exit(1)
            else:
                utils.print_error("vApp '%s' not found" % vapp, cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("VDC '%s' not found" % vdc, cmd_proc)
            sys.exit(1)
    elif 'attach' == operation or 'detach' == operation:
        utils.print_message("%s disk '%s', VM '%s'"
                            " in vApp '%s' in VDC '%s'" %
                            (operation, disk_name, vm_name, vapp, vdc))
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
            if the_vapp:
                link = filter(lambda link: link.get_name() == disk_name,
                              cmd_proc.vca.get_diskRefs(the_vdc))
                if len(link) == 1:
                    if 'attach' == operation:
                        task = the_vapp.attach_disk_to_vm(vm_name, link[0])
                    else:
                        task = the_vapp.detach_disk_from_vm(vm_name, link[0])
                    if task:
                        utils.display_progress(
                            task, cmd_proc,
                            cmd_proc.vca.vcloud_session.get_vcloud_headers())
                    else:
                        utils.print_error("can't attach or detach disk",
                                          cmd_proc)
                        sys.exit(1)
                elif len(link) == 0:
                    utils.print_error("disk not found", cmd_proc)
                    sys.exit(1)
                elif len(link) > 1:
                    utils.print_error(
                        "more than one disk found with "
                        "the same name", cmd_proc)
                    sys.exit(1)
            else:
                utils.print_error("vApp '%s' not found" % vapp, cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("VDC '%s' not found" % vdc, cmd_proc)
            sys.exit(1)
    else:
        utils.print_error('not implemented', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()
Example #45
0
def catalog(cmd_proc, operation, catalog_name, item_name, description,
            file_name):
    """Operations with Catalogs"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        catalogs = cmd_proc.vca.get_catalogs()
        headers = ['Catalog', 'Item']
        table = cmd_proc.catalogs_to_table(catalogs)
        if cmd_proc.json_output:
            json_object = {'catalogs': utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table(
                "Available catalogs and items in org '%s', "
                "profile '%s':" % (cmd_proc.vca.org, cmd_proc.profile),
                headers, table, cmd_proc)
    elif 'create' == operation:
        task = cmd_proc.vca.create_catalog(catalog_name, description)
        if task:
            utils.display_progress(
                task, cmd_proc,
                cmd_proc.vca.vcloud_session.get_vcloud_headers())
        else:
            utils.print_error("can't create the catalog", cmd_proc)
            sys.exit(1)
    elif 'delete' == operation:
        result = cmd_proc.vca.delete_catalog(catalog_name)
        if result:
            utils.print_message('catalog deleted', cmd_proc)
        else:
            utils.print_error("can't delete the catalog", cmd_proc)
            sys.exit(1)
    elif 'delete-item' == operation:
        result = cmd_proc.vca.delete_catalog_item(catalog_name, item_name)
        if result:
            utils.print_message('catalog item deleted', cmd_proc)
        else:
            utils.print_error("can't delete the catalog item", cmd_proc)
            sys.exit(1)
    elif 'upload' == operation:
        if file_name.endswith('.iso'):
            result = cmd_proc.vca.upload_media(catalog_name, item_name,
                                               file_name, description, True,
                                               128 * 1024)
            if result:
                utils.print_message('file successfull uploaded', cmd_proc)
            else:
                utils.print_error("can't upload file", cmd_proc)
                sys.exit(1)
        else:
            utils.print_error(
                'not implemented, ' +
                'only .iso files are currently supported', cmd_proc)
            sys.exit(1)
    else:
        utils.print_error('not implemented', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()
Example #46
0
def cluster(cmd_proc, operation, cluster_name, cluster_id, node_count, vdc,
            network_name):
    """Operations with Container Service Extension"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if vdc is None:
        vdc = cmd_proc.vdc_name
    the_vdc = cmd_proc.vca.get_vdc(vdc)
    if the_vdc is None:
        utils.print_error("VDC not found '%s'" % vdc, cmd_proc)
        sys.exit(1)
    if cmd_proc.vca.vcloud_session and \
       cmd_proc.vca.vcloud_session.organization:
        cse = Cluster(session=cmd_proc.vca.vcloud_session,
                      verify=cmd_proc.verify,
                      log=cmd_proc.vca.log)
        if 'list' == operation:
            headers = ['Name', 'Id', 'Status', 'Leader IP', 'Masters', 'Nodes']
            table1 = []
            try:
                clusters = cse.get_clusters()
            except Exception:
                utils.print_error("can't get list of clusters", cmd_proc, cse)
                sys.exit(1)
            n = 1
            for cluster in clusters:
                cluster['name'] = 'k8s-cluster-%s' % n
                n += 1
                table1.append([
                    cluster['name'],
                    cluster['cluster_id'],
                    cluster['status'],
                    cluster['leader_endpoint'],
                    len(cluster['master_nodes']),
                    len(cluster['nodes']),
                ])
            table = sorted(table1, key=operator.itemgetter(0), reverse=False)
            utils.print_table(
                "Available clusters in VDC '%s', profile '%s':" %
                (vdc, cmd_proc.profile), headers, table, cmd_proc)
        elif 'create' == operation:
            utils.print_message("creating cluster '%s'" % (cluster_name))
            try:
                r = cse.create_cluster(vdc, network_name, cluster_name,
                                       node_count)
                t = Task(session=cmd_proc.vca.vcloud_session,
                         verify=cmd_proc.verify,
                         log=cmd_proc.vca.log)
                task = t.get_task(r['task_id'])
                utils.display_progress(
                    task, cmd_proc,
                    cmd_proc.vca.vcloud_session.get_vcloud_headers())
            except Exception:
                utils.print_error("can't create cluster", cmd_proc, cse)
                sys.exit(1)
        elif 'delete' == operation:
            utils.print_message("deleting cluster with id '%s'" % (cluster_id))
            try:
                r = cse.delete_cluster(cluster_id)
                t = Task(session=cmd_proc.vca.vcloud_session,
                         verify=cmd_proc.verify,
                         log=cmd_proc.vca.log)
                task = t.get_task(r['task_id'])
                utils.display_progress(
                    task, cmd_proc,
                    cmd_proc.vca.vcloud_session.get_vcloud_headers())
            except Exception:
                utils.print_error("can't delete cluster", cmd_proc, cse)
                sys.exit(1)
        else:
            utils.print_error('not implemented', cmd_proc)
            sys.exit(1)
    cmd_proc.save_current_config()
Example #47
0
def vdc(cmd_proc, operation, vdc, template, yes):
    """Operations with Virtual Data Centers"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['Virtual Data Center', "Selected"]
        table = ['', '']
        if cmd_proc.vca.vcloud_session and \
           cmd_proc.vca.vcloud_session.organization:
            links = (cmd_proc.vca.vcloud_session.organization.Link if
                     cmd_proc.vca.vcloud_session.organization else [])
            table1 = [[details.get_name(),
                      '*' if details.get_name() == cmd_proc.vdc_name else '']
                      for details in filter(lambda info: info.name and
                      (info.type_ == 'application/vnd.vmware.vcloud.vdc+xml'),
                      links)]
            table = sorted(table1, key=operator.itemgetter(0), reverse=False)
        utils.print_table(
            "Available Virtual Data Centers in org '%s', profile '%s':" %
            (cmd_proc.vca.org, cmd_proc.profile),
            headers, table, cmd_proc)
    elif 'use' == operation:
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc is not None:
            utils.print_message("Using vdc '%s', profile '%s'" %
                                (vdc, cmd_proc.profile), cmd_proc)
            cmd_proc.vdc_name = vdc
            cmd_proc.select_default_gateway()
        else:
            utils.print_error("Unable to select vdc '%s' in profile '%s'" %
                              (vdc, cmd_proc.profile), cmd_proc)
            sys.exit(1)
    elif 'info' == operation:
        if vdc is None:
            vdc = cmd_proc.vdc_name
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            gateways = cmd_proc.vca.get_gateways(vdc)
            headers1 = ['Type', 'Name']
            table1 = cmd_proc.vdc_to_table(the_vdc, gateways)
            headers2 = ['Resource', 'Allocated',
                        'Limit', 'Reserved', 'Used', 'Overhead']
            table2 = cmd_proc.vdc_resources_to_table(the_vdc)
            headers3 = ['Name', 'External IPs', 'DHCP', 'Firewall', 'NAT',
                        'VPN', 'Networks', 'Syslog', 'Uplinks', 'Selected']
            table3 = cmd_proc.gateways_to_table(gateways)
            if cmd_proc.json_output:
                json_object = {'vdc_entities':
                               utils.table_to_json(headers1, table1),
                               'vdc_resources':
                               utils.table_to_json(headers2, table2),
                               'gateways':
                               utils.table_to_json(headers3, table3)}
                utils.print_json(json_object, cmd_proc=cmd_proc)
            else:
                utils.print_table(
                    "Details of Virtual Data Center '%s', profile '%s':" %
                    (vdc, cmd_proc.profile),
                    headers1, table1, cmd_proc)
                utils.print_table("Compute capacity:",
                                  headers2, table2, cmd_proc)
                utils.print_table('Gateways:',
                                  headers3, table3, cmd_proc)
        else:
            utils.print_error("Unable to select VDC %s, profile '%s': "
                              "VDC not found" %
                              (vdc, cmd_proc.profile), cmd_proc)
            sys.exit(1)
    elif 'create' == operation:
        if vdc is None:
            utils.print_error('please enter new VDC name')
            sys.exit(1)
        task = cmd_proc.vca.create_vdc(vdc, template)
        if task:
            utils.display_progress(task, cmd_proc,
                                   cmd_proc.vca.vcloud_session.
                                   get_vcloud_headers())
        else:
            utils.print_error("can't create the VDC", cmd_proc)
            sys.exit(1)
    elif 'delete' == operation:
        if vdc is None:
            vdc = cmd_proc.vdc_name
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            if not yes:
                confirmed = click.confirm("This will delete the VDC, its "
                                          "edge gateway and all its virtual "
                                          "machines.\n"
                                          "The action can't be undone.\n"
                                          "Do you want to delete VDC '%s'?"
                                          % vdc)
                if not confirmed:
                    utils.print_message('Action cancelled, '
                                        'VDC will not be deleted')
                    sys.exit(0)
            result = cmd_proc.vca.delete_vdc(vdc)
            if result[0]:
                utils.display_progress(result[1], cmd_proc,
                                       cmd_proc.vca.vcloud_session.
                                       get_vcloud_headers())
            else:
                utils.print_error("can't delete the VDC", cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("Unable to delete VDC '%s', profile '%s': "
                              "VDC not found" %
                              (vdc, cmd_proc.profile), cmd_proc)
            sys.exit(1)
    cmd_proc.save_current_config()
Example #48
0
def vapp(cmd_proc, operation, vdc, vapp, catalog, template,
         network, mode, vm_name, cust_file,
         media, disk_name, count, cpu, ram, ip):
    """Operations with vApps"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if vdc is None:
        vdc = cmd_proc.vdc_name
    the_vdc = cmd_proc.vca.get_vdc(vdc)
    if the_vdc is None:
        utils.print_error("VDC not found '%s'" % vdc, cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        headers = ['vApp', "VMs", "Status", "Deployed", "Description"]
        table = cmd_proc.vapps_to_table(the_vdc)
        if cmd_proc.json_output:
            json_object = {'vapps':
                           utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table("Available vApps in '%s', profile '%s':" %
                              (vdc, cmd_proc.profile),
                              headers, table, cmd_proc)
    elif 'create' == operation:
        for x in xrange(1, count + 1):
            vapp_name = vapp
            if count > 1:
                vapp_name += '-' + str(x)
            utils.print_message("creating vApp '%s' in VDC '%s'"
                                " from template '%s' in catalog '%s'" %
                                (vapp_name, vdc, template, catalog),
                                cmd_proc)
            task = None
            if ((vm_name is not None) and
                ((cmd_proc.vca.version == "1.0") or
                 (cmd_proc.vca.version == "1.5") or
                 (cmd_proc.vca.version == "5.1") or
                 (cmd_proc.vca.version == "5.5"))):
                task = cmd_proc.vca.create_vapp(vdc, vapp_name,
                                                template, catalog)
            else:
                task = cmd_proc.vca.create_vapp(vdc, vapp_name,
                                                template, catalog,
                                                vm_name=vm_name)
            if task:
                utils.display_progress(task, cmd_proc,
                                       cmd_proc.vca.vcloud_session.
                                       get_vcloud_headers())
            else:
                utils.print_error("can't create the vApp", cmd_proc)
                sys.exit(1)
            the_vdc = cmd_proc.vca.get_vdc(vdc)
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if ((vm_name is not None) and
                ((cmd_proc.vca.version == "1.0") or
                 (cmd_proc.vca.version == "1.5") or
                 (cmd_proc.vca.version == "5.1") or
                 (cmd_proc.vca.version == "5.5"))):
                utils.print_message(
                    "setting VM name to '%s'"
                    % (vm_name), cmd_proc)
                task = the_vapp.modify_vm_name(1, vm_name)
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't set VM name", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if vm_name is not None:
                utils.print_message(
                    "setting computer name for VM '%s'"
                    % (vm_name), cmd_proc)
                task = the_vapp.customize_guest_os(vm_name,
                                                   computer_name=vm_name)
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't set computer name", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if cpu is not None:
                utils.print_message(
                    "configuring '%s' vCPUs for VM '%s', vApp '%s'"
                    % (cpu, vm_name, vapp_name), cmd_proc)
                task = the_vapp.modify_vm_cpu(vm_name, cpu)
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't configure virtual CPUs", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if ram is not None:
                utils.print_message("configuring '%s' MB of memory"
                                    " for VM '%s', vApp '%s'"
                                    % (ram, vm_name, vapp_name), cmd_proc)
                task = the_vapp.modify_vm_memory(vm_name, ram)
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't configure RAM", cmd_proc)
                    sys.exit(1)
                the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp_name)
            if '' != network:
                utils.print_message("disconnecting VM from networks"
                                    " pre-defined in the template", cmd_proc)
                task = the_vapp.disconnect_vms()
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't disconnect VM from networks",
                                      cmd_proc)
                    sys.exit(1)
                utils.print_message("disconnecting vApp from networks"
                                    " pre-defined in the template", cmd_proc)
                task = the_vapp.disconnect_from_networks()
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't disconnect vApp from networks",
                                      cmd_proc)
                    sys.exit(1)
                nets = filter(lambda n: n.name == network,
                              cmd_proc.vca.get_networks(vdc))
                if len(nets) == 1:
                    utils.print_message("connecting vApp to network"
                                        " '%s' with mode '%s'" %
                                        (network, mode), cmd_proc)
                    task = the_vapp.connect_to_network(
                        nets[0].name, nets[0].href)
                    if task:
                        utils.display_progress(task, cmd_proc,
                                               cmd_proc.vca.vcloud_session.
                                               get_vcloud_headers())
                    else:
                        utils.print_error("can't connect the vApp "
                                          "to the network",
                                          cmd_proc)
                        sys.exit(1)
                    utils.print_message("connecting VM to network '%s'"
                                        " with mode '%s'" % (network, mode),
                                        cmd_proc)
                    task = the_vapp.connect_vms(
                        nets[0].name,
                        connection_index=0,
                        ip_allocation_mode=mode.upper(),
                        mac_address=None, ip_address=ip)
                    if task:
                        utils.display_progress(task,
                                               cmd_proc,
                                               cmd_proc.vca.vcloud_session.
                                               get_vcloud_headers())
                    else:
                        utils.print_error("can't connect the VM "
                                          "to the network", cmd_proc)
                        sys.exit(1)
    elif 'delete' == operation:
        utils.print_message("deleting vApp '%s' from VDC '%s'" % (vapp, vdc),
                            cmd_proc)
        task = cmd_proc.vca.delete_vapp(vdc, vapp)
        if task:
            utils.display_progress(task, cmd_proc,
                                   cmd_proc.vca.vcloud_session.
                                   get_vcloud_headers())
        else:
            utils.print_error("can't delete the vApp", cmd_proc)
            sys.exit(1)
    elif 'deploy' == operation:
        utils.print_message("deploying vApp '%s' to VDC '%s'" % (vapp, vdc),
                            cmd_proc)
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
        task = the_vapp.deploy()
        if task:
            utils.display_progress(task, cmd_proc,
                                   cmd_proc.vca.vcloud_session.
                                   get_vcloud_headers())
        else:
            utils.print_error("can't deploy vApp", cmd_proc)
            sys.exit(1)
    elif 'undeploy' == operation:
        utils.print_message("undeploying vApp '%s' from VDC '%s'" %
                            (vapp, vdc), cmd_proc)
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
        task = the_vapp.undeploy()
        if task:
            utils.display_progress(task, cmd_proc,
                                   cmd_proc.vca.vcloud_session.
                                   get_vcloud_headers())
        else:
            utils.print_error("can't undeploy vApp", cmd_proc)
            sys.exit(1)
    elif ('info' == operation or 'power-off' == operation or
          'power-on' == operation):
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
            if the_vapp and the_vapp.me:
                if 'info' == operation:
                    headers = ['Entity', 'Attribute', 'Value']
                    table = cmd_proc.vapp_details_to_table(the_vapp)
                    if cmd_proc.json_output:
                        json_object = {'vapp':
                                       utils.table_to_json(headers, table)}
                        utils.print_json(json_object, cmd_proc=cmd_proc)
                    else:
                        utils.print_table("Details of vApp '%s', "
                                          "profile '%s':" %
                                          (vapp, cmd_proc.profile),
                                          headers, table, cmd_proc)
                else:
                    task = None
                    if 'power-on' == operation:
                        task = the_vapp.poweron()
                    elif 'power-off' == operation:
                        task = the_vapp.poweroff()
                    elif 'delete' == operation:
                        task = the_vapp.delete()
                    if task:
                        utils.display_progress(task,
                                               cmd_proc,
                                               cmd_proc.vca.vcloud_session.
                                               get_vcloud_headers())
                    else:
                        utils.print_error("can't operate with the vApp",
                                          cmd_proc)
                        sys.exit(1)
            else:
                utils.print_error("vApp '%s' not found" % vapp, cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("VDC '%s' not found" % vdc, cmd_proc)
            sys.exit(1)
    elif 'customize' == operation:
        utils.print_message("customizing VM '%s'"
                            "in vApp '%s' in VDC '%s'" %
                            (vm_name, vapp, vdc))
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
        if the_vdc and the_vapp and cust_file:
            utils.print_message("uploading customization script", cmd_proc)
            task = the_vapp.customize_guest_os(vm_name, cust_file.read())
            if task:
                utils.display_progress(task, cmd_proc,
                                       cmd_proc.vca.vcloud_session.
                                       get_vcloud_headers())
                utils.print_message("deploying and starting the vApp",
                                    cmd_proc)
                task = the_vapp.force_customization(vm_name)
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't customize vApp", cmd_proc)
                    sys.exit(1)
            else:
                utils.print_error("can't customize vApp", cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("can't find the resource",
                              cmd_proc)
            sys.exit(1)
    elif 'insert' == operation or 'eject' == operation:
        utils.print_message("%s media '%s', VM '%s'"
                            " in vApp '%s' in VDC '%s'" %
                            (operation, media, vm_name, vapp, vdc))
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
            if the_vapp:
                the_media = cmd_proc.vca.get_media(catalog, media)
                task = the_vapp.vm_media(vm_name, the_media, operation)
                if task:
                    utils.display_progress(task, cmd_proc,
                                           cmd_proc.vca.vcloud_session.
                                           get_vcloud_headers())
                else:
                    utils.print_error("can't insert or eject media",
                                      cmd_proc)
                    sys.exit(1)
            else:
                utils.print_error("vApp '%s' not found" % vapp, cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("VDC '%s' not found" % vdc, cmd_proc)
            sys.exit(1)
    elif 'attach' == operation or 'detach' == operation:
        utils.print_message("%s disk '%s', VM '%s'"
                            " in vApp '%s' in VDC '%s'" %
                            (operation, disk_name, vm_name, vapp, vdc))
        the_vdc = cmd_proc.vca.get_vdc(vdc)
        if the_vdc:
            the_vapp = cmd_proc.vca.get_vapp(the_vdc, vapp)
            if the_vapp:
                link = filter(lambda link:
                              link.get_name() == disk_name,
                              cmd_proc.vca.get_diskRefs(the_vdc))
                if len(link) == 1:
                    if 'attach' == operation:
                        task = the_vapp.attach_disk_to_vm(vm_name,
                                                          link[0])
                    else:
                        task = the_vapp.detach_disk_from_vm(vm_name,
                                                            link[0])
                    if task:
                        utils.display_progress(task, cmd_proc,
                                               cmd_proc.vca.vcloud_session.
                                               get_vcloud_headers())
                    else:
                        utils.print_error("can't attach or detach disk",
                                          cmd_proc)
                        sys.exit(1)
                elif len(link) == 0:
                    utils.print_error("disk not found", cmd_proc)
                    sys.exit(1)
                elif len(link) > 1:
                    utils.print_error("more than one disk found with "
                                      "the same name",
                                      cmd_proc)
                    sys.exit(1)
            else:
                utils.print_error("vApp '%s' not found" % vapp, cmd_proc)
                sys.exit(1)
        else:
            utils.print_error("VDC '%s' not found" % vdc, cmd_proc)
            sys.exit(1)
    else:
        utils.print_error('not implemented', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()
Example #49
0
def catalog(cmd_proc, operation, catalog_name, item_name, description,
            file_name):
    """Operations with Catalogs"""
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    if 'list' == operation:
        catalogs = cmd_proc.vca.get_catalogs()
        headers = ['Catalog', 'Item']
        table = cmd_proc.catalogs_to_table(catalogs)
        if cmd_proc.json_output:
            json_object = {'catalogs':
                           utils.table_to_json(headers, table)}
            utils.print_json(json_object, cmd_proc=cmd_proc)
        else:
            utils.print_table("Available catalogs and items in org '%s', "
                              "profile '%s':" %
                              (cmd_proc.vca.org, cmd_proc.profile),
                              headers, table, cmd_proc)
    elif 'create' == operation:
        task = cmd_proc.vca.create_catalog(catalog_name, description)
        if task:
            utils.display_progress(task, cmd_proc,
                                   cmd_proc.vca.vcloud_session.
                                   get_vcloud_headers())
        else:
            utils.print_error("can't create the catalog", cmd_proc)
            sys.exit(1)
    elif 'delete' == operation:
        result = cmd_proc.vca.delete_catalog(catalog_name)
        if result:
            utils.print_message('catalog deleted', cmd_proc)
        else:
            utils.print_error("can't delete the catalog", cmd_proc)
            sys.exit(1)
    elif 'delete-item' == operation:
        result = cmd_proc.vca.delete_catalog_item(catalog_name, item_name)
        if result:
            utils.print_message('catalog item deleted', cmd_proc)
        else:
            utils.print_error("can't delete the catalog item", cmd_proc)
            sys.exit(1)
    elif 'upload' == operation:
        if file_name.endswith('.iso'):
            result = cmd_proc.vca.upload_media(catalog_name, item_name,
                                               file_name, description, True,
                                               128*1024)
            if result:
                utils.print_message('file successfull uploaded', cmd_proc)
            else:
                utils.print_error("can't upload file", cmd_proc)
                sys.exit(1)
        else:
            utils.print_error('not implemented, ' +
                              'only .iso files are currently supported',
                              cmd_proc)
            sys.exit(1)
    else:
        utils.print_error('not implemented', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()
Example #50
0
def user(cmd_proc, operation, username, user_id, password, new_password,
         first_name, last_name, roles, token):
    """Operations with Users"""
    if cmd_proc.vca.service_type != VCA.VCA_SERVICE_TYPE_VCA:
        utils.print_error('Operation not supported ' 'in this service type')
        sys.exit(1)
    result = cmd_proc.re_login()
    if not result:
        utils.print_error('Not logged in', cmd_proc)
        sys.exit(1)
    try:
        if 'list' == operation:
            headers = [
                'User Name', 'First', 'Last', 'Email', 'State', 'Id', 'Roles'
            ]
            table = []
            for u in cmd_proc.vca.get_users():
                roles = []
                for r in u.get('roles').get('roles'):
                    roles.append(str(r.get('name')))
                table.append([
                    u.get('userName'),
                    u.get('givenName'),
                    u.get('familyName'),
                    u.get('email'),
                    u.get('state'),
                    u.get('id'),
                    utils.beautified(roles)
                ])
            sorted_table = sorted(table,
                                  key=operator.itemgetter(0),
                                  reverse=False)
            utils.print_table(
                "Available users in instance '%s'"
                ", profile '%s':" % (cmd_proc.instance, cmd_proc.profile),
                headers, sorted_table, cmd_proc)
        elif 'info' == operation:
            cmd_proc.error_message = 'not implemented'
            sys.exit(1)
        elif 'create' == operation:
            roles_array = roles.split(',')
            result = cmd_proc.vca.add_user(username, first_name, last_name,
                                           roles_array)
            utils.print_message("User '%s' successfully created" % username)
        elif 'delete' == operation:
            result = cmd_proc.vca.del_user(user_id)
            utils.print_message("Successfully deleted user '%s'" %
                                cmd_proc.vca.username)
        elif 'change-password' == operation:
            result = cmd_proc.vca.change_password(password, new_password)
            utils.print_message("Successfully changed password for user '%s'" %
                                cmd_proc.vca.username)
        elif 'validate' == operation:
            result = cmd_proc.vca.validate_user(username, password, token)
            print(result)
        elif 'reset-password' == operation:
            result = cmd_proc.vca.reset_password(user_id)
            utils.print_message("Successfully reset password for user id"
                                "'%s', check email to enter new password" %
                                user_id)
    except Exception:
        utils.print_error('An error has ocurred', cmd_proc)
        sys.exit(1)
    cmd_proc.save_current_config()