Ejemplo n.º 1
0
def monitor():

    try:
        window_size = arg_cardinal('window')
    except ValueError as ex:
        return bad_request(str(ex))

    try:
        cursor = dbcursor_query(
            """SELECT ppf, lower(times), upper(times), task, run,
                                          state_enum, state_display, task_json,
                                          task_cli FROM schedule_monitor(%s)""",
            [window_size])
    except Exception as ex:
        log.exception()
        return error(str(ex))

    result = []

    base_url = pscheduler.api_url_hostport(server_netloc())
    for row in cursor:

        task_href = "%s/tasks/%s" % (base_url, row[2])
        run_href = "%s/runs/%s" % (task_href, row[3])

        run = {
            "ppf": row[0],
            "start-time": pscheduler.datetime_as_iso8601(row[1]),
            "end-time": pscheduler.datetime_as_iso8601(row[2]),
            "href": run_href,
            "result-href": "%s/result" % run_href,
            "state": row[5],
            "state-display": row[6],
            "task": row[7],
            "cli": row[8]
        }

        run["task"]["href"] = task_href

        result.append(run)

    return ok_json(result)
Ejemplo n.º 2
0
def tasks():

    if request.method == 'GET':

        where_clause = "TRUE"
        args = []

        try:
            json_query = arg_json("json")
        except ValueError as ex:
            return bad_request(str(ex))

        if json_query is not None:
            where_clause += " AND task.json @> %s"
            args.append(request.args.get("json"))

        where_clause += " ORDER BY added"

        try:
            tasks = __tasks_get_filtered(request.base_url,
                                         where_clause=where_clause,
                                         args=args,
                                         expanded=is_expanded(),
                                         detail=arg_boolean("detail"),
                                         single=False)
        except Exception as ex:
            return error(str(ex))

        return ok_json(tasks)

    elif request.method == 'POST':

        try:
            task = pscheduler.json_load(request.data, max_schema=1)
        except ValueError as ex:
            return bad_request("Invalid task specification: %s" % (str(ex)))

        # Validate the JSON against a TaskSpecification
        # TODO: Figure out how to do this without the intermediate object

        valid, message = pscheduler.json_validate({"": task}, {
            "type": "object",
            "properties": {
                "": {
                    "$ref": "#/pScheduler/TaskSpecification"
                }
            },
            "required": [""]
        })

        if not valid:
            return bad_request("Invalid task specification: %s" % (message))

        # See if the test spec is valid

        try:
            returncode, stdout, stderr = pscheduler.run_program(
                [
                    "pscheduler", "internal", "invoke", "test",
                    task['test']['type'], "spec-is-valid"
                ],
                stdin=pscheduler.json_dump(task['test']['spec']))

            if returncode != 0:
                return error("Unable to validate test spec: %s" % (stderr))
            validate_json = pscheduler.json_load(stdout, max_schema=1)
            if not validate_json["valid"]:
                return bad_request(
                    "Invalid test specification: %s" %
                    (validate_json.get("error", "Unspecified error")))
        except Exception as ex:
            return error("Unable to validate test spec: " + str(ex))

        log.debug("Validated test: %s", pscheduler.json_dump(task['test']))

        # Reject tasks that have archive specs that use transforms.
        # See ticket #330.

        try:
            for archive in task['archives']:
                if "transform" in archive:
                    return bad_request(
                        "Use of transforms in archives is not yet supported.")
        except KeyError:
            pass  # Not there

        # Find the participants

        try:

            # HACK: BWCTLBC
            if "lead-bind" in task:
                lead_bind_env = {
                    "PSCHEDULER_LEAD_BIND_HACK": task["lead-bind"]
                }
            else:
                lead_bind_env = None

            returncode, stdout, stderr = pscheduler.run_program(
                [
                    "pscheduler", "internal", "invoke", "test",
                    task['test']['type'], "participants"
                ],
                stdin=pscheduler.json_dump(task['test']['spec']),
                timeout=5,
                env_add=lead_bind_env)

            if returncode != 0:
                return error("Unable to determine participants: " + stderr)

            participants = [
                host if host is not None else server_netloc() for host in
                pscheduler.json_load(stdout, max_schema=1)["participants"]
            ]
        except Exception as ex:
            return error("Exception while determining participants: " +
                         str(ex))
        nparticipants = len(participants)

        # TODO: The participants must be unique.  This should be
        # verified by fetching the host name from each one.

        #
        # TOOL SELECTION
        #

        lead_bind = task.get("lead-bind", None)

        # TODO: Need to provide for tool being specified by the task
        # package.

        tools = []

        tool_params = {"test": pscheduler.json_dump(task["test"])}
        # HACK: BWCTLBC
        if lead_bind is not None:
            log.debug("Using lead bind of %s" % str(lead_bind))
            tool_params["lead-bind"] = lead_bind

        for participant_no in range(0, len(participants)):

            participant = participants[participant_no]

            try:

                # Make sure the other participants are running pScheduler

                participant_api = pscheduler.api_url_hostport(participant)

                log.debug("Pinging %s" % (participant))
                status, result = pscheduler.url_get(participant_api,
                                                    throw=False,
                                                    timeout=10,
                                                    bind=lead_bind)

                if status == 400:
                    raise TaskPostingException(result)
                elif status in [ 202, 204, 205, 206, 207, 208, 226,
                                 300, 301, 302, 303, 304, 205, 306, 307, 308 ] \
                    or ( (status >= 400) and (status <=499) ):
                    raise TaskPostingException(
                        "Host is not running pScheduler")
                elif status != 200:
                    raise TaskPostingException("returned status %d: %s" %
                                               (status, result))

                # TODO: This will fail with a very large test spec.
                status, result = pscheduler.url_get("%s/tools" %
                                                    (participant_api),
                                                    params=tool_params,
                                                    throw=False,
                                                    bind=lead_bind)
                if status != 200:
                    raise TaskPostingException("%d: %s" % (status, result))
                tools.append(result)
            except TaskPostingException as ex:
                return error("Error getting tools from %s: %s" \
                                     % (participant, str(ex)))
            log.debug("Participant %s offers tools %s", participant, result)

        if len(tools) != nparticipants:
            return error("Didn't get a full set of tool responses")

        if "tools" in task:
            tool = pick_tool(tools, pick_from=task['tools'])
        else:
            tool = pick_tool(tools)

        if tool is None:
            # TODO: This could stand some additional diagnostics.
            return no_can_do(
                "Couldn't find a tool in common among the participants.")

        task['tool'] = tool

        #
        # TASK CREATION
        #

        tasks_posted = []

        # Evaluate the task against the limits and reject the request
        # if it doesn't pass.

        log.debug("Checking limits on %s", task["test"])

        (processor, whynot) = limitprocessor()
        if processor is None:
            log.debug("Limit processor is not initialized. %s", whynot)
            return no_can_do("Limit processor is not initialized: %s" % whynot)

        hints = request_hints()
        hints_data = pscheduler.json_dump(hints)

        log.debug("Processor = %s" % processor)
        passed, limits_passed, diags = processor.process(task["test"], hints)

        if not passed:
            return forbidden("Task forbidden by limits:\n" + diags)

        # Post the lead with the local database, which also assigns
        # its UUID.  Make it disabled so the scheduler doesn't try to
        # do anything with it until the task has been submitted to all
        # of the other participants.

        try:
            cursor = dbcursor_query(
                "SELECT * FROM api_task_post(%s, %s, %s, %s, 0, NULL, FALSE)",
                [
                    pscheduler.json_dump(task), participants, hints_data,
                    pscheduler.json_dump(limits_passed)
                ],
                onerow=True)
        except Exception as ex:
            return error(str(ex.diag.message_primary))

        if cursor.rowcount == 0:
            return error("Task post failed; poster returned nothing.")

        task_uuid = cursor.fetchone()[0]

        log.debug("Tasked lead, UUID %s", task_uuid)

        # Other participants get the UUID and participant list forced upon them.

        task["participants"] = participants
        task_data = pscheduler.json_dump(task)

        for participant in range(1, nparticipants):

            part_name = participants[participant]
            log.debug("Tasking participant %s", part_name)
            try:

                # Post the task

                log.debug("Tasking %d@%s: %s", participant, part_name,
                          task_data)
                post_url = pscheduler.api_url_hostport(part_name,
                                                       'tasks/' + task_uuid)
                log.debug("Posting task to %s", post_url)
                status, result = pscheduler.url_post(
                    post_url,
                    params={'participant': participant},
                    data=task_data,
                    bind=lead_bind,
                    json=False,
                    throw=False)
                log.debug("Remote returned %d: %s", status, result)
                if status != 200:
                    raise TaskPostingException(
                        "Unable to post task to %s: %s" % (part_name, result))
                tasks_posted.append(result)

                # Fetch the task's details and add the list of limits
                # passed to our own.

                status, result = pscheduler.url_get(post_url,
                                                    params={"detail": True},
                                                    bind=lead_bind,
                                                    throw=False)
                if status != 200:
                    raise TaskPostingException(
                        "Unable to fetch posted task from %s: %s" %
                        (part_name, result))
                log.debug("Fetched %s", result)
                try:
                    details = result["detail"]["spec-limits-passed"]
                    log.debug("Details from %s: %s", post_url, details)
                    limits_passed.extend(details)
                except KeyError:
                    pass

            except TaskPostingException as ex:

                # Disable the task locally and let it get rid of the
                # other participants.

                posted_to = "%s/%s" % (request.url, task_uuid)
                parsed = list(urlparse.urlsplit(posted_to))
                parsed[1] = "%s"
                template = urlparse.urlunsplit(parsed)

                try:
                    dbcursor_query("SELECT api_task_disable(%s, %s)",
                                   [task_uuid, template])
                except Exception:
                    log.exception()

                return error("Error while tasking %s: %s" % (part_name, ex))

        # Update the list of limits passed in the local database
        # TODO: How do the other participants know about this?
        log.debug("Limits passed: %s", limits_passed)
        try:
            cursor = dbcursor_query(
                "UPDATE task SET limits_passed = %s::JSON WHERE uuid = %s",
                [pscheduler.json_dump(limits_passed), task_uuid])
        except Exception as ex:
            return error(str(ex.diag.message_primary))

        # Enable the task so the scheduler will schedule it.
        try:
            dbcursor_query("SELECT api_task_enable(%s)", [task_uuid])
        except Exception as ex:
            log.exception()
            return error("Failed to enable task %s.  See system logs." %
                         task_uuid)
        log.debug("Task enabled for scheduling.")

        return ok_json("%s/%s" % (request.base_url, task_uuid))

    else:

        return not_allowed()
