Exemple #1
0
def list(context, args):
    params = {
        k: getattr(args, k)
        for k in ["sort", "limit", "offset", "where"]
    }
    params["embed"] = "topic,remoteci,team"
    return job.list(context, **params)
Exemple #2
0
def get_failed_jobs_for_product(product_id):
    num_of_jobs = dci_job.list(context,
                               where=f"product_id:{product_id},status:failure",
                               limit=1,
                               offset=0).json()["_meta"]["count"]
    offset = 0
    limit = 100
    jobs = []
    while offset < num_of_jobs:
        jobs_list = dci_job.list(
            context,
            where=f"product_id:{product_id},status:failure",
            limit=limit,
            offset=offset,
            embed="remoteci,jobstates,analytics",
        ).json()["jobs"]
        jobs = jobs + jobs_list
        offset += limit
    return jobs
Exemple #3
0
def list(context, limit):
    """list(context)

    List all jobs.

    >>> dcictl job-list
    """
    result = job.list(
        context, limit=limit, embed='jobdefinition,remoteci,team')
    headers = ['id', 'status', 'recheck',
               'jobdefinition/name', 'remoteci/name',
               'team/name', 'etag', 'created_at', 'updated_at']

    utils.format_output(result, context.format,
                        job.RESOURCE, headers)
Exemple #4
0
    def v2_playbook_on_play_start(self, play):
        """Event executed before each play. Create a new jobstate and save
        the current jobstate id.
        """
        def _get_comment(play):
            """ Return the comment for the new jobstate

                The order of priority is as follow:

                  * play/vars/dci_comment
                  * play/name
                  * '' (Empty String)
            """

            if play.get_vars() and 'dci_comment' in play.get_vars():
                comment = play.get_vars()['dci_comment'].encode('UTF-8')
            # If no name has been specified to the play, play.name is equal
            # to the hosts value
            elif play.name and play.name not in play.hosts:
                comment = play.name.encode('UTF-8')
            else:
                comment = ''

            return comment

        super(CallbackModule, self).v2_playbook_on_play_start(play)
        status = None
        comment = _get_comment(play)
        if play.get_vars():
            status = play.get_vars()['dci_status']
            if 'dci_mime_type' in play.get_vars():
                self._mime_type = play.get_vars()['dci_mime_type']
            else:
                self._mime_type = 'text/plain'

        if status:
            self._job_id = dci_job.list(
                self._dci_context).json()['jobs'][0]['id']
            ns = dci_jobstate.create(self._dci_context,
                                     status=status,
                                     comment=comment,
                                     job_id=self._job_id).json()
            self._jobstate_id = ns['jobstate']['id']
Exemple #5
0
def list(context):
    result = job.list(context)
    utils.format_output(result.json(), context.format,
                        job.RESOURCE, job.TABLE_HEADERS)
Exemple #6
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            state=dict(default='present',
                       choices=['present', 'absent'],
                       type='str'),
            # Authentication related parameters
            #
            dci_login=dict(required=False, type='str'),
            dci_password=dict(required=False, type='str'),
            dci_cs_url=dict(required=False, type='str'),
            # Resource related parameters
            #
            id=dict(type='str'),
            topic=dict(required=False, type='str'),
            remoteci=dict(type='str'),
            comment=dict(type='str'),
            status=dict(type='str'),
            configuration=dict(type='dict'),
            metadata=dict(type='dict'),
        ), )

    if not dciclient_found:
        module.fail_json(msg='The python dciclient module is required')

    topic_list = [module.params['topic'], os.getenv('DCI_TOPIC')]
    topic = next((item for item in topic_list if item is not None), None)

    login, password, url = get_details(module)
    if not login or not password:
        module.fail_json(msg='login and/or password have not been specified')

    ctx = dci_context.build_dci_context(url, login, password, 'Ansible')

    # Action required: List all jobs
    # Endpoint called: /jobs GET via dci_job.list()
    #
    # List all jobs
    if module_params_empty(module.params):
        res = dci_job.list(ctx)

    # Action required: Delete the job matching the job id
    # Endpoint called: /jobs/<job_id> DELETE via dci_job.delete()
    #
    # If the job exist and it has been succesfully deleted the changed is
    # set to true, else if the file does not exist changed is set to False
    elif module.params['state'] == 'absent':
        if not module.params['id']:
            module.fail_json(msg='id parameter is required')
        res = dci_job.get(ctx, module.params['id'])
        if res.status_code not in [400, 401, 404, 409]:
            kwargs = {
                'id': module.params['id'],
                'etag': res.json()['job']['etag']
            }
            res = dci_job.delete(ctx, **kwargs)

    # Action required: Retrieve job informations
    # Endpoint called: /jobs/<job_id> GET via dci_job.get()
    #
    # Get job informations
    elif module.params['id'] and not module.params[
            'comment'] and not module.params['status'] and not module.params[
                'configuration'] and not module.params['metadata']:
        res = dci_job.get(ctx, module.params['id'])

    # Action required: Update an existing job
    # Endpoint called: /jobs/<job_id> PUT via dci_job.update()
    #
    # Update the job with the specified characteristics.
    elif module.params['id']:
        res = dci_job.get(ctx, module.params['id'])
        if res.status_code not in [400, 401, 404, 409]:
            kwargs = {
                'id': module.params['id'],
                'etag': res.json()['job']['etag']
            }
            if module.params['comment']:
                kwargs['comment'] = module.params['comment']
            if module.params['status']:
                kwargs['status'] = module.params['status']
            if module.params['configuration']:
                kwargs['configuration'] = module.params['configuration']
            if module.params['metadata']:
                for k, v in module.params['metadata'].items():
                    dci_job.set_meta(ctx, module.params['id'], k, v)
            res = dci_job.update(ctx, **kwargs)

    # Action required: Schedule a new job
    # Endpoint called: /jobs/schedule POST via dci_job.schedule()
    #
    # Schedule a new job against the DCI Control-Server
    else:
        topic_id = dci_topic.get(ctx, topic).json()['topic']['id']
        remoteci = dci_remoteci.get(ctx, module.params['remoteci']).json()
        remoteci_id = remoteci['remoteci']['id']

        res = dci_job.schedule(ctx, remoteci_id, topic_id=topic_id)
        if res.status_code not in [400, 401, 404, 409]:
            res = dci_job.get_full_data(ctx, ctx.last_job_id)

    try:
        result = res.json()
        if res.status_code == 404:
            module.fail_json(msg='The resource does not exist')
        if res.status_code in [400, 401, 409]:
            result['changed'] = False
        else:
            result['changed'] = True
    except AttributeError:
        # Enter here if new job has been schedule, return of get_full_data is already json.
        result = res
        result['changed'] = True
        result['job_id'] = ctx.last_job_id
    except:
        result = {}
        result['changed'] = True

    module.exit_json(**result)