Ejemplo n.º 1
0
def _run(flow):
    """Make authorization and retrieve access token and user email.

    :param flow: OAuth2 web server flow
    :param launch_browser: if possible to run browser
    :return: dict with the keys token and email
    :rtype: dict
    """

    emitter.publish(
        errors.DefaultError('\n\n\n{}\n\n    {}\n\n'.format(
            'Go to the following link in your browser:',
            flow.step1_get_authorize_url())))

    sys.stderr.write('Enter verification code: ')
    code = sys.stdin.readline().strip()
    if not code:
        sys.stderr.write('Skipping authentication.\nEnter email address: ')

        email = sys.stdin.readline().strip()
        if not email:
            emitter.publish(errors.DefaultError('Skipping email input.'))
            email = str(uuid.uuid1())

        return {CORE_EMAIL_KEY: email}

    return make_oauth_request(code, flow)
Ejemplo n.º 2
0
def _list(json_, extra_field_names):
    """List DC/OS nodes

    :param json_: If true, output json.
        Otherwise, output a human readable table.
    :type json_: bool
    :param extra_field_names: List of additional field names to include in
        table output
    :type extra_field_names: [str]
    :returns: process return code
    :rtype: int
    """

    client = mesos.DCOSClient()
    slaves = client.get_state_summary()['slaves']
    if json_:
        emitter.publish(slaves)
    else:
        for extra_field_name in extra_field_names:
            field_name = extra_field_name.split(':')[-1]
            if len(slaves) > 0:
                try:
                    tables._dotted_itemgetter(field_name)(slaves[0])
                except KeyError:
                    emitter.publish(errors.DefaultError(
                        'Field "%s" is invalid.' % field_name))
                    return
        table = tables.slave_table(slaves, extra_field_names)
        output = six.text_type(table)
        if output:
            emitter.publish(output)
        else:
            emitter.publish(errors.DefaultError('No slaves found.'))
Ejemplo n.º 3
0
def _list(json_, extra_field_names):
    """List DC/OS nodes

    :param json_: If true, output json.
        Otherwise, output a human readable table.
    :type json_: bool
    :param extra_field_names: List of additional field names to include in
        table output
    :type extra_field_names: [str]
    :returns: process return code
    :rtype: int
    """

    client = mesos.DCOSClient()
    masters = mesos.MesosDNSClient().masters()
    master_state = client.get_master_state()
    slaves = client.get_state_summary()['slaves']
    for master in masters:
        if master['ip'] == master_state['hostname']:
            master['type'] = 'master (leader)'
            region, zone = util.get_fault_domain(master_state)
            master['region'] = region
            master['zone'] = zone
            for key in ('id', 'pid', 'version'):
                master[key] = master_state.get(key)
        else:
            master['type'] = 'master'
    for slave in slaves:
        region, zone = util.get_fault_domain(slave)
        slave['type'] = 'agent'
        slave['region'] = region
        slave['zone'] = zone
    nodes = masters + slaves
    if json_:
        emitter.publish(nodes)
    else:
        for extra_field_name in extra_field_names:
            field_name = extra_field_name.split(':')[-1]
            if len(slaves) > 0:
                try:
                    tables._dotted_itemgetter(field_name)(slaves[0])
                except KeyError:
                    emitter.publish(
                        errors.DefaultError('Field "%s" is invalid.' %
                                            field_name))
                    return
        table = tables.node_table(nodes, extra_field_names)
        output = six.text_type(table)
        if output:
            emitter.publish(output)
        else:
            emitter.publish(errors.DefaultError('No agents found.'))
Ejemplo n.º 4
0
def _validate_json_file(fullpath):
    """Validates the content of the file against its schema. Throws an
    exception if the file is not valid.

    :param fullpath: full path to the file.
    :type fullpath: str
    :return: json object if it is a special file
    :rtype: dict
    """

    filename = os.path.basename(fullpath)
    if filename in ['command.json', 'config.json', 'package.json']:
        schema_path = 'data/universe-schema/{}'.format(filename)
    else:
        raise DCOSException(('Error bundling package. Unknown file in package '
                             'directory [{}]').format(fullpath))

    special_schema = util.load_jsons(
        pkg_resources.resource_string('dcoscli', schema_path).decode('utf-8'))

    with util.open_file(fullpath) as special_file:
        special_json = util.load_json(special_file)

    errs = util.validate_json(special_json, special_schema)
    if errs:
        emitter.publish(
            errors.DefaultError(
                'Error validating JSON file [{}]'.format(fullpath)))
        raise DCOSException(util.list_to_err(errs))

    return special_json
