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