Ejemplo n.º 3
0
def tasks():

    if request.method == 'GET':

        where_clause = "TRUE"
        args = []

        try:
            json_query = arg_json("json")
        except ValueError as ex:
            return bad_request(str(ex))

        if json_query is not None:
            where_clause += " AND task.json_detail @> %s"
            args.append(request.args.get("json"))

        where_clause += " ORDER BY added"

        tasks = __tasks_get_filtered(request.base_url,
                                     where_clause=where_clause,
                                     args=args,
                                     expanded=is_expanded(),
                                     detail=arg_boolean("detail"),
                                     single=False)

        return ok_json(tasks)

    elif request.method == 'POST':

        data = request.data.decode("ascii")

        try:
            task = pscheduler.json_load(data, max_schema=3)
        except ValueError as ex:
            return bad_request("Invalid task specification: %s" % (str(ex)))

        # Validate the JSON against a TaskSpecification
        # TODO: Figure out how to do this without the intermediate object

        valid, message = pscheduler.json_validate({"": task}, {
            "type": "object",
            "properties": {
                "": {
                    "$ref": "#/pScheduler/TaskSpecification"
                }
            },
            "required": [""]
        })

        if not valid:
            return bad_request("Invalid task specification: %s" % (message))

        # See if the test spec is valid

        try:
            returncode, stdout, stderr = pscheduler.plugin_invoke(
                "test",
                task['test']['type'],
                "spec-is-valid",
                stdin=pscheduler.json_dump(task['test']['spec']))

            if returncode != 0:
                return error("Unable to validate test spec: %s" % (stderr))
            validate_json = pscheduler.json_load(stdout, max_schema=1)
            if not validate_json["valid"]:
                return bad_request(
                    "Invalid test specification: %s" %
                    (validate_json.get("error", "Unspecified error")))
        except Exception as ex:
            return error("Unable to validate test spec: " + str(ex))

        log.debug("Validated test: %s", pscheduler.json_dump(task['test']))

        # Validate the schedule

        try:
            cron = crontab.CronTab(task["schedule"]["repeat-cron"])
        except (AttributeError, ValueError):
            return error("Cron repeat specification is invalid.")
        except KeyError:
            pass

        # Validate the archives

        for archive in task.get("archives", []):

            # Data

            try:
                returncode, stdout, stderr = pscheduler.plugin_invoke(
                    "archiver",
                    archive["archiver"],
                    "data-is-valid",
                    stdin=pscheduler.json_dump(archive["data"]),
                )
                if returncode != 0:
                    return error("Unable to validate archive spec: %s" %
                                 (stderr))
            except Exception as ex:
                return error("Unable to validate test spec: " + str(ex))

            try:
                returned_json = pscheduler.json_load(stdout)
                if not returned_json["valid"]:
                    return bad_request("Invalid archiver data: %s" %
                                       (returned_json["error"]))
            except Exception as ex:
                return error("Internal probelm validating archiver data: %s" %
                             (str(ex)))

            # Transform, if there was one.

            if "transform" in archive:
                transform = archive["transform"]
                try:
                    _ = pscheduler.JQFilter(filter_spec=transform["script"],
                                            args=transform.get("args", {}))

                except ValueError as ex:
                    return error("Invalid transform: %s" % (str(ex)))

        # Validate the lead binding if there was one.

        lead_bind = task.get("lead-bind", None)
        if lead_bind is not None \
           and (pscheduler.address_interface(lead_bind) is None):
            return bad_request("Lead bind '%s' is not  on this host" %
                               (lead_bind))

        # Evaluate the task against the limits and reject the request
        # if it doesn't pass.  We do this early so anything else in
        # the process gets any rewrites.

        log.debug("Checking limits on %s", task)

        (processor, whynot) = limitprocessor()
        if processor is None:
            log.debug("Limit processor is not initialized. %s", whynot)
            return no_can_do("Limit processor is not initialized: %s" % whynot)

        hints, error_response = request_hints()
        if hints is None:
            log.debug("Can't come up with valid hints for lead task limits.")
            return error_response

        hints_data = pscheduler.json_dump(hints)

        log.debug("Processor = %s" % processor)
        passed, limits_passed, diags, new_task, _priority \
            = processor.process(task, hints)

        if not passed:
            return forbidden("Task forbidden by limits:\n" + diags)

        if new_task is not None:
            try:
                task = new_task
                returncode, stdout, stderr = pscheduler.plugin_invoke(
                    "test",
                    task['test']['type'],
                    "spec-is-valid",
                    stdin=pscheduler.json_dump(task["test"]["spec"]))

                if returncode != 0:
                    return error(
                        "Failed to validate rewritten test specification: %s" %
                        (stderr))
                validate_json = pscheduler.json_load(stdout, max_schema=1)
                if not validate_json["valid"]:
                    return bad_request(
                        "Rewritten test specification is invalid: %s" %
                        (validate_json.get("error", "Unspecified error")))
            except Exception as ex:
                return error(
                    "Unable to validate rewritten test specification: " +
                    str(ex))

        # Find the participants

        try:

            returncode, stdout, stderr = pscheduler.plugin_invoke(
                "test",
                task['test']['type'],
                "participants",
                stdin=pscheduler.json_dump(task['test']['spec']),
                timeout=5)

            if returncode != 0:
                return error("Unable to determine participants: " + stderr)

            participants = [
                host if host is not None else server_netloc() for host in
                pscheduler.json_load(stdout, max_schema=1)["participants"]
            ]
        except Exception as ex:
            return error("Exception while determining participants: " +
                         str(ex))
        nparticipants = len(participants)

        # TODO: The participants must be unique.  This should be
        # verified by fetching the host name from each one.

        #
        # TOOL SELECTION
        #

        # TODO: Need to provide for tool being specified by the task
        # package.

        tools = []

        tool_params = {"test": pscheduler.json_dump(task["test"])}

        tool_offers = {}

        for participant_no in range(0, len(participants)):

            participant = participants[participant_no]

            try:

                # Make sure the other participants are running pScheduler

                participant_api = pscheduler.api_url_hostport(participant)

                log.debug("Pinging %s" % (participant))
                status, result = pscheduler.url_get(participant_api,
                                                    throw=False,
                                                    timeout=10,
                                                    bind=lead_bind)

                if status == 400:
                    raise TaskPostingException(result)
                elif status in [ 202, 204, 205, 206, 207, 208, 226,
                                 300, 301, 302, 303, 304, 205, 306, 307, 308 ] \
                    or ( (status >= 400) and (status <=499) ):
                    raise TaskPostingException(
                        "Host is not running pScheduler")
                elif status != 200:
                    raise TaskPostingException("returned status %d: %s" %
                                               (status, result))

                # TODO: This will fail with a very large test spec.
                status, result = pscheduler.url_get("%s/tools" %
                                                    (participant_api),
                                                    params=tool_params,
                                                    throw=False,
                                                    bind=lead_bind)
                if status != 200:
                    raise TaskPostingException("%d: %s" % (status, result))
                tools.append(result)
            except TaskPostingException as ex:
                return error("Error getting tools from %s: %s" \
                                     % (participant, str(ex)))
            log.debug("Participant %s offers tools %s", participant, result)
            tool_offers[participant] = result

        if len(tools) != nparticipants:
            return error("Didn't get a full set of tool responses")

        if "tools" in task:
            tool = pick_tool(tools, pick_from=task['tools'])
        else:
            tool = pick_tool(tools)

        # Complain if no usable tool was found

        if tool is None:

            offers = []
            for participant in participants:
                participant_offers = tool_offers.get(participant,
                                                     [{
                                                         "name": "nothing"
                                                     }])
                if participant_offers is not None:
                    offer_set = [offer["name"] for offer in participant_offers]
                else:
                    offer_set = ["nothing"]
                offers.append("%s offered %s" %
                              (participant, ", ".join(offer_set)))

            return no_can_do("No tool in common among the participants:  %s." %
                             (";  ".join(offers)))

        task['tool'] = tool

        #
        # TASK CREATION
        #

        tasks_posted = []

        # Post the lead with the local database, which also assigns
        # its UUID.  Make it disabled so the scheduler doesn't try to
        # do anything with it until the task has been submitted to all
        # of the other participants.

        cursor = dbcursor_query(
            "SELECT * FROM api_task_post(%s, %s, %s, %s, 0, %s, NULL, FALSE, %s)",
            [
                pscheduler.json_dump(task), participants, hints_data,
                pscheduler.json_dump(limits_passed),
                task.get("priority", None), diags
            ],
            onerow=True)

        if cursor.rowcount == 0:
            return error("Task post failed; poster returned nothing.")

        task_uuid = cursor.fetchone()[0]

        log.debug("Tasked lead, UUID %s", task_uuid)

        # Other participants get the UUID and participant list forced upon them.

        task["participants"] = participants

        task_params = {"key": task["_key"]} if "_key" in task else {}

        for participant in range(1, nparticipants):

            part_name = participants[participant]
            log.debug("Tasking participant %s", part_name)
            try:

                # Post the task

                log.debug("Tasking %d@%s: %s", participant, part_name, task)
                post_url = pscheduler.api_url_hostport(part_name,
                                                       'tasks/' + task_uuid)

                task_params["participant"] = participant

                log.debug("Posting task to %s", post_url)
                status, result = pscheduler.url_post(post_url,
                                                     params=task_params,
                                                     data=task,
                                                     bind=lead_bind,
                                                     json=False,
                                                     throw=False)
                log.debug("Remote returned %d: %s", status, result)
                if status != 200:
                    raise TaskPostingException(
                        "Unable to post task to %s: %s" % (part_name, result))
                tasks_posted.append(result)

                # Fetch the task's details and add the list of limits
                # passed to our own.

                status, result = pscheduler.url_get(post_url,
                                                    params={"detail": True},
                                                    bind=lead_bind,
                                                    throw=False)
                if status != 200:
                    raise TaskPostingException(
                        "Unable to fetch posted task from %s: %s" %
                        (part_name, result))
                log.debug("Fetched %s", result)
                try:
                    details = result["detail"]["spec-limits-passed"]
                    log.debug("Details from %s: %s", post_url, details)
                    limits_passed.extend(details)
                except KeyError:
                    pass

            except TaskPostingException as ex:

                # Disable the task locally and let it get rid of the
                # other participants.

                posted_to = "%s/%s" % (request.url, task_uuid)
                parsed = list(urllib.parse.urlsplit(posted_to))
                parsed[1] = "%s"
                template = urllib.parse.urlunsplit(parsed)

                try:
                    dbcursor_query("SELECT api_task_disable(%s, %s)",
                                   [task_uuid, template])
                except Exception:
                    log.exception()

                return error("Error while tasking %s: %s" % (part_name, ex))

        # Update the list of limits passed in the local database
        # TODO: How do the other participants know about this?
        log.debug("Limits passed: %s", limits_passed)
        cursor = dbcursor_query(
            "UPDATE task SET limits_passed = %s::JSON WHERE uuid = %s",
            [pscheduler.json_dump(limits_passed), task_uuid])

        # Enable the task so the scheduler will schedule it.
        try:
            dbcursor_query("SELECT api_task_enable(%s)", [task_uuid])
        except Exception:
            log.exception()
            return error("Failed to enable task %s.  See system logs." %
                         task_uuid)
        log.debug("Task enabled for scheduling.")

        task_url = "%s/%s" % (request.base_url, task_uuid)

        # Non-expanded gets just the URL
        if not arg_boolean("expanded"):
            return ok_json(task_url)

        # Expanded gets a redirect to GET+expanded

        params = []
        for arg in ["detail", "pretty"]:
            if arg_boolean(arg):
                params.append(arg)

        if params:
            task_url += "?%s" % ("&".join(params))

        return see_other(task_url)

    else:

        return not_allowed()
