Aviv Keshet | 1830892 | 2013-02-19 17:49:49 -0800 | [diff] [blame^] | 1 | #pylint: disable-msg=C0111 |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 2 | """\ |
| 3 | Utility functions for rpc_interface.py. We keep them in a separate file so that |
| 4 | only RPC interface functions go into that file. |
| 5 | """ |
| 6 | |
| 7 | __author__ = 'showard@google.com (Steve Howard)' |
| 8 | |
Aviv Keshet | 1830892 | 2013-02-19 17:49:49 -0800 | [diff] [blame^] | 9 | import datetime, os, inspect |
showard | 3d6ae11 | 2009-05-02 00:45:48 +0000 | [diff] [blame] | 10 | import django.http |
jamesren | dd85524 | 2010-03-02 22:23:44 +0000 | [diff] [blame] | 11 | from autotest_lib.frontend.afe import models, model_logic, model_attributes |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 12 | |
showard | a62866b | 2008-07-28 21:27:41 +0000 | [diff] [blame] | 13 | NULL_DATETIME = datetime.datetime.max |
| 14 | NULL_DATE = datetime.date.max |
| 15 | |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 16 | def prepare_for_serialization(objects): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 17 | """ |
| 18 | Prepare Python objects to be returned via RPC. |
Aviv Keshet | 1830892 | 2013-02-19 17:49:49 -0800 | [diff] [blame^] | 19 | @param objects: objects to be prepared. |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 20 | """ |
| 21 | if (isinstance(objects, list) and len(objects) and |
| 22 | isinstance(objects[0], dict) and 'id' in objects[0]): |
| 23 | objects = gather_unique_dicts(objects) |
| 24 | return _prepare_data(objects) |
showard | b8d3424 | 2008-04-25 18:11:16 +0000 | [diff] [blame] | 25 | |
| 26 | |
showard | c92da83 | 2009-04-07 18:14:34 +0000 | [diff] [blame] | 27 | def prepare_rows_as_nested_dicts(query, nested_dict_column_names): |
| 28 | """ |
| 29 | Prepare a Django query to be returned via RPC as a sequence of nested |
| 30 | dictionaries. |
| 31 | |
| 32 | @param query - A Django model query object with a select_related() method. |
| 33 | @param nested_dict_column_names - A list of column/attribute names for the |
| 34 | rows returned by query to expand into nested dictionaries using |
| 35 | their get_object_dict() method when not None. |
| 36 | |
| 37 | @returns An list suitable to returned in an RPC. |
| 38 | """ |
| 39 | all_dicts = [] |
| 40 | for row in query.select_related(): |
| 41 | row_dict = row.get_object_dict() |
| 42 | for column in nested_dict_column_names: |
| 43 | if row_dict[column] is not None: |
| 44 | row_dict[column] = getattr(row, column).get_object_dict() |
| 45 | all_dicts.append(row_dict) |
| 46 | return prepare_for_serialization(all_dicts) |
| 47 | |
| 48 | |
showard | b8d3424 | 2008-04-25 18:11:16 +0000 | [diff] [blame] | 49 | def _prepare_data(data): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 50 | """ |
| 51 | Recursively process data structures, performing necessary type |
| 52 | conversions to values in data to allow for RPC serialization: |
| 53 | -convert datetimes to strings |
showard | 2b9a88b | 2008-06-13 20:55:03 +0000 | [diff] [blame] | 54 | -convert tuples and sets to lists |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 55 | """ |
| 56 | if isinstance(data, dict): |
| 57 | new_data = {} |
| 58 | for key, value in data.iteritems(): |
| 59 | new_data[key] = _prepare_data(value) |
| 60 | return new_data |
showard | 2b9a88b | 2008-06-13 20:55:03 +0000 | [diff] [blame] | 61 | elif (isinstance(data, list) or isinstance(data, tuple) or |
| 62 | isinstance(data, set)): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 63 | return [_prepare_data(item) for item in data] |
showard | 9865997 | 2008-07-17 17:00:07 +0000 | [diff] [blame] | 64 | elif isinstance(data, datetime.date): |
showard | a62866b | 2008-07-28 21:27:41 +0000 | [diff] [blame] | 65 | if data is NULL_DATETIME or data is NULL_DATE: |
| 66 | return None |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 67 | return str(data) |
| 68 | else: |
| 69 | return data |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 70 | |
| 71 | |
showard | 3d6ae11 | 2009-05-02 00:45:48 +0000 | [diff] [blame] | 72 | def raw_http_response(response_data, content_type=None): |
| 73 | response = django.http.HttpResponse(response_data, mimetype=content_type) |
| 74 | response['Content-length'] = str(len(response.content)) |
| 75 | return response |
| 76 | |
| 77 | |
showard | b0dfb9f | 2008-06-06 18:08:02 +0000 | [diff] [blame] | 78 | def gather_unique_dicts(dict_iterable): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 79 | """\ |
| 80 | Pick out unique objects (by ID) from an iterable of object dicts. |
| 81 | """ |
| 82 | id_set = set() |
| 83 | result = [] |
| 84 | for obj in dict_iterable: |
| 85 | if obj['id'] not in id_set: |
| 86 | id_set.add(obj['id']) |
| 87 | result.append(obj) |
| 88 | return result |
showard | b0dfb9f | 2008-06-06 18:08:02 +0000 | [diff] [blame] | 89 | |
| 90 | |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 91 | def extra_job_filters(not_yet_run=False, running=False, finished=False): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 92 | """\ |
| 93 | Generate a SQL WHERE clause for job status filtering, and return it in |
| 94 | a dict of keyword args to pass to query.extra(). No more than one of |
| 95 | the parameters should be passed as True. |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 96 | * not_yet_run: all HQEs are Queued |
| 97 | * finished: all HQEs are complete |
| 98 | * running: everything else |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 99 | """ |
| 100 | assert not ((not_yet_run and running) or |
| 101 | (not_yet_run and finished) or |
| 102 | (running and finished)), ('Cannot specify more than one ' |
| 103 | 'filter to this function') |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 104 | |
showard | eab66ce | 2009-12-23 00:03:56 +0000 | [diff] [blame] | 105 | not_queued = ('(SELECT job_id FROM afe_host_queue_entries ' |
| 106 | 'WHERE status != "%s")' |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 107 | % models.HostQueueEntry.Status.QUEUED) |
showard | eab66ce | 2009-12-23 00:03:56 +0000 | [diff] [blame] | 108 | not_finished = ('(SELECT job_id FROM afe_host_queue_entries ' |
| 109 | 'WHERE not complete)') |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 110 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 111 | if not_yet_run: |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 112 | where = ['id NOT IN ' + not_queued] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 113 | elif running: |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 114 | where = ['(id IN %s) AND (id IN %s)' % (not_queued, not_finished)] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 115 | elif finished: |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 116 | where = ['id NOT IN ' + not_finished] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 117 | else: |
showard | 10f4167 | 2009-05-13 21:28:25 +0000 | [diff] [blame] | 118 | return {} |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 119 | return {'where': where} |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 120 | |
| 121 | |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 122 | def extra_host_filters(multiple_labels=()): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 123 | """\ |
| 124 | Generate SQL WHERE clauses for matching hosts in an intersection of |
| 125 | labels. |
| 126 | """ |
| 127 | extra_args = {} |
showard | eab66ce | 2009-12-23 00:03:56 +0000 | [diff] [blame] | 128 | where_str = ('afe_hosts.id in (select host_id from afe_hosts_labels ' |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 129 | 'where label_id=%s)') |
| 130 | extra_args['where'] = [where_str] * len(multiple_labels) |
| 131 | extra_args['params'] = [models.Label.smart_get(label).id |
| 132 | for label in multiple_labels] |
| 133 | return extra_args |
showard | 8e3aa5e | 2008-04-08 19:42:32 +0000 | [diff] [blame] | 134 | |
| 135 | |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 136 | def get_host_query(multiple_labels, exclude_only_if_needed_labels, |
showard | 8aa84fc | 2009-09-16 17:17:55 +0000 | [diff] [blame] | 137 | exclude_atomic_group_hosts, valid_only, filter_data): |
| 138 | if valid_only: |
| 139 | query = models.Host.valid_objects.all() |
| 140 | else: |
| 141 | query = models.Host.objects.all() |
| 142 | |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 143 | if exclude_only_if_needed_labels: |
| 144 | only_if_needed_labels = models.Label.valid_objects.filter( |
| 145 | only_if_needed=True) |
showard | f7eac6f | 2008-11-13 21:18:01 +0000 | [diff] [blame] | 146 | if only_if_needed_labels.count() > 0: |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 147 | only_if_needed_ids = ','.join( |
| 148 | str(label['id']) |
| 149 | for label in only_if_needed_labels.values('id')) |
showard | f7eac6f | 2008-11-13 21:18:01 +0000 | [diff] [blame] | 150 | query = models.Host.objects.add_join( |
showard | eab66ce | 2009-12-23 00:03:56 +0000 | [diff] [blame] | 151 | query, 'afe_hosts_labels', join_key='host_id', |
| 152 | join_condition=('afe_hosts_labels_exclude_OIN.label_id IN (%s)' |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 153 | % only_if_needed_ids), |
| 154 | suffix='_exclude_OIN', exclude=True) |
showard | 8aa84fc | 2009-09-16 17:17:55 +0000 | [diff] [blame] | 155 | |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 156 | if exclude_atomic_group_hosts: |
| 157 | atomic_group_labels = models.Label.valid_objects.filter( |
| 158 | atomic_group__isnull=False) |
| 159 | if atomic_group_labels.count() > 0: |
| 160 | atomic_group_label_ids = ','.join( |
| 161 | str(atomic_group['id']) |
| 162 | for atomic_group in atomic_group_labels.values('id')) |
| 163 | query = models.Host.objects.add_join( |
showard | eab66ce | 2009-12-23 00:03:56 +0000 | [diff] [blame] | 164 | query, 'afe_hosts_labels', join_key='host_id', |
| 165 | join_condition=( |
| 166 | 'afe_hosts_labels_exclude_AG.label_id IN (%s)' |
| 167 | % atomic_group_label_ids), |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 168 | suffix='_exclude_AG', exclude=True) |
showard | 8aa84fc | 2009-09-16 17:17:55 +0000 | [diff] [blame] | 169 | |
| 170 | assert 'extra_args' not in filter_data |
| 171 | filter_data['extra_args'] = extra_host_filters(multiple_labels) |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 172 | return models.Host.query_objects(filter_data, initial_query=query) |
| 173 | |
| 174 | |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 175 | class InconsistencyException(Exception): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 176 | 'Raised when a list of objects does not have a consistent value' |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 177 | |
| 178 | |
| 179 | def get_consistent_value(objects, field): |
mbligh | c5ddfd1 | 2008-08-04 17:15:00 +0000 | [diff] [blame] | 180 | if not objects: |
| 181 | # well a list of nothing is consistent |
| 182 | return None |
| 183 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 184 | value = getattr(objects[0], field) |
| 185 | for obj in objects: |
| 186 | this_value = getattr(obj, field) |
| 187 | if this_value != value: |
| 188 | raise InconsistencyException(objects[0], obj) |
| 189 | return value |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 190 | |
| 191 | |
showard | 2b9a88b | 2008-06-13 20:55:03 +0000 | [diff] [blame] | 192 | def prepare_generate_control_file(tests, kernel, label, profilers): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 193 | test_objects = [models.Test.smart_get(test) for test in tests] |
showard | 2b9a88b | 2008-06-13 20:55:03 +0000 | [diff] [blame] | 194 | profiler_objects = [models.Profiler.smart_get(profiler) |
| 195 | for profiler in profilers] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 196 | # ensure tests are all the same type |
| 197 | try: |
| 198 | test_type = get_consistent_value(test_objects, 'test_type') |
| 199 | except InconsistencyException, exc: |
| 200 | test1, test2 = exc.args |
mbligh | ec5546d | 2008-06-16 16:51:28 +0000 | [diff] [blame] | 201 | raise model_logic.ValidationError( |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 202 | {'tests' : 'You cannot run both server- and client-side ' |
| 203 | 'tests together (tests %s and %s differ' % ( |
| 204 | test1.name, test2.name)}) |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 205 | |
jamesren | dd85524 | 2010-03-02 22:23:44 +0000 | [diff] [blame] | 206 | is_server = (test_type == model_attributes.TestTypes.SERVER) |
showard | 14374b1 | 2009-01-31 00:11:54 +0000 | [diff] [blame] | 207 | if test_objects: |
| 208 | synch_count = max(test.sync_count for test in test_objects) |
| 209 | else: |
| 210 | synch_count = 1 |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 211 | if label: |
| 212 | label = models.Label.smart_get(label) |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 213 | |
showard | 989f25d | 2008-10-01 11:38:11 +0000 | [diff] [blame] | 214 | dependencies = set(label.name for label |
| 215 | in models.Label.objects.filter(test__in=test_objects)) |
| 216 | |
showard | 2bab8f4 | 2008-11-12 18:15:22 +0000 | [diff] [blame] | 217 | cf_info = dict(is_server=is_server, synch_count=synch_count, |
| 218 | dependencies=list(dependencies)) |
| 219 | return cf_info, test_objects, profiler_objects, label |
showard | 989f25d | 2008-10-01 11:38:11 +0000 | [diff] [blame] | 220 | |
| 221 | |
| 222 | def check_job_dependencies(host_objects, job_dependencies): |
| 223 | """ |
| 224 | Check that a set of machines satisfies a job's dependencies. |
| 225 | host_objects: list of models.Host objects |
| 226 | job_dependencies: list of names of labels |
| 227 | """ |
| 228 | # check that hosts satisfy dependencies |
| 229 | host_ids = [host.id for host in host_objects] |
| 230 | hosts_in_job = models.Host.objects.filter(id__in=host_ids) |
| 231 | ok_hosts = hosts_in_job |
| 232 | for index, dependency in enumerate(job_dependencies): |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 233 | ok_hosts = ok_hosts.filter(labels__name=dependency) |
showard | 989f25d | 2008-10-01 11:38:11 +0000 | [diff] [blame] | 234 | failing_hosts = (set(host.hostname for host in host_objects) - |
| 235 | set(host.hostname for host in ok_hosts)) |
| 236 | if failing_hosts: |
| 237 | raise model_logic.ValidationError( |
Eric Li | e0493a4 | 2010-11-15 13:05:43 -0800 | [diff] [blame] | 238 | {'hosts' : 'Host(s) failed to meet job dependencies (' + |
| 239 | (', '.join(job_dependencies)) + '): ' + |
| 240 | (', '.join(failing_hosts))}) |
| 241 | |
showard | 989f25d | 2008-10-01 11:38:11 +0000 | [diff] [blame] | 242 | |
showard | 2bab8f4 | 2008-11-12 18:15:22 +0000 | [diff] [blame] | 243 | |
| 244 | def _execution_key_for(host_queue_entry): |
| 245 | return (host_queue_entry.job.id, host_queue_entry.execution_subdir) |
| 246 | |
| 247 | |
| 248 | def check_abort_synchronous_jobs(host_queue_entries): |
| 249 | # ensure user isn't aborting part of a synchronous autoserv execution |
| 250 | count_per_execution = {} |
| 251 | for queue_entry in host_queue_entries: |
| 252 | key = _execution_key_for(queue_entry) |
| 253 | count_per_execution.setdefault(key, 0) |
| 254 | count_per_execution[key] += 1 |
| 255 | |
| 256 | for queue_entry in host_queue_entries: |
| 257 | if not queue_entry.execution_subdir: |
| 258 | continue |
| 259 | execution_count = count_per_execution[_execution_key_for(queue_entry)] |
| 260 | if execution_count < queue_entry.job.synch_count: |
mbligh | 1ef218d | 2009-08-03 16:57:56 +0000 | [diff] [blame] | 261 | raise model_logic.ValidationError( |
| 262 | {'' : 'You cannot abort part of a synchronous job execution ' |
| 263 | '(%d/%s), %d included, %d expected' |
| 264 | % (queue_entry.job.id, queue_entry.execution_subdir, |
| 265 | execution_count, queue_entry.job.synch_count)}) |
showard | 8fbae65 | 2009-01-20 23:23:10 +0000 | [diff] [blame] | 266 | |
| 267 | |
showard | c92da83 | 2009-04-07 18:14:34 +0000 | [diff] [blame] | 268 | def check_atomic_group_create_job(synch_count, host_objects, metahost_objects, |
| 269 | dependencies, atomic_group, labels_by_name): |
| 270 | """ |
| 271 | Attempt to reject create_job requests with an atomic group that |
| 272 | will be impossible to schedule. The checks are not perfect but |
| 273 | should catch the most obvious issues. |
| 274 | |
| 275 | @param synch_count - The job's minimum synch count. |
| 276 | @param host_objects - A list of models.Host instances. |
| 277 | @param metahost_objects - A list of models.Label instances. |
| 278 | @param dependencies - A list of job dependency label names. |
| 279 | @param atomic_group - The models.AtomicGroup instance. |
| 280 | @param labels_by_name - A dictionary mapping label names to models.Label |
| 281 | instance. Used to look up instances for dependencies. |
| 282 | |
| 283 | @raises model_logic.ValidationError - When an issue is found. |
| 284 | """ |
| 285 | # If specific host objects were supplied with an atomic group, verify |
| 286 | # that there are enough to satisfy the synch_count. |
| 287 | minimum_required = synch_count or 1 |
| 288 | if (host_objects and not metahost_objects and |
| 289 | len(host_objects) < minimum_required): |
| 290 | raise model_logic.ValidationError( |
| 291 | {'hosts': |
| 292 | 'only %d hosts provided for job with synch_count = %d' % |
| 293 | (len(host_objects), synch_count)}) |
| 294 | |
| 295 | # Check that the atomic group has a hope of running this job |
| 296 | # given any supplied metahosts and dependancies that may limit. |
| 297 | |
| 298 | # Get a set of hostnames in the atomic group. |
| 299 | possible_hosts = set() |
| 300 | for label in atomic_group.label_set.all(): |
| 301 | possible_hosts.update(h.hostname for h in label.host_set.all()) |
| 302 | |
| 303 | # Filter out hosts that don't match all of the job dependency labels. |
| 304 | for label_name in set(dependencies): |
| 305 | label = labels_by_name[label_name] |
| 306 | hosts_in_label = (h.hostname for h in label.host_set.all()) |
| 307 | possible_hosts.intersection_update(hosts_in_label) |
| 308 | |
showard | 225bdc1 | 2009-04-13 16:09:21 +0000 | [diff] [blame] | 309 | if not host_objects and not metahost_objects: |
| 310 | # No hosts or metahosts are required to queue an atomic group Job. |
| 311 | # However, if they are given, we respect them below. |
| 312 | host_set = possible_hosts |
| 313 | else: |
| 314 | host_set = set(host.hostname for host in host_objects) |
| 315 | unusable_host_set = host_set.difference(possible_hosts) |
| 316 | if unusable_host_set: |
| 317 | raise model_logic.ValidationError( |
| 318 | {'hosts': 'Hosts "%s" are not in Atomic Group "%s"' % |
| 319 | (', '.join(sorted(unusable_host_set)), atomic_group.name)}) |
showard | c92da83 | 2009-04-07 18:14:34 +0000 | [diff] [blame] | 320 | |
| 321 | # Lookup hosts provided by each meta host and merge them into the |
| 322 | # host_set for final counting. |
| 323 | for meta_host in metahost_objects: |
| 324 | meta_possible = possible_hosts.copy() |
| 325 | hosts_in_meta_host = (h.hostname for h in meta_host.host_set.all()) |
| 326 | meta_possible.intersection_update(hosts_in_meta_host) |
| 327 | |
| 328 | # Count all hosts that this meta_host will provide. |
| 329 | host_set.update(meta_possible) |
| 330 | |
| 331 | if len(host_set) < minimum_required: |
| 332 | raise model_logic.ValidationError( |
| 333 | {'atomic_group_name': |
| 334 | 'Insufficient hosts in Atomic Group "%s" with the' |
| 335 | ' supplied dependencies and meta_hosts.' % |
| 336 | (atomic_group.name,)}) |
| 337 | |
| 338 | |
showard | be0d869 | 2009-08-20 23:42:44 +0000 | [diff] [blame] | 339 | def check_modify_host(update_data): |
| 340 | """ |
| 341 | Sanity check modify_host* requests. |
| 342 | |
| 343 | @param update_data: A dictionary with the changes to make to a host |
| 344 | or hosts. |
| 345 | """ |
| 346 | # Only the scheduler (monitor_db) is allowed to modify Host status. |
| 347 | # Otherwise race conditions happen as a hosts state is changed out from |
| 348 | # beneath tasks being run on a host. |
| 349 | if 'status' in update_data: |
| 350 | raise model_logic.ValidationError({ |
| 351 | 'status': 'Host status can not be modified by the frontend.'}) |
| 352 | |
| 353 | |
showard | ce7c092 | 2009-09-11 18:39:24 +0000 | [diff] [blame] | 354 | def check_modify_host_locking(host, update_data): |
| 355 | """ |
| 356 | Checks when locking/unlocking has been requested if the host is already |
| 357 | locked/unlocked. |
| 358 | |
| 359 | @param host: models.Host object to be modified |
| 360 | @param update_data: A dictionary with the changes to make to the host. |
| 361 | """ |
| 362 | locked = update_data.get('locked', None) |
| 363 | if locked is not None: |
| 364 | if locked and host.locked: |
| 365 | raise model_logic.ValidationError({ |
| 366 | 'locked': 'Host already locked by %s on %s.' % |
| 367 | (host.locked_by, host.lock_time)}) |
| 368 | if not locked and not host.locked: |
| 369 | raise model_logic.ValidationError({ |
| 370 | 'locked': 'Host already unlocked.'}) |
| 371 | |
| 372 | |
showard | 8fbae65 | 2009-01-20 23:23:10 +0000 | [diff] [blame] | 373 | def get_motd(): |
| 374 | dirname = os.path.dirname(__file__) |
| 375 | filename = os.path.join(dirname, "..", "..", "motd.txt") |
| 376 | text = '' |
| 377 | try: |
| 378 | fp = open(filename, "r") |
| 379 | try: |
| 380 | text = fp.read() |
| 381 | finally: |
| 382 | fp.close() |
| 383 | except: |
| 384 | pass |
| 385 | |
| 386 | return text |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 387 | |
| 388 | |
| 389 | def _get_metahost_counts(metahost_objects): |
| 390 | metahost_counts = {} |
| 391 | for metahost in metahost_objects: |
| 392 | metahost_counts.setdefault(metahost, 0) |
| 393 | metahost_counts[metahost] += 1 |
| 394 | return metahost_counts |
| 395 | |
| 396 | |
showard | a965cef | 2009-05-15 23:17:41 +0000 | [diff] [blame] | 397 | def get_job_info(job, preserve_metahosts=False, queue_entry_filter_data=None): |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 398 | hosts = [] |
| 399 | one_time_hosts = [] |
| 400 | meta_hosts = [] |
| 401 | atomic_group = None |
jamesren | 2275ef1 | 2010-04-12 18:25:06 +0000 | [diff] [blame] | 402 | hostless = False |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 403 | |
showard | 4d07756 | 2009-05-08 18:24:36 +0000 | [diff] [blame] | 404 | queue_entries = job.hostqueueentry_set.all() |
showard | a965cef | 2009-05-15 23:17:41 +0000 | [diff] [blame] | 405 | if queue_entry_filter_data: |
| 406 | queue_entries = models.HostQueueEntry.query_objects( |
| 407 | queue_entry_filter_data, initial_query=queue_entries) |
showard | 4d07756 | 2009-05-08 18:24:36 +0000 | [diff] [blame] | 408 | |
| 409 | for queue_entry in queue_entries: |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 410 | if (queue_entry.host and (preserve_metahosts or |
| 411 | not queue_entry.meta_host)): |
| 412 | if queue_entry.deleted: |
| 413 | continue |
| 414 | if queue_entry.host.invalid: |
| 415 | one_time_hosts.append(queue_entry.host) |
| 416 | else: |
| 417 | hosts.append(queue_entry.host) |
jamesren | 2275ef1 | 2010-04-12 18:25:06 +0000 | [diff] [blame] | 418 | elif queue_entry.meta_host: |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 419 | meta_hosts.append(queue_entry.meta_host) |
jamesren | 2275ef1 | 2010-04-12 18:25:06 +0000 | [diff] [blame] | 420 | else: |
| 421 | hostless = True |
| 422 | |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 423 | if atomic_group is None: |
| 424 | if queue_entry.atomic_group is not None: |
| 425 | atomic_group = queue_entry.atomic_group |
| 426 | else: |
| 427 | assert atomic_group.name == queue_entry.atomic_group.name, ( |
| 428 | 'DB inconsistency. HostQueueEntries with multiple atomic' |
| 429 | ' groups on job %s: %s != %s' % ( |
| 430 | id, atomic_group.name, queue_entry.atomic_group.name)) |
| 431 | |
| 432 | meta_host_counts = _get_metahost_counts(meta_hosts) |
| 433 | |
| 434 | info = dict(dependencies=[label.name for label |
| 435 | in job.dependency_labels.all()], |
| 436 | hosts=hosts, |
| 437 | meta_hosts=meta_hosts, |
| 438 | meta_host_counts=meta_host_counts, |
| 439 | one_time_hosts=one_time_hosts, |
jamesren | 2275ef1 | 2010-04-12 18:25:06 +0000 | [diff] [blame] | 440 | atomic_group=atomic_group, |
| 441 | hostless=hostless) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 442 | return info |
| 443 | |
| 444 | |
showard | 09d80f9 | 2009-11-19 01:01:19 +0000 | [diff] [blame] | 445 | def check_for_duplicate_hosts(host_objects): |
| 446 | host_ids = set() |
| 447 | duplicate_hostnames = set() |
| 448 | for host in host_objects: |
| 449 | if host.id in host_ids: |
| 450 | duplicate_hostnames.add(host.hostname) |
| 451 | host_ids.add(host.id) |
| 452 | |
| 453 | if duplicate_hostnames: |
| 454 | raise model_logic.ValidationError( |
| 455 | {'hosts' : 'Duplicate hosts: %s' |
| 456 | % ', '.join(duplicate_hostnames)}) |
| 457 | |
| 458 | |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 459 | def create_new_job(owner, options, host_objects, metahost_objects, |
| 460 | atomic_group=None): |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 461 | labels_by_name = dict((label.name, label) |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 462 | for label in models.Label.objects.all()) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 463 | all_host_objects = host_objects + metahost_objects |
| 464 | metahost_counts = _get_metahost_counts(metahost_objects) |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 465 | dependencies = options.get('dependencies', []) |
| 466 | synch_count = options.get('synch_count') |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 467 | |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 468 | if atomic_group: |
| 469 | check_atomic_group_create_job( |
| 470 | synch_count, host_objects, metahost_objects, |
| 471 | dependencies, atomic_group, labels_by_name) |
| 472 | else: |
| 473 | if synch_count is not None and synch_count > len(all_host_objects): |
| 474 | raise model_logic.ValidationError( |
| 475 | {'hosts': |
| 476 | 'only %d hosts provided for job with synch_count = %d' % |
| 477 | (len(all_host_objects), synch_count)}) |
| 478 | atomic_hosts = models.Host.objects.filter( |
| 479 | id__in=[host.id for host in host_objects], |
| 480 | labels__atomic_group=True) |
| 481 | unusable_host_names = [host.hostname for host in atomic_hosts] |
| 482 | if unusable_host_names: |
| 483 | raise model_logic.ValidationError( |
| 484 | {'hosts': |
| 485 | 'Host(s) "%s" are atomic group hosts but no ' |
| 486 | 'atomic group was specified for this job.' % |
| 487 | (', '.join(unusable_host_names),)}) |
| 488 | |
showard | 09d80f9 | 2009-11-19 01:01:19 +0000 | [diff] [blame] | 489 | check_for_duplicate_hosts(host_objects) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 490 | |
| 491 | check_job_dependencies(host_objects, dependencies) |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 492 | options['dependencies'] = [labels_by_name[label_name] |
| 493 | for label_name in dependencies] |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 494 | |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 495 | for label in metahost_objects + options['dependencies']: |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 496 | if label.atomic_group and not atomic_group: |
| 497 | raise model_logic.ValidationError( |
| 498 | {'atomic_group_name': |
showard | c873032 | 2009-06-30 01:56:38 +0000 | [diff] [blame] | 499 | 'Dependency %r requires an atomic group but no ' |
| 500 | 'atomic_group_name or meta_host in an atomic group was ' |
| 501 | 'specified for this job.' % label.name}) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 502 | elif (label.atomic_group and |
| 503 | label.atomic_group.name != atomic_group.name): |
| 504 | raise model_logic.ValidationError( |
| 505 | {'atomic_group_name': |
showard | c873032 | 2009-06-30 01:56:38 +0000 | [diff] [blame] | 506 | 'meta_hosts or dependency %r requires atomic group ' |
| 507 | '%r instead of the supplied atomic_group_name=%r.' % |
| 508 | (label.name, label.atomic_group.name, atomic_group.name)}) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 509 | |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 510 | job = models.Job.create(owner=owner, options=options, |
| 511 | hosts=all_host_objects) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 512 | job.queue(all_host_objects, atomic_group=atomic_group, |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 513 | is_template=options.get('is_template', False)) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 514 | return job.id |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 515 | |
| 516 | |
showard | 909c914 | 2009-07-07 20:54:42 +0000 | [diff] [blame] | 517 | def find_platform_and_atomic_group(host): |
| 518 | """ |
| 519 | Figure out the platform name and atomic group name for the given host |
| 520 | object. If none, the return value for either will be None. |
| 521 | |
| 522 | @returns (platform name, atomic group name) for the given host. |
| 523 | """ |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 524 | platforms = [label.name for label in host.label_list if label.platform] |
| 525 | if not platforms: |
showard | 909c914 | 2009-07-07 20:54:42 +0000 | [diff] [blame] | 526 | platform = None |
| 527 | else: |
| 528 | platform = platforms[0] |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 529 | if len(platforms) > 1: |
| 530 | raise ValueError('Host %s has more than one platform: %s' % |
| 531 | (host.hostname, ', '.join(platforms))) |
showard | 909c914 | 2009-07-07 20:54:42 +0000 | [diff] [blame] | 532 | for label in host.label_list: |
| 533 | if label.atomic_group: |
| 534 | atomic_group_name = label.atomic_group.name |
| 535 | break |
| 536 | else: |
| 537 | atomic_group_name = None |
| 538 | # Don't check for multiple atomic groups on a host here. That is an |
| 539 | # error but should not trip up the RPC interface. monitor_db_cleanup |
| 540 | # deals with it. This just returns the first one found. |
| 541 | return platform, atomic_group_name |
showard | c0ac3a7 | 2009-07-08 21:14:45 +0000 | [diff] [blame] | 542 | |
| 543 | |
| 544 | # support for get_host_queue_entries_and_special_tasks() |
| 545 | |
| 546 | def _common_entry_to_dict(entry, type, job_dict): |
| 547 | return dict(type=type, |
| 548 | host=entry.host.get_object_dict(), |
| 549 | job=job_dict, |
| 550 | execution_path=entry.execution_path(), |
| 551 | status=entry.status, |
| 552 | started_on=entry.started_on, |
showard | 8fb1fde | 2009-07-11 01:47:16 +0000 | [diff] [blame] | 553 | id=str(entry.id) + type) |
showard | c0ac3a7 | 2009-07-08 21:14:45 +0000 | [diff] [blame] | 554 | |
| 555 | |
| 556 | def _special_task_to_dict(special_task): |
| 557 | job_dict = None |
| 558 | if special_task.queue_entry: |
| 559 | job_dict = special_task.queue_entry.job.get_object_dict() |
| 560 | return _common_entry_to_dict(special_task, special_task.task, job_dict) |
| 561 | |
| 562 | |
| 563 | def _queue_entry_to_dict(queue_entry): |
| 564 | return _common_entry_to_dict(queue_entry, 'Job', |
| 565 | queue_entry.job.get_object_dict()) |
| 566 | |
| 567 | |
| 568 | def _compute_next_job_for_tasks(queue_entries, special_tasks): |
| 569 | """ |
| 570 | For each task, try to figure out the next job that ran after that task. |
| 571 | This is done using two pieces of information: |
| 572 | * if the task has a queue entry, we can use that entry's job ID. |
| 573 | * if the task has a time_started, we can try to compare that against the |
| 574 | started_on field of queue_entries. this isn't guaranteed to work perfectly |
| 575 | since queue_entries may also have null started_on values. |
| 576 | * if the task has neither, or if use of time_started fails, just use the |
| 577 | last computed job ID. |
| 578 | """ |
| 579 | next_job_id = None # most recently computed next job |
| 580 | hqe_index = 0 # index for scanning by started_on times |
| 581 | for task in special_tasks: |
| 582 | if task.queue_entry: |
| 583 | next_job_id = task.queue_entry.job.id |
| 584 | elif task.time_started is not None: |
| 585 | for queue_entry in queue_entries[hqe_index:]: |
| 586 | if queue_entry.started_on is None: |
| 587 | continue |
| 588 | if queue_entry.started_on < task.time_started: |
| 589 | break |
| 590 | next_job_id = queue_entry.job.id |
| 591 | |
| 592 | task.next_job_id = next_job_id |
| 593 | |
| 594 | # advance hqe_index to just after next_job_id |
| 595 | if next_job_id is not None: |
| 596 | for queue_entry in queue_entries[hqe_index:]: |
| 597 | if queue_entry.job.id < next_job_id: |
| 598 | break |
| 599 | hqe_index += 1 |
| 600 | |
| 601 | |
| 602 | def interleave_entries(queue_entries, special_tasks): |
| 603 | """ |
| 604 | Both lists should be ordered by descending ID. |
| 605 | """ |
| 606 | _compute_next_job_for_tasks(queue_entries, special_tasks) |
| 607 | |
| 608 | # start with all special tasks that've run since the last job |
| 609 | interleaved_entries = [] |
| 610 | for task in special_tasks: |
| 611 | if task.next_job_id is not None: |
| 612 | break |
| 613 | interleaved_entries.append(_special_task_to_dict(task)) |
| 614 | |
| 615 | # now interleave queue entries with the remaining special tasks |
| 616 | special_task_index = len(interleaved_entries) |
| 617 | for queue_entry in queue_entries: |
| 618 | interleaved_entries.append(_queue_entry_to_dict(queue_entry)) |
| 619 | # add all tasks that ran between this job and the previous one |
| 620 | for task in special_tasks[special_task_index:]: |
| 621 | if task.next_job_id < queue_entry.job.id: |
| 622 | break |
| 623 | interleaved_entries.append(_special_task_to_dict(task)) |
| 624 | special_task_index += 1 |
| 625 | |
| 626 | return interleaved_entries |
jamesren | 4a41e01 | 2010-07-16 22:33:48 +0000 | [diff] [blame] | 627 | |
| 628 | |
| 629 | def get_create_job_common_args(local_args): |
| 630 | """ |
| 631 | Returns a dict containing only the args that apply for create_job_common |
| 632 | |
| 633 | Returns a subset of local_args, which contains only the arguments that can |
| 634 | be passed in to create_job_common(). |
| 635 | """ |
| 636 | arg_names, _, _, _ = inspect.getargspec(create_job_common) |
| 637 | return dict(item for item in local_args.iteritems() if item[0] in arg_names) |
| 638 | |
| 639 | |
| 640 | def create_job_common(name, priority, control_type, control_file=None, |
| 641 | hosts=(), meta_hosts=(), one_time_hosts=(), |
| 642 | atomic_group_name=None, synch_count=None, |
Simran Basi | 3421702 | 2012-11-06 13:43:15 -0800 | [diff] [blame] | 643 | is_template=False, timeout=None, max_runtime_mins=None, |
jamesren | 4a41e01 | 2010-07-16 22:33:48 +0000 | [diff] [blame] | 644 | run_verify=True, email_list='', dependencies=(), |
| 645 | reboot_before=None, reboot_after=None, |
| 646 | parse_failed_repair=None, hostless=False, keyvals=None, |
Aviv Keshet | 1830892 | 2013-02-19 17:49:49 -0800 | [diff] [blame^] | 647 | drone_set=None, parameterized_job=None, |
| 648 | parent_job_id=None): |
| 649 | #pylint: disable-msg=C0111 |
jamesren | 4a41e01 | 2010-07-16 22:33:48 +0000 | [diff] [blame] | 650 | """ |
| 651 | Common code between creating "standard" jobs and creating parameterized jobs |
| 652 | """ |
| 653 | user = models.User.current_user() |
| 654 | owner = user.login |
| 655 | |
| 656 | # Convert metahost names to lower case, to avoid case sensitivity issues |
| 657 | meta_hosts = [meta_host.lower() for meta_host in meta_hosts] |
| 658 | |
| 659 | # input validation |
| 660 | if not (hosts or meta_hosts or one_time_hosts or atomic_group_name |
| 661 | or hostless): |
| 662 | raise model_logic.ValidationError({ |
| 663 | 'arguments' : "You must pass at least one of 'hosts', " |
| 664 | "'meta_hosts', 'one_time_hosts', " |
| 665 | "'atomic_group_name', or 'hostless'" |
| 666 | }) |
| 667 | |
| 668 | if hostless: |
| 669 | if hosts or meta_hosts or one_time_hosts or atomic_group_name: |
| 670 | raise model_logic.ValidationError({ |
| 671 | 'hostless': 'Hostless jobs cannot include any hosts!'}) |
| 672 | server_type = models.Job.ControlType.get_string( |
| 673 | models.Job.ControlType.SERVER) |
| 674 | if control_type != server_type: |
| 675 | raise model_logic.ValidationError({ |
| 676 | 'control_type': 'Hostless jobs cannot use client-side ' |
| 677 | 'control files'}) |
| 678 | |
| 679 | labels_by_name = dict((label.name.lower(), label) |
| 680 | for label in models.Label.objects.all()) |
| 681 | atomic_groups_by_name = dict((ag.name.lower(), ag) |
| 682 | for ag in models.AtomicGroup.objects.all()) |
| 683 | |
| 684 | # Schedule on an atomic group automagically if one of the labels given |
| 685 | # is an atomic group label and no explicit atomic_group_name was supplied. |
| 686 | if not atomic_group_name: |
| 687 | for label_name in meta_hosts or []: |
| 688 | label = labels_by_name.get(label_name) |
| 689 | if label and label.atomic_group: |
| 690 | atomic_group_name = label.atomic_group.name |
| 691 | break |
| 692 | |
| 693 | # convert hostnames & meta hosts to host/label objects |
| 694 | host_objects = models.Host.smart_get_bulk(hosts) |
| 695 | metahost_objects = [] |
| 696 | for label_name in meta_hosts or []: |
| 697 | if label_name in labels_by_name: |
| 698 | label = labels_by_name[label_name] |
| 699 | metahost_objects.append(label) |
| 700 | elif label_name in atomic_groups_by_name: |
| 701 | # If given a metahost name that isn't a Label, check to |
| 702 | # see if the user was specifying an Atomic Group instead. |
| 703 | atomic_group = atomic_groups_by_name[label_name] |
| 704 | if atomic_group_name and atomic_group_name != atomic_group.name: |
| 705 | raise model_logic.ValidationError({ |
| 706 | 'meta_hosts': ( |
| 707 | 'Label "%s" not found. If assumed to be an ' |
| 708 | 'atomic group it would conflict with the ' |
| 709 | 'supplied atomic group "%s".' % ( |
| 710 | label_name, atomic_group_name))}) |
| 711 | atomic_group_name = atomic_group.name |
| 712 | else: |
| 713 | raise model_logic.ValidationError( |
| 714 | {'meta_hosts' : 'Label "%s" not found' % label_name}) |
| 715 | |
| 716 | # Create and sanity check an AtomicGroup object if requested. |
| 717 | if atomic_group_name: |
| 718 | if one_time_hosts: |
| 719 | raise model_logic.ValidationError( |
| 720 | {'one_time_hosts': |
| 721 | 'One time hosts cannot be used with an Atomic Group.'}) |
| 722 | atomic_group = models.AtomicGroup.smart_get(atomic_group_name) |
| 723 | if synch_count and synch_count > atomic_group.max_number_of_machines: |
| 724 | raise model_logic.ValidationError( |
| 725 | {'atomic_group_name' : |
| 726 | 'You have requested a synch_count (%d) greater than the ' |
| 727 | 'maximum machines in the requested Atomic Group (%d).' % |
| 728 | (synch_count, atomic_group.max_number_of_machines)}) |
| 729 | else: |
| 730 | atomic_group = None |
| 731 | |
| 732 | for host in one_time_hosts or []: |
| 733 | this_host = models.Host.create_one_time_host(host) |
| 734 | host_objects.append(this_host) |
| 735 | |
| 736 | options = dict(name=name, |
| 737 | priority=priority, |
| 738 | control_file=control_file, |
| 739 | control_type=control_type, |
| 740 | is_template=is_template, |
| 741 | timeout=timeout, |
Simran Basi | 3421702 | 2012-11-06 13:43:15 -0800 | [diff] [blame] | 742 | max_runtime_mins=max_runtime_mins, |
jamesren | 4a41e01 | 2010-07-16 22:33:48 +0000 | [diff] [blame] | 743 | synch_count=synch_count, |
| 744 | run_verify=run_verify, |
| 745 | email_list=email_list, |
| 746 | dependencies=dependencies, |
| 747 | reboot_before=reboot_before, |
| 748 | reboot_after=reboot_after, |
| 749 | parse_failed_repair=parse_failed_repair, |
| 750 | keyvals=keyvals, |
| 751 | drone_set=drone_set, |
Aviv Keshet | 1830892 | 2013-02-19 17:49:49 -0800 | [diff] [blame^] | 752 | parameterized_job=parameterized_job, |
| 753 | parent_job_id=parent_job_id) |
jamesren | 4a41e01 | 2010-07-16 22:33:48 +0000 | [diff] [blame] | 754 | return create_new_job(owner=owner, |
| 755 | options=options, |
| 756 | host_objects=host_objects, |
| 757 | metahost_objects=metahost_objects, |
| 758 | atomic_group=atomic_group) |