1#! /usr/bin/python
2
3# Copyright 2015 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Counts the number of jobs created in the last 24 hours."""
8
9import argparse
10from datetime import datetime, timedelta
11import sys
12
13import common
14from autotest_lib.frontend import setup_django_environment
15from autotest_lib.frontend.afe import models
16from autotest_lib.server import site_utils
17
18try:
19    from chromite.lib import metrics
20except ImportError:
21    metrics = site_utils.metrics_mock
22
23
24def number_of_jobs_since(delta):
25    """Returns the number of jobs kicked off in the last |duration| minutes.
26
27    @param delta: A timedelta which indicates the maximum age of the jobs to count
28    """
29    cutoff = datetime.now() - delta
30    return models.Job.objects.filter(created_on__gt=cutoff).count()
31
32
33def main():
34    """Counts the number of AFE jobs in the last day, then pushes the count to statsd"""
35    parser = argparse.ArgumentParser(
36        description=('A script which records the number of afe jobs run in a time interval.'))
37    parser.parse_args(sys.argv[1:])
38    count = number_of_jobs_since(timedelta(days=1))
39
40    with site_utils.SetupTsMonGlobalState('count_jobs', short_lived=True):
41        # TODO: Reporting a stat for each job created from the afe directly could be better.
42        # More discussions are needed to decide whether to remove this file.
43        metrics.Gauge('chromeos/autotest/experimental/jobs_rate/afe_daily_count').set(count)
44
45
46if __name__ == '__main__':
47    main()
48