Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5'
[arvados.git] / services / nodemanager / arvnodeman / jobqueue.py
1 #!/usr/bin/env python
2
3 from __future__ import absolute_import, print_function
4
5 import logging
6
7 from . import clientactor
8 from .config import ARVADOS_ERRORS
9
10 class ServerCalculator(object):
11     """Generate cloud server wishlists from an Arvados job queue.
12
13     Instantiate this class with a list of cloud node sizes you're willing to
14     use, plus keyword overrides from the configuration.  Then you can pass
15     job queues to servers_for_queue.  It will return a list of node sizes
16     that would best satisfy the jobs, choosing the cheapest size that
17     satisfies each job, and ignoring jobs that can't be satisfied.
18     """
19
20     class CloudSizeWrapper(object):
21         def __init__(self, real_size, **kwargs):
22             self.real = real_size
23             for name in ['id', 'name', 'ram', 'disk', 'bandwidth', 'price',
24                          'extra']:
25                 setattr(self, name, getattr(self.real, name))
26             self.cores = kwargs.pop('cores')
27             self.scratch = self.disk
28             for name, override in kwargs.iteritems():
29                 if not hasattr(self, name):
30                     raise ValueError("unrecognized size field '%s'" % (name,))
31                 setattr(self, name, override)
32
33         def meets_constraints(self, **kwargs):
34             for name, want_value in kwargs.iteritems():
35                 have_value = getattr(self, name)
36                 if (have_value != 0) and (have_value < want_value):
37                     return False
38             return True
39
40
41     def __init__(self, server_list, max_nodes=None):
42         self.cloud_sizes = [self.CloudSizeWrapper(s, **kws)
43                             for s, kws in server_list]
44         self.cloud_sizes.sort(key=lambda s: s.price)
45         self.max_nodes = max_nodes or float('inf')
46         self.logger = logging.getLogger('arvnodeman.jobqueue')
47         self.logged_jobs = set()
48
49     @staticmethod
50     def coerce_int(x, fallback):
51         try:
52             return int(x)
53         except (TypeError, ValueError):
54             return fallback
55
56     def cloud_size_for_constraints(self, constraints):
57         want_value = lambda key: self.coerce_int(constraints.get(key), 0)
58         wants = {'cores': want_value('min_cores_per_node'),
59                  'ram': want_value('min_ram_mb_per_node'),
60                  'scratch': want_value('min_scratch_mb_per_node')}
61         for size in self.cloud_sizes:
62             if size.meets_constraints(**wants):
63                 return size
64         return None
65
66     def servers_for_queue(self, queue):
67         servers = []
68         seen_jobs = set()
69         for job in queue:
70             seen_jobs.add(job['uuid'])
71             constraints = job['runtime_constraints']
72             want_count = self.coerce_int(constraints.get('min_nodes'), 1)
73             cloud_size = self.cloud_size_for_constraints(constraints)
74             if cloud_size is None:
75                 if job['uuid'] not in self.logged_jobs:
76                     self.logged_jobs.add(job['uuid'])
77                     self.logger.debug("job %s not satisfiable", job['uuid'])
78             elif (want_count <= self.max_nodes):
79                 servers.extend([cloud_size.real] * max(1, want_count))
80         self.logged_jobs.intersection_update(seen_jobs)
81         return servers
82
83     def cheapest_size(self):
84         return self.cloud_sizes[0]
85
86
87 class JobQueueMonitorActor(clientactor.RemotePollLoopActor):
88     """Actor to generate server wishlists from the job queue.
89
90     This actor regularly polls Arvados' job queue, and uses the provided
91     ServerCalculator to turn that into a list of requested node sizes.  That
92     list is sent to subscribers on every poll.
93     """
94
95     CLIENT_ERRORS = ARVADOS_ERRORS
96     LOGGER_NAME = 'arvnodeman.jobqueue'
97
98     def __init__(self, client, timer_actor, server_calc, *args, **kwargs):
99         super(JobQueueMonitorActor, self).__init__(
100             client, timer_actor, *args, **kwargs)
101         self._calculator = server_calc
102
103     def _send_request(self):
104         return self._client.jobs().queue().execute()['items']
105
106     def _got_response(self, queue):
107         server_list = self._calculator.servers_for_queue(queue)
108         self._logger.debug("Sending server wishlist: %s",
109                            ', '.join(s.name for s in server_list) or "(empty)")
110         return super(JobQueueMonitorActor, self)._got_response(server_list)