Ejemplo n.º 5
0
def _main():
    signal.signal(signal.SIGINT, signal_handler)

    http.silence_requests_warnings()

    args = docopt.docopt(default_doc("dcos"), options_first=True)

    log_level = args['--log-level']
    if log_level and not _config_log_level_environ(log_level):
        return 1

    if args['--debug']:
        os.environ[constants.DCOS_DEBUG_ENV] = 'true'

    util.configure_process_from_environ()

    if args['--version']:
        return _get_versions()

    command = args['<command>']

    if not command:
        return dcos_help()

    if config.uses_deprecated_config():
        if constants.DCOS_CONFIG_ENV in os.environ:
            msg = ('{} is deprecated, please consider using '
                   '`dcos cluster setup <dcos_url>`.')
            err = errors.DefaultError(msg.format(constants.DCOS_CONFIG_ENV))
            emitter.publish(err)

        cluster.move_to_cluster_config()

    if command in subcommand.default_subcommands():
        sc = SubcommandMain(command, args['<args>'])
    else:
        executable = subcommand.command_executables(command)
        sc = subcommand.SubcommandProcess(executable, command, args['<args>'])

    exitcode, _ = sc.run_and_capture()
    return exitcode
Ejemplo n.º 6
0
def _list(json_):
    """List DC/OS nodes

    :param json_: If true, output json.
        Otherwise, output a human readable table.
    :type json_: bool
    :returns: process return code
    :rtype: int
    """

    client = mesos.DCOSClient()
    slaves = client.get_state_summary()['slaves']
    if json_:
        emitter.publish(slaves)
    else:
        table = tables.slave_table(slaves)
        output = six.text_type(table)
        if output:
            emitter.publish(output)
        else:
            emitter.publish(errors.DefaultError('No slaves found.'))
Ejemplo n.º 7
0
    def wrapper(*args, **kwargs):
        import re

        c = cluster.get_attached_cluster()
        if c is None:
            return func(*args, **kwargs)

        version = c.get_dcos_version()
        m = re.match(r'^(1\.[0-9]+)\D*', version)
        if m is None:
            return func(*args, **kwargs)

        supported_version = "1.14"
        major_version = m.group(1)

        if major_version != supported_version:
            message = ("Warning: The attached cluster is running DC/OS {} "
                       "but this CLI only supports DC/OS {}."
                       ).format(major_version, supported_version)
            emitter.publish(errors.DefaultError(message))

        return func(*args, **kwargs)
Ejemplo n.º 8
0
def signal_handler(signal, frame):
    emitter.publish(
        errors.DefaultError("User interrupted command with Ctrl-C"))
    sys.exit(0)
Ejemplo n.º 9
0
def _bundle(package_directory, output_directory):
    """
    :param package_directory: directory containing the package
    :type package_directory: str
    :param output_directory: directory where to save the package zip file
    :type output_directory: str
    :returns: process status
    :rtype: int
    """

    if output_directory is None:
        output_directory = os.getcwd()
    logger.debug('Using [%s] as the ouput directory', output_directory)

    # Find package.json file and parse it
    if not os.path.exists(os.path.join(package_directory, 'package.json')):
        raise DCOSException(
            ('The file package.json is required in the package directory '
             '[{}]').format(package_directory))

    package_json = _validate_json_file(
        os.path.join(package_directory, 'package.json'))

    with tempfile.NamedTemporaryFile() as temp_file:
        with zipfile.ZipFile(temp_file.name,
                             mode='w',
                             compression=zipfile.ZIP_DEFLATED,
                             allowZip64=True) as zip_file:
            # list through package directory and add files zip archive
            for filename in sorted(os.listdir(package_directory)):
                fullpath = os.path.join(package_directory, filename)
                if filename == 'marathon.json.mustache':
                    zip_file.write(fullpath, arcname=filename)
                elif filename in [
                        'config.json', 'command.json', 'package.json'
                ]:
                    # schema check the config and command json file
                    _validate_json_file(fullpath)
                    zip_file.write(fullpath, arcname=filename)
                elif filename == 'assets' and os.path.isdir(fullpath):
                    _bundle_assets(fullpath, zip_file)
                elif filename == 'images' and os.path.isdir(fullpath):
                    _bundle_images(fullpath, zip_file)
                else:
                    # anything else is an error
                    raise DCOSException(
                        ('Error bundling package. Extra file in package '
                         'directory [{}]').format(fullpath))

        # Compute the name of the package file
        zip_file_name = os.path.join(
            output_directory, '{}-{}-{}.zip'.format(package_json['name'],
                                                    package_json['version'],
                                                    _hashfile(temp_file.name)))

        if os.path.exists(zip_file_name):
            raise DCOSException(
                'Output file [{}] already exists'.format(zip_file_name))

        # rename with digest
        util.sh_copy(temp_file.name, zip_file_name)

    # Print the full path to the file
    emitter.publish(
        errors.DefaultError(
            'Created DCOS Universe package [{}].'.format(zip_file_name)))

    return 0