Esempio n. 1
0
def list(options):
    """
    list programs that belong to the authenticated user

    """
    configuration = config.get_default()
    app_url = configuration["app_url"]

    if options.deployment != None:
        deployment_name = options.deployment
    else:
        deployment_name = configuration["deployment_name"]

    client_id = configuration["client_id"]
    client_secret = configuration["client_secret"]

    token_manager = auth.TokenManager(client_id=client_id, client_secret=client_secret, app_url=app_url)

    if options.all == True:
        account_id = None

    else:
        account_id = accounts.get_logged_in_account_id(token_manager=token_manager, app_url=app_url)

    programs_details = programs.get_programs(
        deployment_name, token_manager=token_manager, created_by=account_id, app_url=app_url
    )

    account_ids = set()
    for program in programs_details:
        account_ids.add(program["createdBy"])

    accounts_details = accounts.get_accounts(account_ids, token_manager=token_manager, app_url=app_url)

    account_lookup = {}
    for account in accounts_details["accounts"]:
        account_lookup[account["id"]] = account

    headers = ["Name", "Last Saved", "Created By"]
    table = []

    for program in programs_details:
        username = account_lookup[program["createdBy"]]["username"]
        program_name = program["name"]
        last_edited = program["lastEdited"]
        table.append([program_name, last_edited, username])

    if options.format == "table":
        info(tabulate.tabulate(table, headers, tablefmt="orgtbl"))

    elif options.format == "text":
        info(tabulate.tabulate(table, headers, tablefmt="orgtbl", stralign="center"))

    else:
        raise JutException('Unsupported format "%s"' % options.format)
Esempio n. 2
0
def pull(options):
    """
    pull all remote programs to a local directory

    """
    configuration = config.get_default()
    app_url = configuration["app_url"]

    if options.deployment != None:
        deployment_name = options.deployment
    else:
        deployment_name = configuration["deployment_name"]

    client_id = configuration["client_id"]
    client_secret = configuration["client_secret"]

    token_manager = auth.TokenManager(client_id=client_id, client_secret=client_secret, app_url=app_url)

    if options.all == True:
        account_id = None

    else:
        account_id = accounts.get_logged_in_account_id(token_manager=token_manager, app_url=app_url)

    programs_details = programs.get_programs(
        deployment_name, token_manager=token_manager, created_by=account_id, app_url=app_url
    )

    if not os.path.exists(options.directory):
        os.mkdir(options.directory)

    account_ids = set()
    for program in programs_details:
        account_ids.add(program["createdBy"])

    accounts_details = accounts.get_accounts(account_ids, token_manager=token_manager, app_url=app_url)

    account_lookup = {}
    for account in accounts_details["accounts"]:
        account_lookup[account["id"]] = account

    decision = None
    for program in programs_details:
        program_name = program["name"]
        juttle_filename = "%s.juttle" % escape_filename(program_name)

        if options.per_user_directory:
            username = account_lookup[program["createdBy"]]["username"]
            userdir = os.path.join(options.directory, username)

            if not os.path.exists(userdir):
                os.mkdir(userdir)

            juttle_filepath = os.path.join(userdir, juttle_filename)

        else:
            juttle_filepath = os.path.join(options.directory, juttle_filename)

        if os.path.exists(juttle_filepath) and decision != "A":
            program_code = None
            with codecs.open(juttle_filepath, "r", encoding="UTF-8") as program_file:
                program_code = program_file.read()

            local_last_edited = int(os.stat(juttle_filepath).st_mtime)
            remote_last_edited = dates.iso8601_to_epoch(program["lastEdited"])

            if local_last_edited != remote_last_edited:
                info('Juttle changed since last pull for "%s"' % program_name)
                decision = console.prompt(
                    "Would you like to " "(O - Override," " S - Skip," " R - Review Changes," " A - override All)?"
                )

                if decision == "R":
                    info("Following is what would change if we overrode using your copy:")
                    info("*" * 80)
                    for line in difflib.ndiff(program["code"].split("\n"), program_code.split("\n")):
                        info(line)
                    info("*" * 80)
                    decision = console.prompt("Would you like to " "(O - Override," " S - Skip)?")

                if decision == "S":
                    # jump to the next file
                    continue

                elif decision == "O":
                    pass

                elif decision == "A":
                    pass

                else:
                    raise JutException('Unexpected option "%s"' % decision)

        info('importing program "%s" to %s' % (program["name"], juttle_filepath))
        with codecs.open(juttle_filepath, "w", encoding="UTF-8") as program_file:
            program_file.write(program["code"])

        # update creation time to match the lastEdited field
        epoch = dates.iso8601_to_epoch(program["lastEdited"])
        os.utime(juttle_filepath, (epoch, epoch))
Esempio n. 3
0
def _print_jobs(jobs, token_manager, app_url, options):
    """
    internal method to print the provided jobs array in a nice tabular
    format

    """
    accountids = set()
    for job in jobs:
        if job['user'] != 'jut.internal.user':
            accountids.add(job['user'])

    account_lookup = {
        'jut.internal.user': {
            'username': '******'
        }
    }

    if accountids:
        accounts_details = accounts.get_accounts(accountids,
                                                 token_manager=token_manager,
                                                 app_url=app_url)

        for account in accounts_details['accounts']:
            account_lookup[account['id']] = account

    if options.format == 'text':
        labels = OrderedDict()
        labels['id'] = 'Job ID'
        labels['alias'] = 'Juttle Name'
        labels['username'] = '******'
        labels['_start_time'] = 'Start Date'
        labels['persistent'] = 'Persistent'

        max_lengths = {
            'id': 0,
            'alias': 0,
            'username': 0,
            '_start_time': 0,
            'persistent': 0,
        }

        for key in max_lengths.keys():
            max_lengths[key] = len(labels[key]) + 1

        # retrieve username and fix up persistent marker
        for job in jobs:
            job['username'] = account_lookup[job['user']]['username']
            job['persistent'] = 'YES' if job['timeout'] == 0 else 'NO'

        # calculate max length of each column
        for job in jobs:
            for key in labels.keys():
                if max_lengths[key] < len(job[key]):
                    max_lengths[key] = len(job[key]) + 1

        # print labels
        header = ''
        for key in labels.keys():
            header += (labels[key] + ' ' * (max_lengths[key] - len(labels[key])))

        info(header)

        for job in jobs:
            line = ''

            for key in labels.keys():
                line += (job[key] + ' ' * (max_lengths[key] - len(job[key])))

            info(line)

    elif options.format == 'table':
        headers = ['Job ID', 'Juttle Name', 'Owner', 'Start Date', 'Persistent']

        table = []
        for job in jobs:
            owner = account_lookup[job['user']]['username']
            persistent = 'YES' if job['timeout'] == 0 else 'NO'
            name = ''

            if 'alias' in job:
                name = job['alias']

            table.append([job['id'],
                          name,
                          owner,
                          job['_start_time'],
                          persistent])

        info(tabulate.tabulate(table, headers, tablefmt="orgtbl"))

    else:
        raise JutException('Unsupported output format "%s"' %
                           options.format)