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 | |
showard | 14374b1 | 2009-01-31 00:11:54 +0000 | [diff] [blame] | 8 | import datetime, os |
showard | 3d6ae11 | 2009-05-02 00:45:48 +0000 | [diff] [blame] | 9 | import django.http |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 10 | from autotest_lib.frontend.afe import models, model_logic |
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 | |
| 103 | not_queued = ('(SELECT job_id FROM host_queue_entries WHERE status != "%s")' |
| 104 | % models.HostQueueEntry.Status.QUEUED) |
| 105 | not_finished = '(SELECT job_id FROM host_queue_entries WHERE not complete)' |
| 106 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 107 | if not_yet_run: |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 108 | where = ['id NOT IN ' + not_queued] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 109 | elif running: |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 110 | where = ['(id IN %s) AND (id IN %s)' % (not_queued, not_finished)] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 111 | elif finished: |
showard | 6c65d25 | 2009-10-01 18:45:22 +0000 | [diff] [blame] | 112 | where = ['id NOT IN ' + not_finished] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 113 | else: |
showard | 10f4167 | 2009-05-13 21:28:25 +0000 | [diff] [blame] | 114 | return {} |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 115 | return {'where': where} |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 116 | |
| 117 | |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 118 | def extra_host_filters(multiple_labels=()): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 119 | """\ |
| 120 | Generate SQL WHERE clauses for matching hosts in an intersection of |
| 121 | labels. |
| 122 | """ |
| 123 | extra_args = {} |
| 124 | where_str = ('hosts.id in (select host_id from hosts_labels ' |
| 125 | 'where label_id=%s)') |
| 126 | extra_args['where'] = [where_str] * len(multiple_labels) |
| 127 | extra_args['params'] = [models.Label.smart_get(label).id |
| 128 | for label in multiple_labels] |
| 129 | return extra_args |
showard | 8e3aa5e | 2008-04-08 19:42:32 +0000 | [diff] [blame] | 130 | |
| 131 | |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 132 | def get_host_query(multiple_labels, exclude_only_if_needed_labels, |
showard | 8aa84fc | 2009-09-16 17:17:55 +0000 | [diff] [blame] | 133 | exclude_atomic_group_hosts, valid_only, filter_data): |
| 134 | if valid_only: |
| 135 | query = models.Host.valid_objects.all() |
| 136 | else: |
| 137 | query = models.Host.objects.all() |
| 138 | |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 139 | if exclude_only_if_needed_labels: |
| 140 | only_if_needed_labels = models.Label.valid_objects.filter( |
| 141 | only_if_needed=True) |
showard | f7eac6f | 2008-11-13 21:18:01 +0000 | [diff] [blame] | 142 | if only_if_needed_labels.count() > 0: |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 143 | only_if_needed_ids = ','.join( |
| 144 | str(label['id']) |
| 145 | for label in only_if_needed_labels.values('id')) |
showard | f7eac6f | 2008-11-13 21:18:01 +0000 | [diff] [blame] | 146 | query = models.Host.objects.add_join( |
| 147 | query, 'hosts_labels', join_key='host_id', |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 148 | join_condition=('hosts_labels_exclude_OIN.label_id IN (%s)' |
| 149 | % only_if_needed_ids), |
| 150 | suffix='_exclude_OIN', exclude=True) |
showard | 8aa84fc | 2009-09-16 17:17:55 +0000 | [diff] [blame] | 151 | |
showard | 87cc38f | 2009-08-20 23:37:04 +0000 | [diff] [blame] | 152 | if exclude_atomic_group_hosts: |
| 153 | atomic_group_labels = models.Label.valid_objects.filter( |
| 154 | atomic_group__isnull=False) |
| 155 | if atomic_group_labels.count() > 0: |
| 156 | atomic_group_label_ids = ','.join( |
| 157 | str(atomic_group['id']) |
| 158 | for atomic_group in atomic_group_labels.values('id')) |
| 159 | query = models.Host.objects.add_join( |
| 160 | query, 'hosts_labels', join_key='host_id', |
| 161 | join_condition=('hosts_labels_exclude_AG.label_id IN (%s)' |
| 162 | % atomic_group_label_ids), |
| 163 | suffix='_exclude_AG', exclude=True) |
showard | 8aa84fc | 2009-09-16 17:17:55 +0000 | [diff] [blame] | 164 | |
| 165 | assert 'extra_args' not in filter_data |
| 166 | filter_data['extra_args'] = extra_host_filters(multiple_labels) |
showard | 43a3d26 | 2008-11-12 18:17:05 +0000 | [diff] [blame] | 167 | return models.Host.query_objects(filter_data, initial_query=query) |
| 168 | |
| 169 | |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 170 | class InconsistencyException(Exception): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 171 | 'Raised when a list of objects does not have a consistent value' |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 172 | |
| 173 | |
| 174 | def get_consistent_value(objects, field): |
mbligh | c5ddfd1 | 2008-08-04 17:15:00 +0000 | [diff] [blame] | 175 | if not objects: |
| 176 | # well a list of nothing is consistent |
| 177 | return None |
| 178 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 179 | value = getattr(objects[0], field) |
| 180 | for obj in objects: |
| 181 | this_value = getattr(obj, field) |
| 182 | if this_value != value: |
| 183 | raise InconsistencyException(objects[0], obj) |
| 184 | return value |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 185 | |
| 186 | |
showard | 2b9a88b | 2008-06-13 20:55:03 +0000 | [diff] [blame] | 187 | def prepare_generate_control_file(tests, kernel, label, profilers): |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 188 | test_objects = [models.Test.smart_get(test) for test in tests] |
showard | 2b9a88b | 2008-06-13 20:55:03 +0000 | [diff] [blame] | 189 | profiler_objects = [models.Profiler.smart_get(profiler) |
| 190 | for profiler in profilers] |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 191 | # ensure tests are all the same type |
| 192 | try: |
| 193 | test_type = get_consistent_value(test_objects, 'test_type') |
| 194 | except InconsistencyException, exc: |
| 195 | test1, test2 = exc.args |
mbligh | ec5546d | 2008-06-16 16:51:28 +0000 | [diff] [blame] | 196 | raise model_logic.ValidationError( |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 197 | {'tests' : 'You cannot run both server- and client-side ' |
| 198 | 'tests together (tests %s and %s differ' % ( |
| 199 | test1.name, test2.name)}) |
showard | 8fd5824 | 2008-03-10 21:29:07 +0000 | [diff] [blame] | 200 | |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 201 | is_server = (test_type == models.Test.Types.SERVER) |
showard | 14374b1 | 2009-01-31 00:11:54 +0000 | [diff] [blame] | 202 | if test_objects: |
| 203 | synch_count = max(test.sync_count for test in test_objects) |
| 204 | else: |
| 205 | synch_count = 1 |
jadmanski | 0afbb63 | 2008-06-06 21:10:57 +0000 | [diff] [blame] | 206 | if label: |
| 207 | label = models.Label.smart_get(label) |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 208 | |
showard | 989f25d | 2008-10-01 11:38:11 +0000 | [diff] [blame] | 209 | dependencies = set(label.name for label |
| 210 | in models.Label.objects.filter(test__in=test_objects)) |
| 211 | |
showard | 2bab8f4 | 2008-11-12 18:15:22 +0000 | [diff] [blame] | 212 | cf_info = dict(is_server=is_server, synch_count=synch_count, |
| 213 | dependencies=list(dependencies)) |
| 214 | return cf_info, test_objects, profiler_objects, label |
showard | 989f25d | 2008-10-01 11:38:11 +0000 | [diff] [blame] | 215 | |
| 216 | |
| 217 | def check_job_dependencies(host_objects, job_dependencies): |
| 218 | """ |
| 219 | Check that a set of machines satisfies a job's dependencies. |
| 220 | host_objects: list of models.Host objects |
| 221 | job_dependencies: list of names of labels |
| 222 | """ |
| 223 | # check that hosts satisfy dependencies |
| 224 | host_ids = [host.id for host in host_objects] |
| 225 | hosts_in_job = models.Host.objects.filter(id__in=host_ids) |
| 226 | ok_hosts = hosts_in_job |
| 227 | for index, dependency in enumerate(job_dependencies): |
showard | a5288b4 | 2009-07-28 20:06:08 +0000 | [diff] [blame] | 228 | ok_hosts = ok_hosts.filter(labels__name=dependency) |
showard | 989f25d | 2008-10-01 11:38:11 +0000 | [diff] [blame] | 229 | failing_hosts = (set(host.hostname for host in host_objects) - |
| 230 | set(host.hostname for host in ok_hosts)) |
| 231 | if failing_hosts: |
| 232 | raise model_logic.ValidationError( |
| 233 | {'hosts' : 'Host(s) failed to meet job dependencies: ' + |
| 234 | ', '.join(failing_hosts)}) |
| 235 | |
showard | 2bab8f4 | 2008-11-12 18:15:22 +0000 | [diff] [blame] | 236 | |
| 237 | def _execution_key_for(host_queue_entry): |
| 238 | return (host_queue_entry.job.id, host_queue_entry.execution_subdir) |
| 239 | |
| 240 | |
| 241 | def check_abort_synchronous_jobs(host_queue_entries): |
| 242 | # ensure user isn't aborting part of a synchronous autoserv execution |
| 243 | count_per_execution = {} |
| 244 | for queue_entry in host_queue_entries: |
| 245 | key = _execution_key_for(queue_entry) |
| 246 | count_per_execution.setdefault(key, 0) |
| 247 | count_per_execution[key] += 1 |
| 248 | |
| 249 | for queue_entry in host_queue_entries: |
| 250 | if not queue_entry.execution_subdir: |
| 251 | continue |
| 252 | execution_count = count_per_execution[_execution_key_for(queue_entry)] |
| 253 | if execution_count < queue_entry.job.synch_count: |
mbligh | 1ef218d | 2009-08-03 16:57:56 +0000 | [diff] [blame] | 254 | raise model_logic.ValidationError( |
| 255 | {'' : 'You cannot abort part of a synchronous job execution ' |
| 256 | '(%d/%s), %d included, %d expected' |
| 257 | % (queue_entry.job.id, queue_entry.execution_subdir, |
| 258 | execution_count, queue_entry.job.synch_count)}) |
showard | 8fbae65 | 2009-01-20 23:23:10 +0000 | [diff] [blame] | 259 | |
| 260 | |
showard | c92da83 | 2009-04-07 18:14:34 +0000 | [diff] [blame] | 261 | def check_atomic_group_create_job(synch_count, host_objects, metahost_objects, |
| 262 | dependencies, atomic_group, labels_by_name): |
| 263 | """ |
| 264 | Attempt to reject create_job requests with an atomic group that |
| 265 | will be impossible to schedule. The checks are not perfect but |
| 266 | should catch the most obvious issues. |
| 267 | |
| 268 | @param synch_count - The job's minimum synch count. |
| 269 | @param host_objects - A list of models.Host instances. |
| 270 | @param metahost_objects - A list of models.Label instances. |
| 271 | @param dependencies - A list of job dependency label names. |
| 272 | @param atomic_group - The models.AtomicGroup instance. |
| 273 | @param labels_by_name - A dictionary mapping label names to models.Label |
| 274 | instance. Used to look up instances for dependencies. |
| 275 | |
| 276 | @raises model_logic.ValidationError - When an issue is found. |
| 277 | """ |
| 278 | # If specific host objects were supplied with an atomic group, verify |
| 279 | # that there are enough to satisfy the synch_count. |
| 280 | minimum_required = synch_count or 1 |
| 281 | if (host_objects and not metahost_objects and |
| 282 | len(host_objects) < minimum_required): |
| 283 | raise model_logic.ValidationError( |
| 284 | {'hosts': |
| 285 | 'only %d hosts provided for job with synch_count = %d' % |
| 286 | (len(host_objects), synch_count)}) |
| 287 | |
| 288 | # Check that the atomic group has a hope of running this job |
| 289 | # given any supplied metahosts and dependancies that may limit. |
| 290 | |
| 291 | # Get a set of hostnames in the atomic group. |
| 292 | possible_hosts = set() |
| 293 | for label in atomic_group.label_set.all(): |
| 294 | possible_hosts.update(h.hostname for h in label.host_set.all()) |
| 295 | |
| 296 | # Filter out hosts that don't match all of the job dependency labels. |
| 297 | for label_name in set(dependencies): |
| 298 | label = labels_by_name[label_name] |
| 299 | hosts_in_label = (h.hostname for h in label.host_set.all()) |
| 300 | possible_hosts.intersection_update(hosts_in_label) |
| 301 | |
showard | 225bdc1 | 2009-04-13 16:09:21 +0000 | [diff] [blame] | 302 | if not host_objects and not metahost_objects: |
| 303 | # No hosts or metahosts are required to queue an atomic group Job. |
| 304 | # However, if they are given, we respect them below. |
| 305 | host_set = possible_hosts |
| 306 | else: |
| 307 | host_set = set(host.hostname for host in host_objects) |
| 308 | unusable_host_set = host_set.difference(possible_hosts) |
| 309 | if unusable_host_set: |
| 310 | raise model_logic.ValidationError( |
| 311 | {'hosts': 'Hosts "%s" are not in Atomic Group "%s"' % |
| 312 | (', '.join(sorted(unusable_host_set)), atomic_group.name)}) |
showard | c92da83 | 2009-04-07 18:14:34 +0000 | [diff] [blame] | 313 | |
| 314 | # Lookup hosts provided by each meta host and merge them into the |
| 315 | # host_set for final counting. |
| 316 | for meta_host in metahost_objects: |
| 317 | meta_possible = possible_hosts.copy() |
| 318 | hosts_in_meta_host = (h.hostname for h in meta_host.host_set.all()) |
| 319 | meta_possible.intersection_update(hosts_in_meta_host) |
| 320 | |
| 321 | # Count all hosts that this meta_host will provide. |
| 322 | host_set.update(meta_possible) |
| 323 | |
| 324 | if len(host_set) < minimum_required: |
| 325 | raise model_logic.ValidationError( |
| 326 | {'atomic_group_name': |
| 327 | 'Insufficient hosts in Atomic Group "%s" with the' |
| 328 | ' supplied dependencies and meta_hosts.' % |
| 329 | (atomic_group.name,)}) |
| 330 | |
| 331 | |
showard | be0d869 | 2009-08-20 23:42:44 +0000 | [diff] [blame] | 332 | def check_modify_host(update_data): |
| 333 | """ |
| 334 | Sanity check modify_host* requests. |
| 335 | |
| 336 | @param update_data: A dictionary with the changes to make to a host |
| 337 | or hosts. |
| 338 | """ |
| 339 | # Only the scheduler (monitor_db) is allowed to modify Host status. |
| 340 | # Otherwise race conditions happen as a hosts state is changed out from |
| 341 | # beneath tasks being run on a host. |
| 342 | if 'status' in update_data: |
| 343 | raise model_logic.ValidationError({ |
| 344 | 'status': 'Host status can not be modified by the frontend.'}) |
| 345 | |
| 346 | |
showard | ce7c092 | 2009-09-11 18:39:24 +0000 | [diff] [blame] | 347 | def check_modify_host_locking(host, update_data): |
| 348 | """ |
| 349 | Checks when locking/unlocking has been requested if the host is already |
| 350 | locked/unlocked. |
| 351 | |
| 352 | @param host: models.Host object to be modified |
| 353 | @param update_data: A dictionary with the changes to make to the host. |
| 354 | """ |
| 355 | locked = update_data.get('locked', None) |
| 356 | if locked is not None: |
| 357 | if locked and host.locked: |
| 358 | raise model_logic.ValidationError({ |
| 359 | 'locked': 'Host already locked by %s on %s.' % |
| 360 | (host.locked_by, host.lock_time)}) |
| 361 | if not locked and not host.locked: |
| 362 | raise model_logic.ValidationError({ |
| 363 | 'locked': 'Host already unlocked.'}) |
| 364 | |
| 365 | |
showard | 8fbae65 | 2009-01-20 23:23:10 +0000 | [diff] [blame] | 366 | def get_motd(): |
| 367 | dirname = os.path.dirname(__file__) |
| 368 | filename = os.path.join(dirname, "..", "..", "motd.txt") |
| 369 | text = '' |
| 370 | try: |
| 371 | fp = open(filename, "r") |
| 372 | try: |
| 373 | text = fp.read() |
| 374 | finally: |
| 375 | fp.close() |
| 376 | except: |
| 377 | pass |
| 378 | |
| 379 | return text |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 380 | |
| 381 | |
| 382 | def _get_metahost_counts(metahost_objects): |
| 383 | metahost_counts = {} |
| 384 | for metahost in metahost_objects: |
| 385 | metahost_counts.setdefault(metahost, 0) |
| 386 | metahost_counts[metahost] += 1 |
| 387 | return metahost_counts |
| 388 | |
| 389 | |
showard | a965cef | 2009-05-15 23:17:41 +0000 | [diff] [blame] | 390 | def get_job_info(job, preserve_metahosts=False, queue_entry_filter_data=None): |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 391 | hosts = [] |
| 392 | one_time_hosts = [] |
| 393 | meta_hosts = [] |
| 394 | atomic_group = None |
| 395 | |
showard | 4d07756 | 2009-05-08 18:24:36 +0000 | [diff] [blame] | 396 | queue_entries = job.hostqueueentry_set.all() |
showard | a965cef | 2009-05-15 23:17:41 +0000 | [diff] [blame] | 397 | if queue_entry_filter_data: |
| 398 | queue_entries = models.HostQueueEntry.query_objects( |
| 399 | queue_entry_filter_data, initial_query=queue_entries) |
showard | 4d07756 | 2009-05-08 18:24:36 +0000 | [diff] [blame] | 400 | |
| 401 | for queue_entry in queue_entries: |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 402 | if (queue_entry.host and (preserve_metahosts or |
| 403 | not queue_entry.meta_host)): |
| 404 | if queue_entry.deleted: |
| 405 | continue |
| 406 | if queue_entry.host.invalid: |
| 407 | one_time_hosts.append(queue_entry.host) |
| 408 | else: |
| 409 | hosts.append(queue_entry.host) |
| 410 | else: |
| 411 | meta_hosts.append(queue_entry.meta_host) |
| 412 | if atomic_group is None: |
| 413 | if queue_entry.atomic_group is not None: |
| 414 | atomic_group = queue_entry.atomic_group |
| 415 | else: |
| 416 | assert atomic_group.name == queue_entry.atomic_group.name, ( |
| 417 | 'DB inconsistency. HostQueueEntries with multiple atomic' |
| 418 | ' groups on job %s: %s != %s' % ( |
| 419 | id, atomic_group.name, queue_entry.atomic_group.name)) |
| 420 | |
| 421 | meta_host_counts = _get_metahost_counts(meta_hosts) |
| 422 | |
| 423 | info = dict(dependencies=[label.name for label |
| 424 | in job.dependency_labels.all()], |
| 425 | hosts=hosts, |
| 426 | meta_hosts=meta_hosts, |
| 427 | meta_host_counts=meta_host_counts, |
| 428 | one_time_hosts=one_time_hosts, |
| 429 | atomic_group=atomic_group) |
| 430 | return info |
| 431 | |
| 432 | |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 433 | def create_new_job(owner, options, host_objects, metahost_objects, |
| 434 | atomic_group=None): |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 435 | labels_by_name = dict((label.name, label) |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 436 | for label in models.Label.objects.all()) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 437 | all_host_objects = host_objects + metahost_objects |
| 438 | metahost_counts = _get_metahost_counts(metahost_objects) |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 439 | dependencies = options.get('dependencies', []) |
| 440 | synch_count = options.get('synch_count') |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 441 | |
| 442 | # check that each metahost request has enough hosts under the label |
| 443 | for label, requested_count in metahost_counts.iteritems(): |
| 444 | available_count = label.host_set.count() |
| 445 | if requested_count > available_count: |
| 446 | error = ("You have requested %d %s's, but there are only %d." |
| 447 | % (requested_count, label.name, available_count)) |
| 448 | raise model_logic.ValidationError({'meta_hosts' : error}) |
| 449 | |
| 450 | if atomic_group: |
| 451 | check_atomic_group_create_job( |
| 452 | synch_count, host_objects, metahost_objects, |
| 453 | dependencies, atomic_group, labels_by_name) |
| 454 | else: |
| 455 | if synch_count is not None and synch_count > len(all_host_objects): |
| 456 | raise model_logic.ValidationError( |
| 457 | {'hosts': |
| 458 | 'only %d hosts provided for job with synch_count = %d' % |
| 459 | (len(all_host_objects), synch_count)}) |
| 460 | atomic_hosts = models.Host.objects.filter( |
| 461 | id__in=[host.id for host in host_objects], |
| 462 | labels__atomic_group=True) |
| 463 | unusable_host_names = [host.hostname for host in atomic_hosts] |
| 464 | if unusable_host_names: |
| 465 | raise model_logic.ValidationError( |
| 466 | {'hosts': |
| 467 | 'Host(s) "%s" are atomic group hosts but no ' |
| 468 | 'atomic group was specified for this job.' % |
| 469 | (', '.join(unusable_host_names),)}) |
| 470 | |
| 471 | |
| 472 | check_job_dependencies(host_objects, dependencies) |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 473 | options['dependencies'] = [labels_by_name[label_name] |
| 474 | for label_name in dependencies] |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 475 | |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 476 | for label in metahost_objects + options['dependencies']: |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 477 | if label.atomic_group and not atomic_group: |
| 478 | raise model_logic.ValidationError( |
| 479 | {'atomic_group_name': |
showard | c873032 | 2009-06-30 01:56:38 +0000 | [diff] [blame] | 480 | 'Dependency %r requires an atomic group but no ' |
| 481 | 'atomic_group_name or meta_host in an atomic group was ' |
| 482 | 'specified for this job.' % label.name}) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 483 | elif (label.atomic_group and |
| 484 | label.atomic_group.name != atomic_group.name): |
| 485 | raise model_logic.ValidationError( |
| 486 | {'atomic_group_name': |
showard | c873032 | 2009-06-30 01:56:38 +0000 | [diff] [blame] | 487 | 'meta_hosts or dependency %r requires atomic group ' |
| 488 | '%r instead of the supplied atomic_group_name=%r.' % |
| 489 | (label.name, label.atomic_group.name, atomic_group.name)}) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 490 | |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 491 | job = models.Job.create(owner=owner, options=options, |
| 492 | hosts=all_host_objects) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 493 | job.queue(all_host_objects, atomic_group=atomic_group, |
showard | a1e74b3 | 2009-05-12 17:32:04 +0000 | [diff] [blame] | 494 | is_template=options.get('is_template', False)) |
showard | 29f7cd2 | 2009-04-29 21:16:24 +0000 | [diff] [blame] | 495 | return job.id |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 496 | |
| 497 | |
showard | 909c914 | 2009-07-07 20:54:42 +0000 | [diff] [blame] | 498 | def find_platform_and_atomic_group(host): |
| 499 | """ |
| 500 | Figure out the platform name and atomic group name for the given host |
| 501 | object. If none, the return value for either will be None. |
| 502 | |
| 503 | @returns (platform name, atomic group name) for the given host. |
| 504 | """ |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 505 | platforms = [label.name for label in host.label_list if label.platform] |
| 506 | if not platforms: |
showard | 909c914 | 2009-07-07 20:54:42 +0000 | [diff] [blame] | 507 | platform = None |
| 508 | else: |
| 509 | platform = platforms[0] |
showard | 0957a84 | 2009-05-11 19:25:08 +0000 | [diff] [blame] | 510 | if len(platforms) > 1: |
| 511 | raise ValueError('Host %s has more than one platform: %s' % |
| 512 | (host.hostname, ', '.join(platforms))) |
showard | 909c914 | 2009-07-07 20:54:42 +0000 | [diff] [blame] | 513 | for label in host.label_list: |
| 514 | if label.atomic_group: |
| 515 | atomic_group_name = label.atomic_group.name |
| 516 | break |
| 517 | else: |
| 518 | atomic_group_name = None |
| 519 | # Don't check for multiple atomic groups on a host here. That is an |
| 520 | # error but should not trip up the RPC interface. monitor_db_cleanup |
| 521 | # deals with it. This just returns the first one found. |
| 522 | return platform, atomic_group_name |
showard | c0ac3a7 | 2009-07-08 21:14:45 +0000 | [diff] [blame] | 523 | |
| 524 | |
| 525 | # support for get_host_queue_entries_and_special_tasks() |
| 526 | |
| 527 | def _common_entry_to_dict(entry, type, job_dict): |
| 528 | return dict(type=type, |
| 529 | host=entry.host.get_object_dict(), |
| 530 | job=job_dict, |
| 531 | execution_path=entry.execution_path(), |
| 532 | status=entry.status, |
| 533 | started_on=entry.started_on, |
showard | 8fb1fde | 2009-07-11 01:47:16 +0000 | [diff] [blame] | 534 | id=str(entry.id) + type) |
showard | c0ac3a7 | 2009-07-08 21:14:45 +0000 | [diff] [blame] | 535 | |
| 536 | |
| 537 | def _special_task_to_dict(special_task): |
| 538 | job_dict = None |
| 539 | if special_task.queue_entry: |
| 540 | job_dict = special_task.queue_entry.job.get_object_dict() |
| 541 | return _common_entry_to_dict(special_task, special_task.task, job_dict) |
| 542 | |
| 543 | |
| 544 | def _queue_entry_to_dict(queue_entry): |
| 545 | return _common_entry_to_dict(queue_entry, 'Job', |
| 546 | queue_entry.job.get_object_dict()) |
| 547 | |
| 548 | |
| 549 | def _compute_next_job_for_tasks(queue_entries, special_tasks): |
| 550 | """ |
| 551 | For each task, try to figure out the next job that ran after that task. |
| 552 | This is done using two pieces of information: |
| 553 | * if the task has a queue entry, we can use that entry's job ID. |
| 554 | * if the task has a time_started, we can try to compare that against the |
| 555 | started_on field of queue_entries. this isn't guaranteed to work perfectly |
| 556 | since queue_entries may also have null started_on values. |
| 557 | * if the task has neither, or if use of time_started fails, just use the |
| 558 | last computed job ID. |
| 559 | """ |
| 560 | next_job_id = None # most recently computed next job |
| 561 | hqe_index = 0 # index for scanning by started_on times |
| 562 | for task in special_tasks: |
| 563 | if task.queue_entry: |
| 564 | next_job_id = task.queue_entry.job.id |
| 565 | elif task.time_started is not None: |
| 566 | for queue_entry in queue_entries[hqe_index:]: |
| 567 | if queue_entry.started_on is None: |
| 568 | continue |
| 569 | if queue_entry.started_on < task.time_started: |
| 570 | break |
| 571 | next_job_id = queue_entry.job.id |
| 572 | |
| 573 | task.next_job_id = next_job_id |
| 574 | |
| 575 | # advance hqe_index to just after next_job_id |
| 576 | if next_job_id is not None: |
| 577 | for queue_entry in queue_entries[hqe_index:]: |
| 578 | if queue_entry.job.id < next_job_id: |
| 579 | break |
| 580 | hqe_index += 1 |
| 581 | |
| 582 | |
| 583 | def interleave_entries(queue_entries, special_tasks): |
| 584 | """ |
| 585 | Both lists should be ordered by descending ID. |
| 586 | """ |
| 587 | _compute_next_job_for_tasks(queue_entries, special_tasks) |
| 588 | |
| 589 | # start with all special tasks that've run since the last job |
| 590 | interleaved_entries = [] |
| 591 | for task in special_tasks: |
| 592 | if task.next_job_id is not None: |
| 593 | break |
| 594 | interleaved_entries.append(_special_task_to_dict(task)) |
| 595 | |
| 596 | # now interleave queue entries with the remaining special tasks |
| 597 | special_task_index = len(interleaved_entries) |
| 598 | for queue_entry in queue_entries: |
| 599 | interleaved_entries.append(_queue_entry_to_dict(queue_entry)) |
| 600 | # add all tasks that ran between this job and the previous one |
| 601 | for task in special_tasks[special_task_index:]: |
| 602 | if task.next_job_id < queue_entry.job.id: |
| 603 | break |
| 604 | interleaved_entries.append(_special_task_to_dict(task)) |
| 605 | special_task_index += 1 |
| 606 | |
| 607 | return interleaved_entries |