Ejemplo n.º 4
0
def schedule():

    try:
        range_start = arg_datetime('start')
        range_end = arg_datetime('end')
    except ValueError:
        return bad_request('Invalid start or end time')

    try:
        task = arg_uuid("task")
    except ValueError:
        return bad_request('Invalid task UUID')

    query = [
        """
            SELECT
                lower(times),
                upper(times),
                task,
                run,
                state_enum,
                state_display,
                task_json,
                task_cli,
                test_json,
                tool_json,
                errors
            FROM schedule
            WHERE times && tstzrange(%s, %s, '[)')
    """
    ]
    args = [range_start, range_end]

    if task is not None:
        query.append("AND task = %s")
        args.append(task)

    try:
        cursor = dbcursor_query(" ".join(query), args)
    except Exception as ex:
        log.exception()
        return error(str(ex))

    result = []

    base_url = pscheduler.api_url_hostport(server_netloc(), "tasks/")
    for row in cursor:

        task_href = base_url + row[2]
        run_href = "%s/runs/%s" % (task_href, row[3])

        run = {
            "start-time": pscheduler.datetime_as_iso8601(row[0]),
            "end-time": pscheduler.datetime_as_iso8601(row[1]),
            "href": run_href,
            "result-href": "%s/result" % run_href,
            "state": row[4],
            "state-display": row[5],
            "task": row[6],
            "cli": row[7],
            "test": row[8],
            "tool": row[9],
            "errors": row[10]
        }

        run["task"]["href"] = task_href

        result.append(run)

    return ok_json(result)