blob: 27ae9da4c5c883965d51c2ed8efe8a2acf9264f5 [file] [log] [blame]
Aviv Keshet0b9cfc92013-02-05 11:36:02 -08001# pylint: disable-msg=C0111
2
showardd1195652009-12-08 22:21:02 +00003import logging, os
showardfb2a7fa2008-07-17 17:04:12 +00004from datetime import datetime
Aviv Keshetfa199002013-05-09 13:31:46 -07005import django.core
6try:
7 from django.db import models as dbmodels, connection
8except django.core.exceptions.ImproperlyConfigured:
9 raise ImportError('Django database not yet configured. Import either '
10 'setup_django_environment or '
11 'setup_django_lite_environment from '
12 'autotest_lib.frontend before any imports that '
13 'depend on django models.')
jamesren35a70222010-02-16 19:30:46 +000014from xml.sax import saxutils
showardcafd16e2009-05-29 18:37:49 +000015import common
jamesrendd855242010-03-02 22:23:44 +000016from autotest_lib.frontend.afe import model_logic, model_attributes
Prashanth B489b91d2014-03-15 12:17:16 -070017from autotest_lib.frontend.afe import rdb_model_extensions
showardcafd16e2009-05-29 18:37:49 +000018from autotest_lib.frontend import settings, thread_local
Jakob Juelicha94efe62014-09-18 16:02:49 -070019from autotest_lib.client.common_lib import enum, error, host_protections
20from autotest_lib.client.common_lib import global_config
showardeaa408e2009-09-11 18:45:31 +000021from autotest_lib.client.common_lib import host_queue_entry_states
Jakob Juelicha94efe62014-09-18 16:02:49 -070022from autotest_lib.client.common_lib import control_data, priorities, decorators
Prashanth Balasubramanian6edaaf92014-11-24 16:36:25 -080023from autotest_lib.client.common_lib import site_utils
Gabe Blackb72f4fb2015-01-20 16:47:13 -080024from autotest_lib.client.common_lib.cros.graphite import autotest_es
mblighe8819cd2008-02-15 16:48:40 +000025
showard0fc38302008-10-23 00:44:07 +000026# job options and user preferences
jamesrendd855242010-03-02 22:23:44 +000027DEFAULT_REBOOT_BEFORE = model_attributes.RebootBefore.IF_DIRTY
Dan Shi07e09af2013-04-12 09:31:29 -070028DEFAULT_REBOOT_AFTER = model_attributes.RebootBefore.NEVER
mblighe8819cd2008-02-15 16:48:40 +000029
showard89f84db2009-03-12 20:39:13 +000030
mblighe8819cd2008-02-15 16:48:40 +000031class AclAccessViolation(Exception):
jadmanski0afbb632008-06-06 21:10:57 +000032 """\
33 Raised when an operation is attempted with proper permissions as
34 dictated by ACLs.
35 """
mblighe8819cd2008-02-15 16:48:40 +000036
37
showard205fd602009-03-21 00:17:35 +000038class AtomicGroup(model_logic.ModelWithInvalid, dbmodels.Model):
showard89f84db2009-03-12 20:39:13 +000039 """\
40 An atomic group defines a collection of hosts which must only be scheduled
41 all at once. Any host with a label having an atomic group will only be
42 scheduled for a job at the same time as other hosts sharing that label.
43
44 Required:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -080045 name: A name for this atomic group, e.g. 'rack23' or 'funky_net'.
showard89f84db2009-03-12 20:39:13 +000046 max_number_of_machines: The maximum number of machines that will be
47 scheduled at once when scheduling jobs to this atomic group.
48 The job.synch_count is considered the minimum.
49
50 Optional:
51 description: Arbitrary text description of this group's purpose.
52 """
showarda5288b42009-07-28 20:06:08 +000053 name = dbmodels.CharField(max_length=255, unique=True)
showard89f84db2009-03-12 20:39:13 +000054 description = dbmodels.TextField(blank=True)
showarde9450c92009-06-30 01:58:52 +000055 # This magic value is the default to simplify the scheduler logic.
56 # It must be "large". The common use of atomic groups is to want all
57 # machines in the group to be used, limits on which subset used are
58 # often chosen via dependency labels.
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -080059 # TODO(dennisjeffrey): Revisit this so we don't have to assume that
60 # "infinity" is around 3.3 million.
showarde9450c92009-06-30 01:58:52 +000061 INFINITE_MACHINES = 333333333
62 max_number_of_machines = dbmodels.IntegerField(default=INFINITE_MACHINES)
showard205fd602009-03-21 00:17:35 +000063 invalid = dbmodels.BooleanField(default=False,
showarda5288b42009-07-28 20:06:08 +000064 editable=settings.FULL_ADMIN)
showard89f84db2009-03-12 20:39:13 +000065
showard89f84db2009-03-12 20:39:13 +000066 name_field = 'name'
jamesrene3656232010-03-02 00:00:30 +000067 objects = model_logic.ModelWithInvalidManager()
showard205fd602009-03-21 00:17:35 +000068 valid_objects = model_logic.ValidObjectsManager()
69
70
showard29f7cd22009-04-29 21:16:24 +000071 def enqueue_job(self, job, is_template=False):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -080072 """Enqueue a job on an associated atomic group of hosts.
73
74 @param job: A job to enqueue.
75 @param is_template: Whether the status should be "Template".
76 """
showard29f7cd22009-04-29 21:16:24 +000077 queue_entry = HostQueueEntry.create(atomic_group=self, job=job,
78 is_template=is_template)
showardc92da832009-04-07 18:14:34 +000079 queue_entry.save()
80
81
showard205fd602009-03-21 00:17:35 +000082 def clean_object(self):
83 self.label_set.clear()
showard89f84db2009-03-12 20:39:13 +000084
85
86 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -080087 """Metadata for class AtomicGroup."""
showardeab66ce2009-12-23 00:03:56 +000088 db_table = 'afe_atomic_groups'
showard89f84db2009-03-12 20:39:13 +000089
showard205fd602009-03-21 00:17:35 +000090
showarda5288b42009-07-28 20:06:08 +000091 def __unicode__(self):
92 return unicode(self.name)
showard89f84db2009-03-12 20:39:13 +000093
94
showard7c785282008-05-29 19:45:12 +000095class Label(model_logic.ModelWithInvalid, dbmodels.Model):
jadmanski0afbb632008-06-06 21:10:57 +000096 """\
97 Required:
showard89f84db2009-03-12 20:39:13 +000098 name: label name
mblighe8819cd2008-02-15 16:48:40 +000099
jadmanski0afbb632008-06-06 21:10:57 +0000100 Optional:
showard89f84db2009-03-12 20:39:13 +0000101 kernel_config: URL/path to kernel config for jobs run on this label.
102 platform: If True, this is a platform label (defaults to False).
103 only_if_needed: If True, a Host with this label can only be used if that
104 label is requested by the job/test (either as the meta_host or
105 in the job_dependencies).
106 atomic_group: The atomic group associated with this label.
jadmanski0afbb632008-06-06 21:10:57 +0000107 """
showarda5288b42009-07-28 20:06:08 +0000108 name = dbmodels.CharField(max_length=255, unique=True)
109 kernel_config = dbmodels.CharField(max_length=255, blank=True)
jadmanski0afbb632008-06-06 21:10:57 +0000110 platform = dbmodels.BooleanField(default=False)
111 invalid = dbmodels.BooleanField(default=False,
112 editable=settings.FULL_ADMIN)
showardb1e51872008-10-07 11:08:18 +0000113 only_if_needed = dbmodels.BooleanField(default=False)
mblighe8819cd2008-02-15 16:48:40 +0000114
jadmanski0afbb632008-06-06 21:10:57 +0000115 name_field = 'name'
jamesrene3656232010-03-02 00:00:30 +0000116 objects = model_logic.ModelWithInvalidManager()
jadmanski0afbb632008-06-06 21:10:57 +0000117 valid_objects = model_logic.ValidObjectsManager()
showard89f84db2009-03-12 20:39:13 +0000118 atomic_group = dbmodels.ForeignKey(AtomicGroup, null=True, blank=True)
119
mbligh5244cbb2008-04-24 20:39:52 +0000120
jadmanski0afbb632008-06-06 21:10:57 +0000121 def clean_object(self):
122 self.host_set.clear()
showard01a51672009-05-29 18:42:37 +0000123 self.test_set.clear()
mblighe8819cd2008-02-15 16:48:40 +0000124
125
showard29f7cd22009-04-29 21:16:24 +0000126 def enqueue_job(self, job, atomic_group=None, is_template=False):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800127 """Enqueue a job on any host of this label.
128
129 @param job: A job to enqueue.
130 @param atomic_group: The associated atomic group.
131 @param is_template: Whether the status should be "Template".
132 """
showard29f7cd22009-04-29 21:16:24 +0000133 queue_entry = HostQueueEntry.create(meta_host=self, job=job,
134 is_template=is_template,
135 atomic_group=atomic_group)
jadmanski0afbb632008-06-06 21:10:57 +0000136 queue_entry.save()
mblighe8819cd2008-02-15 16:48:40 +0000137
138
Fang Dengff361592015-02-02 15:27:34 -0800139
jadmanski0afbb632008-06-06 21:10:57 +0000140 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800141 """Metadata for class Label."""
showardeab66ce2009-12-23 00:03:56 +0000142 db_table = 'afe_labels'
mblighe8819cd2008-02-15 16:48:40 +0000143
Fang Dengff361592015-02-02 15:27:34 -0800144
showarda5288b42009-07-28 20:06:08 +0000145 def __unicode__(self):
146 return unicode(self.name)
mblighe8819cd2008-02-15 16:48:40 +0000147
148
Jakob Jülich92c06332014-08-25 19:06:57 +0000149class Shard(dbmodels.Model, model_logic.ModelExtensions):
150
Jakob Juelichde2b9a92014-09-02 15:29:28 -0700151 hostname = dbmodels.CharField(max_length=255, unique=True)
152
153 name_field = 'hostname'
154
Jakob Jülich92c06332014-08-25 19:06:57 +0000155 labels = dbmodels.ManyToManyField(Label, blank=True,
156 db_table='afe_shards_labels')
157
158 class Meta:
159 """Metadata for class ParameterizedJob."""
160 db_table = 'afe_shards'
161
162
Prashanth Balasubramanian6edaaf92014-11-24 16:36:25 -0800163 def rpc_hostname(self):
164 """Get the rpc hostname of the shard.
165
166 @return: Just the shard hostname for all non-testing environments.
167 The address of the default gateway for vm testing environments.
168 """
169 # TODO: Figure out a better solution for testing. Since no 2 shards
170 # can run on the same host, if the shard hostname is localhost we
171 # conclude that it must be a vm in a test cluster. In such situations
172 # a name of localhost:<port> is necessary to achieve the correct
173 # afe links/redirection from the frontend (this happens through the
174 # host), but for rpcs that are performed *on* the shard, they need to
175 # use the address of the gateway.
176 hostname = self.hostname.split(':')[0]
177 if site_utils.is_localhost(hostname):
178 return self.hostname.replace(
179 hostname, site_utils.DEFAULT_VM_GATEWAY)
180 return self.hostname
181
182
jamesren76fcf192010-04-21 20:39:50 +0000183class Drone(dbmodels.Model, model_logic.ModelExtensions):
184 """
185 A scheduler drone
186
187 hostname: the drone's hostname
188 """
189 hostname = dbmodels.CharField(max_length=255, unique=True)
190
191 name_field = 'hostname'
192 objects = model_logic.ExtendedManager()
193
194
195 def save(self, *args, **kwargs):
196 if not User.current_user().is_superuser():
197 raise Exception('Only superusers may edit drones')
198 super(Drone, self).save(*args, **kwargs)
199
200
201 def delete(self):
202 if not User.current_user().is_superuser():
203 raise Exception('Only superusers may delete drones')
204 super(Drone, self).delete()
205
206
207 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800208 """Metadata for class Drone."""
jamesren76fcf192010-04-21 20:39:50 +0000209 db_table = 'afe_drones'
210
211 def __unicode__(self):
212 return unicode(self.hostname)
213
214
215class DroneSet(dbmodels.Model, model_logic.ModelExtensions):
216 """
217 A set of scheduler drones
218
219 These will be used by the scheduler to decide what drones a job is allowed
220 to run on.
221
222 name: the drone set's name
223 drones: the drones that are part of the set
224 """
225 DRONE_SETS_ENABLED = global_config.global_config.get_config_value(
226 'SCHEDULER', 'drone_sets_enabled', type=bool, default=False)
227 DEFAULT_DRONE_SET_NAME = global_config.global_config.get_config_value(
228 'SCHEDULER', 'default_drone_set_name', default=None)
229
230 name = dbmodels.CharField(max_length=255, unique=True)
231 drones = dbmodels.ManyToManyField(Drone, db_table='afe_drone_sets_drones')
232
233 name_field = 'name'
234 objects = model_logic.ExtendedManager()
235
236
237 def save(self, *args, **kwargs):
238 if not User.current_user().is_superuser():
239 raise Exception('Only superusers may edit drone sets')
240 super(DroneSet, self).save(*args, **kwargs)
241
242
243 def delete(self):
244 if not User.current_user().is_superuser():
245 raise Exception('Only superusers may delete drone sets')
246 super(DroneSet, self).delete()
247
248
249 @classmethod
250 def drone_sets_enabled(cls):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800251 """Returns whether drone sets are enabled.
252
253 @param cls: Implicit class object.
254 """
jamesren76fcf192010-04-21 20:39:50 +0000255 return cls.DRONE_SETS_ENABLED
256
257
258 @classmethod
259 def default_drone_set_name(cls):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800260 """Returns the default drone set name.
261
262 @param cls: Implicit class object.
263 """
jamesren76fcf192010-04-21 20:39:50 +0000264 return cls.DEFAULT_DRONE_SET_NAME
265
266
267 @classmethod
268 def get_default(cls):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800269 """Gets the default drone set name, compatible with Job.add_object.
270
271 @param cls: Implicit class object.
272 """
jamesren76fcf192010-04-21 20:39:50 +0000273 return cls.smart_get(cls.DEFAULT_DRONE_SET_NAME)
274
275
276 @classmethod
277 def resolve_name(cls, drone_set_name):
278 """
279 Returns the name of one of these, if not None, in order of preference:
280 1) the drone set given,
281 2) the current user's default drone set, or
282 3) the global default drone set
283
284 or returns None if drone sets are disabled
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800285
286 @param cls: Implicit class object.
287 @param drone_set_name: A drone set name.
jamesren76fcf192010-04-21 20:39:50 +0000288 """
289 if not cls.drone_sets_enabled():
290 return None
291
292 user = User.current_user()
293 user_drone_set_name = user.drone_set and user.drone_set.name
294
295 return drone_set_name or user_drone_set_name or cls.get_default().name
296
297
298 def get_drone_hostnames(self):
299 """
300 Gets the hostnames of all drones in this drone set
301 """
302 return set(self.drones.all().values_list('hostname', flat=True))
303
304
305 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800306 """Metadata for class DroneSet."""
jamesren76fcf192010-04-21 20:39:50 +0000307 db_table = 'afe_drone_sets'
308
309 def __unicode__(self):
310 return unicode(self.name)
311
312
showardfb2a7fa2008-07-17 17:04:12 +0000313class User(dbmodels.Model, model_logic.ModelExtensions):
314 """\
315 Required:
316 login :user login name
317
318 Optional:
319 access_level: 0=User (default), 1=Admin, 100=Root
320 """
321 ACCESS_ROOT = 100
322 ACCESS_ADMIN = 1
323 ACCESS_USER = 0
324
showard64a95952010-01-13 21:27:16 +0000325 AUTOTEST_SYSTEM = 'autotest_system'
326
showarda5288b42009-07-28 20:06:08 +0000327 login = dbmodels.CharField(max_length=255, unique=True)
showardfb2a7fa2008-07-17 17:04:12 +0000328 access_level = dbmodels.IntegerField(default=ACCESS_USER, blank=True)
329
showard0fc38302008-10-23 00:44:07 +0000330 # user preferences
jamesrendd855242010-03-02 22:23:44 +0000331 reboot_before = dbmodels.SmallIntegerField(
332 choices=model_attributes.RebootBefore.choices(), blank=True,
333 default=DEFAULT_REBOOT_BEFORE)
334 reboot_after = dbmodels.SmallIntegerField(
335 choices=model_attributes.RebootAfter.choices(), blank=True,
336 default=DEFAULT_REBOOT_AFTER)
jamesren76fcf192010-04-21 20:39:50 +0000337 drone_set = dbmodels.ForeignKey(DroneSet, null=True, blank=True)
showard97db5ba2008-11-12 18:18:02 +0000338 show_experimental = dbmodels.BooleanField(default=False)
showard0fc38302008-10-23 00:44:07 +0000339
showardfb2a7fa2008-07-17 17:04:12 +0000340 name_field = 'login'
341 objects = model_logic.ExtendedManager()
342
343
showarda5288b42009-07-28 20:06:08 +0000344 def save(self, *args, **kwargs):
showardfb2a7fa2008-07-17 17:04:12 +0000345 # is this a new object being saved for the first time?
346 first_time = (self.id is None)
347 user = thread_local.get_user()
showard0fc38302008-10-23 00:44:07 +0000348 if user and not user.is_superuser() and user.login != self.login:
349 raise AclAccessViolation("You cannot modify user " + self.login)
showarda5288b42009-07-28 20:06:08 +0000350 super(User, self).save(*args, **kwargs)
showardfb2a7fa2008-07-17 17:04:12 +0000351 if first_time:
352 everyone = AclGroup.objects.get(name='Everyone')
353 everyone.users.add(self)
354
355
356 def is_superuser(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800357 """Returns whether the user has superuser access."""
showardfb2a7fa2008-07-17 17:04:12 +0000358 return self.access_level >= self.ACCESS_ROOT
359
360
showard64a95952010-01-13 21:27:16 +0000361 @classmethod
362 def current_user(cls):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800363 """Returns the current user.
364
365 @param cls: Implicit class object.
366 """
showard64a95952010-01-13 21:27:16 +0000367 user = thread_local.get_user()
368 if user is None:
showardcfcdd802010-01-15 00:16:33 +0000369 user, _ = cls.objects.get_or_create(login=cls.AUTOTEST_SYSTEM)
showard64a95952010-01-13 21:27:16 +0000370 user.access_level = cls.ACCESS_ROOT
371 user.save()
372 return user
373
374
Prashanth Balasubramanianaf516642014-12-12 18:16:32 -0800375 @classmethod
376 def get_record(cls, data):
377 """Check the database for an identical record.
378
379 Check for a record with matching id and login. If one exists,
380 return it. If one does not exist there is a possibility that
381 the following cases have happened:
382 1. Same id, different login
383 We received: "1 chromeos-test"
384 And we have: "1 debug-user"
385 In this case we need to delete "1 debug_user" and insert
386 "1 chromeos-test".
387
388 2. Same login, different id:
389 We received: "1 chromeos-test"
390 And we have: "2 chromeos-test"
391 In this case we need to delete "2 chromeos-test" and insert
392 "1 chromeos-test".
393
394 As long as this method deletes bad records and raises the
395 DoesNotExist exception the caller will handle creating the
396 new record.
397
398 @raises: DoesNotExist, if a record with the matching login and id
399 does not exist.
400 """
401
402 # Both the id and login should be uniqe but there are cases when
403 # we might already have a user with the same login/id because
404 # current_user will proactively create a user record if it doesn't
405 # exist. Since we want to avoid conflict between the master and
406 # shard, just delete any existing user records that don't match
407 # what we're about to deserialize from the master.
408 try:
409 return cls.objects.get(login=data['login'], id=data['id'])
410 except cls.DoesNotExist:
411 cls.delete_matching_record(login=data['login'])
412 cls.delete_matching_record(id=data['id'])
413 raise
414
415
showardfb2a7fa2008-07-17 17:04:12 +0000416 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800417 """Metadata for class User."""
showardeab66ce2009-12-23 00:03:56 +0000418 db_table = 'afe_users'
showardfb2a7fa2008-07-17 17:04:12 +0000419
showarda5288b42009-07-28 20:06:08 +0000420 def __unicode__(self):
421 return unicode(self.login)
showardfb2a7fa2008-07-17 17:04:12 +0000422
423
Prashanth B489b91d2014-03-15 12:17:16 -0700424class Host(model_logic.ModelWithInvalid, rdb_model_extensions.AbstractHostModel,
showardf8b19042009-05-12 17:22:49 +0000425 model_logic.ModelWithAttributes):
jadmanski0afbb632008-06-06 21:10:57 +0000426 """\
427 Required:
428 hostname
mblighe8819cd2008-02-15 16:48:40 +0000429
jadmanski0afbb632008-06-06 21:10:57 +0000430 optional:
showard21baa452008-10-21 00:08:39 +0000431 locked: if true, host is locked and will not be queued
mblighe8819cd2008-02-15 16:48:40 +0000432
jadmanski0afbb632008-06-06 21:10:57 +0000433 Internal:
Prashanth B489b91d2014-03-15 12:17:16 -0700434 From AbstractHostModel:
435 synch_id: currently unused
436 status: string describing status of host
437 invalid: true if the host has been deleted
438 protection: indicates what can be done to this host during repair
439 lock_time: DateTime at which the host was locked
440 dirty: true if the host has been used without being rebooted
441 Local:
442 locked_by: user that locked the host, or null if the host is unlocked
jadmanski0afbb632008-06-06 21:10:57 +0000443 """
mblighe8819cd2008-02-15 16:48:40 +0000444
Jakob Juelich3bb7c802014-09-02 16:31:11 -0700445 SERIALIZATION_LINKS_TO_FOLLOW = set(['aclgroup_set',
446 'hostattribute_set',
447 'labels',
448 'shard'])
Prashanth Balasubramanian5949b4a2014-11-23 12:58:30 -0800449 SERIALIZATION_LOCAL_LINKS_TO_UPDATE = set(['invalid'])
Jakob Juelich3bb7c802014-09-02 16:31:11 -0700450
Jakob Juelichf88fa932014-09-03 17:58:04 -0700451
452 def custom_deserialize_relation(self, link, data):
Jakob Juelich116ff0f2014-09-17 18:25:16 -0700453 assert link == 'shard', 'Link %s should not be deserialized' % link
Jakob Juelichf88fa932014-09-03 17:58:04 -0700454 self.shard = Shard.deserialize(data)
455
456
Prashanth B489b91d2014-03-15 12:17:16 -0700457 # Note: Only specify foreign keys here, specify all native host columns in
458 # rdb_model_extensions instead.
459 Protection = host_protections.Protection
showardeab66ce2009-12-23 00:03:56 +0000460 labels = dbmodels.ManyToManyField(Label, blank=True,
461 db_table='afe_hosts_labels')
showardfb2a7fa2008-07-17 17:04:12 +0000462 locked_by = dbmodels.ForeignKey(User, null=True, blank=True, editable=False)
jadmanski0afbb632008-06-06 21:10:57 +0000463 name_field = 'hostname'
jamesrene3656232010-03-02 00:00:30 +0000464 objects = model_logic.ModelWithInvalidManager()
jadmanski0afbb632008-06-06 21:10:57 +0000465 valid_objects = model_logic.ValidObjectsManager()
beepscc9fc702013-12-02 12:45:38 -0800466 leased_objects = model_logic.LeasedHostManager()
mbligh5244cbb2008-04-24 20:39:52 +0000467
Jakob Juelichde2b9a92014-09-02 15:29:28 -0700468 shard = dbmodels.ForeignKey(Shard, blank=True, null=True)
showard2bab8f42008-11-12 18:15:22 +0000469
470 def __init__(self, *args, **kwargs):
471 super(Host, self).__init__(*args, **kwargs)
472 self._record_attributes(['status'])
473
474
showardb8471e32008-07-03 19:51:08 +0000475 @staticmethod
476 def create_one_time_host(hostname):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800477 """Creates a one-time host.
478
479 @param hostname: The name for the host.
480 """
showardb8471e32008-07-03 19:51:08 +0000481 query = Host.objects.filter(hostname=hostname)
482 if query.count() == 0:
483 host = Host(hostname=hostname, invalid=True)
showarda8411af2008-08-07 22:35:58 +0000484 host.do_validate()
showardb8471e32008-07-03 19:51:08 +0000485 else:
486 host = query[0]
487 if not host.invalid:
488 raise model_logic.ValidationError({
mblighb5b7b5d2009-02-03 17:47:15 +0000489 'hostname' : '%s already exists in the autotest DB. '
490 'Select it rather than entering it as a one time '
491 'host.' % hostname
showardb8471e32008-07-03 19:51:08 +0000492 })
showard1ab512b2008-07-30 23:39:04 +0000493 host.protection = host_protections.Protection.DO_NOT_REPAIR
showard946a7af2009-04-15 21:53:23 +0000494 host.locked = False
showardb8471e32008-07-03 19:51:08 +0000495 host.save()
showard2924b0a2009-06-18 23:16:15 +0000496 host.clean_object()
showardb8471e32008-07-03 19:51:08 +0000497 return host
mbligh5244cbb2008-04-24 20:39:52 +0000498
showard1ff7b2e2009-05-15 23:17:18 +0000499
Jakob Juelich59cfe542014-09-02 16:37:46 -0700500 @classmethod
Jakob Juelich1b525742014-09-30 13:08:07 -0700501 def assign_to_shard(cls, shard, known_ids):
Jakob Juelich59cfe542014-09-02 16:37:46 -0700502 """Assigns hosts to a shard.
503
Jakob Juelich1b525742014-09-30 13:08:07 -0700504 For all labels that have been assigned to this shard, all hosts that
505 have this label, are assigned to this shard.
506
507 Hosts that are assigned to the shard but aren't already present on the
508 shard are returned.
Jakob Juelich59cfe542014-09-02 16:37:46 -0700509
510 @param shard: The shard object to assign labels/hosts for.
Jakob Juelich1b525742014-09-30 13:08:07 -0700511 @param known_ids: List of all host-ids the shard already knows.
512 This is used to figure out which hosts should be sent
513 to the shard. If shard_ids were used instead, hosts
514 would only be transferred once, even if the client
515 failed persisting them.
516 The number of hosts usually lies in O(100), so the
517 overhead is acceptable.
518
Jakob Juelich59cfe542014-09-02 16:37:46 -0700519 @returns the hosts objects that should be sent to the shard.
520 """
521
522 # Disclaimer: concurrent heartbeats should theoretically not occur in
523 # the current setup. As they may be introduced in the near future,
524 # this comment will be left here.
525
526 # Sending stuff twice is acceptable, but forgetting something isn't.
527 # Detecting duplicates on the client is easy, but here it's harder. The
528 # following options were considered:
529 # - SELECT ... WHERE and then UPDATE ... WHERE: Update might update more
530 # than select returned, as concurrently more hosts might have been
531 # inserted
532 # - UPDATE and then SELECT WHERE shard=shard: select always returns all
533 # hosts for the shard, this is overhead
534 # - SELECT and then UPDATE only selected without requerying afterwards:
535 # returns the old state of the records.
536 host_ids = list(Host.objects.filter(
Jakob Juelich59cfe542014-09-02 16:37:46 -0700537 labels=shard.labels.all(),
538 leased=False
Jakob Juelich1b525742014-09-30 13:08:07 -0700539 ).exclude(
540 id__in=known_ids,
Jakob Juelich59cfe542014-09-02 16:37:46 -0700541 ).values_list('pk', flat=True))
542
543 if host_ids:
544 Host.objects.filter(pk__in=host_ids).update(shard=shard)
545 return list(Host.objects.filter(pk__in=host_ids).all())
546 return []
547
showardafd97de2009-10-01 18:45:09 +0000548 def resurrect_object(self, old_object):
549 super(Host, self).resurrect_object(old_object)
550 # invalid hosts can be in use by the scheduler (as one-time hosts), so
551 # don't change the status
552 self.status = old_object.status
553
554
jadmanski0afbb632008-06-06 21:10:57 +0000555 def clean_object(self):
556 self.aclgroup_set.clear()
557 self.labels.clear()
mblighe8819cd2008-02-15 16:48:40 +0000558
559
Dan Shia0acfbc2014-10-14 15:56:23 -0700560 def record_state(self, type_str, state, value, other_metadata=None):
561 """Record metadata in elasticsearch.
562
563 @param type_str: sets the _type field in elasticsearch db.
564 @param state: string representing what state we are recording,
565 e.g. 'locked'
566 @param value: value of the state, e.g. True
567 @param other_metadata: Other metadata to store in metaDB.
568 """
569 metadata = {
570 state: value,
571 'hostname': self.hostname,
572 }
573 if other_metadata:
574 metadata = dict(metadata.items() + other_metadata.items())
Gabe Blackb72f4fb2015-01-20 16:47:13 -0800575 autotest_es.post(type_str=type_str, metadata=metadata)
Dan Shia0acfbc2014-10-14 15:56:23 -0700576
577
showarda5288b42009-07-28 20:06:08 +0000578 def save(self, *args, **kwargs):
jadmanski0afbb632008-06-06 21:10:57 +0000579 # extra spaces in the hostname can be a sneaky source of errors
580 self.hostname = self.hostname.strip()
581 # is this a new object being saved for the first time?
582 first_time = (self.id is None)
showard3dd47c22008-07-10 00:41:36 +0000583 if not first_time:
584 AclGroup.check_for_acl_violation_hosts([self])
Dan Shia0acfbc2014-10-14 15:56:23 -0700585 # If locked is changed, send its status and user made the change to
586 # metaDB. Locks are important in host history because if a device is
587 # locked then we don't really care what state it is in.
showardfb2a7fa2008-07-17 17:04:12 +0000588 if self.locked and not self.locked_by:
showard64a95952010-01-13 21:27:16 +0000589 self.locked_by = User.current_user()
showardfb2a7fa2008-07-17 17:04:12 +0000590 self.lock_time = datetime.now()
Dan Shia0acfbc2014-10-14 15:56:23 -0700591 self.record_state('lock_history', 'locked', self.locked,
592 {'changed_by': self.locked_by.login})
showard21baa452008-10-21 00:08:39 +0000593 self.dirty = True
showardfb2a7fa2008-07-17 17:04:12 +0000594 elif not self.locked and self.locked_by:
Dan Shia0acfbc2014-10-14 15:56:23 -0700595 self.record_state('lock_history', 'locked', self.locked,
596 {'changed_by': self.locked_by.login})
showardfb2a7fa2008-07-17 17:04:12 +0000597 self.locked_by = None
598 self.lock_time = None
showarda5288b42009-07-28 20:06:08 +0000599 super(Host, self).save(*args, **kwargs)
jadmanski0afbb632008-06-06 21:10:57 +0000600 if first_time:
601 everyone = AclGroup.objects.get(name='Everyone')
602 everyone.hosts.add(self)
showard2bab8f42008-11-12 18:15:22 +0000603 self._check_for_updated_attributes()
604
mblighe8819cd2008-02-15 16:48:40 +0000605
showardb8471e32008-07-03 19:51:08 +0000606 def delete(self):
showard3dd47c22008-07-10 00:41:36 +0000607 AclGroup.check_for_acl_violation_hosts([self])
showardb8471e32008-07-03 19:51:08 +0000608 for queue_entry in self.hostqueueentry_set.all():
609 queue_entry.deleted = True
showard64a95952010-01-13 21:27:16 +0000610 queue_entry.abort()
showardb8471e32008-07-03 19:51:08 +0000611 super(Host, self).delete()
612
mblighe8819cd2008-02-15 16:48:40 +0000613
showard2bab8f42008-11-12 18:15:22 +0000614 def on_attribute_changed(self, attribute, old_value):
615 assert attribute == 'status'
showardf1175bb2009-06-17 19:34:36 +0000616 logging.info(self.hostname + ' -> ' + self.status)
showard2bab8f42008-11-12 18:15:22 +0000617
618
showard29f7cd22009-04-29 21:16:24 +0000619 def enqueue_job(self, job, atomic_group=None, is_template=False):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800620 """Enqueue a job on this host.
621
622 @param job: A job to enqueue.
623 @param atomic_group: The associated atomic group.
624 @param is_template: Whther the status should be "Template".
625 """
showard29f7cd22009-04-29 21:16:24 +0000626 queue_entry = HostQueueEntry.create(host=self, job=job,
627 is_template=is_template,
628 atomic_group=atomic_group)
jadmanski0afbb632008-06-06 21:10:57 +0000629 # allow recovery of dead hosts from the frontend
630 if not self.active_queue_entry() and self.is_dead():
631 self.status = Host.Status.READY
632 self.save()
633 queue_entry.save()
mblighe8819cd2008-02-15 16:48:40 +0000634
showard08f981b2008-06-24 21:59:03 +0000635 block = IneligibleHostQueue(job=job, host=self)
636 block.save()
637
mblighe8819cd2008-02-15 16:48:40 +0000638
jadmanski0afbb632008-06-06 21:10:57 +0000639 def platform(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800640 """The platform of the host."""
jadmanski0afbb632008-06-06 21:10:57 +0000641 # TODO(showard): slighly hacky?
642 platforms = self.labels.filter(platform=True)
643 if len(platforms) == 0:
644 return None
645 return platforms[0]
646 platform.short_description = 'Platform'
mblighe8819cd2008-02-15 16:48:40 +0000647
648
showardcafd16e2009-05-29 18:37:49 +0000649 @classmethod
650 def check_no_platform(cls, hosts):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800651 """Verify the specified hosts have no associated platforms.
652
653 @param cls: Implicit class object.
654 @param hosts: The hosts to verify.
655 @raises model_logic.ValidationError if any hosts already have a
656 platform.
657 """
showardcafd16e2009-05-29 18:37:49 +0000658 Host.objects.populate_relationships(hosts, Label, 'label_list')
659 errors = []
660 for host in hosts:
661 platforms = [label.name for label in host.label_list
662 if label.platform]
663 if platforms:
664 # do a join, just in case this host has multiple platforms,
665 # we'll be able to see it
666 errors.append('Host %s already has a platform: %s' % (
667 host.hostname, ', '.join(platforms)))
668 if errors:
669 raise model_logic.ValidationError({'labels': '; '.join(errors)})
670
671
jadmanski0afbb632008-06-06 21:10:57 +0000672 def is_dead(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800673 """Returns whether the host is dead (has status repair failed)."""
jadmanski0afbb632008-06-06 21:10:57 +0000674 return self.status == Host.Status.REPAIR_FAILED
mbligh3cab4a72008-03-05 23:19:09 +0000675
676
jadmanski0afbb632008-06-06 21:10:57 +0000677 def active_queue_entry(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800678 """Returns the active queue entry for this host, or None if none."""
jadmanski0afbb632008-06-06 21:10:57 +0000679 active = list(self.hostqueueentry_set.filter(active=True))
680 if not active:
681 return None
682 assert len(active) == 1, ('More than one active entry for '
683 'host ' + self.hostname)
684 return active[0]
mblighe8819cd2008-02-15 16:48:40 +0000685
686
showardf8b19042009-05-12 17:22:49 +0000687 def _get_attribute_model_and_args(self, attribute):
688 return HostAttribute, dict(host=self, attribute=attribute)
showard0957a842009-05-11 19:25:08 +0000689
690
Fang Dengff361592015-02-02 15:27:34 -0800691 @classmethod
692 def get_attribute_model(cls):
693 """Return the attribute model.
694
695 Override method in parent class. See ModelExtensions for details.
696 @returns: The attribute model of Host.
697 """
698 return HostAttribute
699
700
jadmanski0afbb632008-06-06 21:10:57 +0000701 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800702 """Metadata for the Host class."""
showardeab66ce2009-12-23 00:03:56 +0000703 db_table = 'afe_hosts'
mblighe8819cd2008-02-15 16:48:40 +0000704
Fang Dengff361592015-02-02 15:27:34 -0800705
showarda5288b42009-07-28 20:06:08 +0000706 def __unicode__(self):
707 return unicode(self.hostname)
mblighe8819cd2008-02-15 16:48:40 +0000708
709
MK Ryuacf35922014-10-03 14:56:49 -0700710class HostAttribute(dbmodels.Model, model_logic.ModelExtensions):
showard0957a842009-05-11 19:25:08 +0000711 """Arbitrary keyvals associated with hosts."""
Fang Deng86248502014-12-18 16:38:00 -0800712
713 SERIALIZATION_LINKS_TO_KEEP = set(['host'])
Fang Dengff361592015-02-02 15:27:34 -0800714 SERIALIZATION_LOCAL_LINKS_TO_UPDATE = set(['value'])
showard0957a842009-05-11 19:25:08 +0000715 host = dbmodels.ForeignKey(Host)
showarda5288b42009-07-28 20:06:08 +0000716 attribute = dbmodels.CharField(max_length=90)
717 value = dbmodels.CharField(max_length=300)
showard0957a842009-05-11 19:25:08 +0000718
719 objects = model_logic.ExtendedManager()
720
721 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800722 """Metadata for the HostAttribute class."""
showardeab66ce2009-12-23 00:03:56 +0000723 db_table = 'afe_host_attributes'
showard0957a842009-05-11 19:25:08 +0000724
725
Fang Dengff361592015-02-02 15:27:34 -0800726 @classmethod
727 def get_record(cls, data):
728 """Check the database for an identical record.
729
730 Use host_id and attribute to search for a existing record.
731
732 @raises: DoesNotExist, if no record found
733 @raises: MultipleObjectsReturned if multiple records found.
734 """
735 # TODO(fdeng): We should use host_id and attribute together as
736 # a primary key in the db.
737 return cls.objects.get(host_id=data['host_id'],
738 attribute=data['attribute'])
739
740
741 @classmethod
742 def deserialize(cls, data):
743 """Override deserialize in parent class.
744
745 Do not deserialize id as id is not kept consistent on master and shards.
746
747 @param data: A dictionary of data to deserialize.
748
749 @returns: A HostAttribute object.
750 """
751 if data:
752 data.pop('id')
753 return super(HostAttribute, cls).deserialize(data)
754
755
showard7c785282008-05-29 19:45:12 +0000756class Test(dbmodels.Model, model_logic.ModelExtensions):
jadmanski0afbb632008-06-06 21:10:57 +0000757 """\
758 Required:
showard909c7a62008-07-15 21:52:38 +0000759 author: author name
760 description: description of the test
jadmanski0afbb632008-06-06 21:10:57 +0000761 name: test name
showard909c7a62008-07-15 21:52:38 +0000762 time: short, medium, long
763 test_class: This describes the class for your the test belongs in.
764 test_category: This describes the category for your tests
jadmanski0afbb632008-06-06 21:10:57 +0000765 test_type: Client or Server
766 path: path to pass to run_test()
showard909c7a62008-07-15 21:52:38 +0000767 sync_count: is a number >=1 (1 being the default). If it's 1, then it's an
768 async job. If it's >1 it's sync job for that number of machines
showard2bab8f42008-11-12 18:15:22 +0000769 i.e. if sync_count = 2 it is a sync job that requires two
770 machines.
jadmanski0afbb632008-06-06 21:10:57 +0000771 Optional:
showard909c7a62008-07-15 21:52:38 +0000772 dependencies: What the test requires to run. Comma deliminated list
showard989f25d2008-10-01 11:38:11 +0000773 dependency_labels: many-to-many relationship with labels corresponding to
774 test dependencies.
showard909c7a62008-07-15 21:52:38 +0000775 experimental: If this is set to True production servers will ignore the test
776 run_verify: Whether or not the scheduler should run the verify stage
Dan Shi07e09af2013-04-12 09:31:29 -0700777 run_reset: Whether or not the scheduler should run the reset stage
Aviv Keshet9af96d32013-03-05 12:56:24 -0800778 test_retry: Number of times to retry test if the test did not complete
779 successfully. (optional, default: 0)
jadmanski0afbb632008-06-06 21:10:57 +0000780 """
showard909c7a62008-07-15 21:52:38 +0000781 TestTime = enum.Enum('SHORT', 'MEDIUM', 'LONG', start_value=1)
mblighe8819cd2008-02-15 16:48:40 +0000782
showarda5288b42009-07-28 20:06:08 +0000783 name = dbmodels.CharField(max_length=255, unique=True)
784 author = dbmodels.CharField(max_length=255)
785 test_class = dbmodels.CharField(max_length=255)
786 test_category = dbmodels.CharField(max_length=255)
787 dependencies = dbmodels.CharField(max_length=255, blank=True)
jadmanski0afbb632008-06-06 21:10:57 +0000788 description = dbmodels.TextField(blank=True)
showard909c7a62008-07-15 21:52:38 +0000789 experimental = dbmodels.BooleanField(default=True)
Dan Shi07e09af2013-04-12 09:31:29 -0700790 run_verify = dbmodels.BooleanField(default=False)
showard909c7a62008-07-15 21:52:38 +0000791 test_time = dbmodels.SmallIntegerField(choices=TestTime.choices(),
792 default=TestTime.MEDIUM)
Aviv Keshet3dd8beb2013-05-13 17:36:04 -0700793 test_type = dbmodels.SmallIntegerField(
794 choices=control_data.CONTROL_TYPE.choices())
showard909c7a62008-07-15 21:52:38 +0000795 sync_count = dbmodels.IntegerField(default=1)
showarda5288b42009-07-28 20:06:08 +0000796 path = dbmodels.CharField(max_length=255, unique=True)
Aviv Keshet9af96d32013-03-05 12:56:24 -0800797 test_retry = dbmodels.IntegerField(blank=True, default=0)
Dan Shi07e09af2013-04-12 09:31:29 -0700798 run_reset = dbmodels.BooleanField(default=True)
mblighe8819cd2008-02-15 16:48:40 +0000799
showardeab66ce2009-12-23 00:03:56 +0000800 dependency_labels = (
801 dbmodels.ManyToManyField(Label, blank=True,
802 db_table='afe_autotests_dependency_labels'))
jadmanski0afbb632008-06-06 21:10:57 +0000803 name_field = 'name'
804 objects = model_logic.ExtendedManager()
mblighe8819cd2008-02-15 16:48:40 +0000805
806
jamesren35a70222010-02-16 19:30:46 +0000807 def admin_description(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800808 """Returns a string representing the admin description."""
jamesren35a70222010-02-16 19:30:46 +0000809 escaped_description = saxutils.escape(self.description)
810 return '<span style="white-space:pre">%s</span>' % escaped_description
811 admin_description.allow_tags = True
jamesrencae88c62010-02-19 00:12:28 +0000812 admin_description.short_description = 'Description'
jamesren35a70222010-02-16 19:30:46 +0000813
814
jadmanski0afbb632008-06-06 21:10:57 +0000815 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800816 """Metadata for class Test."""
showardeab66ce2009-12-23 00:03:56 +0000817 db_table = 'afe_autotests'
mblighe8819cd2008-02-15 16:48:40 +0000818
showarda5288b42009-07-28 20:06:08 +0000819 def __unicode__(self):
820 return unicode(self.name)
mblighe8819cd2008-02-15 16:48:40 +0000821
822
jamesren4a41e012010-07-16 22:33:48 +0000823class TestParameter(dbmodels.Model):
824 """
825 A declared parameter of a test
826 """
827 test = dbmodels.ForeignKey(Test)
828 name = dbmodels.CharField(max_length=255)
829
830 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800831 """Metadata for class TestParameter."""
jamesren4a41e012010-07-16 22:33:48 +0000832 db_table = 'afe_test_parameters'
833 unique_together = ('test', 'name')
834
835 def __unicode__(self):
Eric Li0a993912011-05-17 12:56:25 -0700836 return u'%s (%s)' % (self.name, self.test.name)
jamesren4a41e012010-07-16 22:33:48 +0000837
838
showard2b9a88b2008-06-13 20:55:03 +0000839class Profiler(dbmodels.Model, model_logic.ModelExtensions):
840 """\
841 Required:
842 name: profiler name
843 test_type: Client or Server
844
845 Optional:
846 description: arbirary text description
847 """
showarda5288b42009-07-28 20:06:08 +0000848 name = dbmodels.CharField(max_length=255, unique=True)
showard2b9a88b2008-06-13 20:55:03 +0000849 description = dbmodels.TextField(blank=True)
850
851 name_field = 'name'
852 objects = model_logic.ExtendedManager()
853
854
855 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800856 """Metadata for class Profiler."""
showardeab66ce2009-12-23 00:03:56 +0000857 db_table = 'afe_profilers'
showard2b9a88b2008-06-13 20:55:03 +0000858
showarda5288b42009-07-28 20:06:08 +0000859 def __unicode__(self):
860 return unicode(self.name)
showard2b9a88b2008-06-13 20:55:03 +0000861
862
showard7c785282008-05-29 19:45:12 +0000863class AclGroup(dbmodels.Model, model_logic.ModelExtensions):
jadmanski0afbb632008-06-06 21:10:57 +0000864 """\
865 Required:
866 name: name of ACL group
mblighe8819cd2008-02-15 16:48:40 +0000867
jadmanski0afbb632008-06-06 21:10:57 +0000868 Optional:
869 description: arbitrary description of group
870 """
Jakob Juelich3bb7c802014-09-02 16:31:11 -0700871
872 SERIALIZATION_LINKS_TO_FOLLOW = set(['users'])
873
showarda5288b42009-07-28 20:06:08 +0000874 name = dbmodels.CharField(max_length=255, unique=True)
875 description = dbmodels.CharField(max_length=255, blank=True)
showardeab66ce2009-12-23 00:03:56 +0000876 users = dbmodels.ManyToManyField(User, blank=False,
877 db_table='afe_acl_groups_users')
878 hosts = dbmodels.ManyToManyField(Host, blank=True,
879 db_table='afe_acl_groups_hosts')
mblighe8819cd2008-02-15 16:48:40 +0000880
jadmanski0afbb632008-06-06 21:10:57 +0000881 name_field = 'name'
882 objects = model_logic.ExtendedManager()
showardeb3be4d2008-04-21 20:59:26 +0000883
showard08f981b2008-06-24 21:59:03 +0000884 @staticmethod
showard3dd47c22008-07-10 00:41:36 +0000885 def check_for_acl_violation_hosts(hosts):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800886 """Verify the current user has access to the specified hosts.
887
888 @param hosts: The hosts to verify against.
889 @raises AclAccessViolation if the current user doesn't have access
890 to a host.
891 """
showard64a95952010-01-13 21:27:16 +0000892 user = User.current_user()
showard3dd47c22008-07-10 00:41:36 +0000893 if user.is_superuser():
showard9dbdcda2008-10-14 17:34:36 +0000894 return
showard3dd47c22008-07-10 00:41:36 +0000895 accessible_host_ids = set(
showardd9ac4452009-02-07 02:04:37 +0000896 host.id for host in Host.objects.filter(aclgroup__users=user))
showard3dd47c22008-07-10 00:41:36 +0000897 for host in hosts:
898 # Check if the user has access to this host,
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800899 # but only if it is not a metahost or a one-time-host.
showard98ead172009-06-22 18:13:24 +0000900 no_access = (isinstance(host, Host)
901 and not host.invalid
902 and int(host.id) not in accessible_host_ids)
903 if no_access:
showardeaa408e2009-09-11 18:45:31 +0000904 raise AclAccessViolation("%s does not have access to %s" %
905 (str(user), str(host)))
showard3dd47c22008-07-10 00:41:36 +0000906
showard9dbdcda2008-10-14 17:34:36 +0000907
908 @staticmethod
showarddc817512008-11-12 18:16:41 +0000909 def check_abort_permissions(queue_entries):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800910 """Look for queue entries that aren't abortable by the current user.
911
912 An entry is not abortable if:
913 * the job isn't owned by this user, and
showarddc817512008-11-12 18:16:41 +0000914 * the machine isn't ACL-accessible, or
915 * the machine is in the "Everyone" ACL
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800916
917 @param queue_entries: The queue entries to check.
918 @raises AclAccessViolation if a queue entry is not abortable by the
919 current user.
showarddc817512008-11-12 18:16:41 +0000920 """
showard64a95952010-01-13 21:27:16 +0000921 user = User.current_user()
showard9dbdcda2008-10-14 17:34:36 +0000922 if user.is_superuser():
923 return
showarddc817512008-11-12 18:16:41 +0000924 not_owned = queue_entries.exclude(job__owner=user.login)
925 # I do this using ID sets instead of just Django filters because
showarda5288b42009-07-28 20:06:08 +0000926 # filtering on M2M dbmodels is broken in Django 0.96. It's better in
927 # 1.0.
928 # TODO: Use Django filters, now that we're using 1.0.
showarddc817512008-11-12 18:16:41 +0000929 accessible_ids = set(
930 entry.id for entry
showardd9ac4452009-02-07 02:04:37 +0000931 in not_owned.filter(host__aclgroup__users__login=user.login))
showarddc817512008-11-12 18:16:41 +0000932 public_ids = set(entry.id for entry
showardd9ac4452009-02-07 02:04:37 +0000933 in not_owned.filter(host__aclgroup__name='Everyone'))
showarddc817512008-11-12 18:16:41 +0000934 cannot_abort = [entry for entry in not_owned.select_related()
935 if entry.id not in accessible_ids
936 or entry.id in public_ids]
937 if len(cannot_abort) == 0:
938 return
939 entry_names = ', '.join('%s-%s/%s' % (entry.job.id, entry.job.owner,
showard3f15eed2008-11-14 22:40:48 +0000940 entry.host_or_metahost_name())
showarddc817512008-11-12 18:16:41 +0000941 for entry in cannot_abort)
942 raise AclAccessViolation('You cannot abort the following job entries: '
943 + entry_names)
showard9dbdcda2008-10-14 17:34:36 +0000944
945
showard3dd47c22008-07-10 00:41:36 +0000946 def check_for_acl_violation_acl_group(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800947 """Verifies the current user has acces to this ACL group.
948
949 @raises AclAccessViolation if the current user doesn't have access to
950 this ACL group.
951 """
showard64a95952010-01-13 21:27:16 +0000952 user = User.current_user()
showard3dd47c22008-07-10 00:41:36 +0000953 if user.is_superuser():
showard8cbaf1e2009-09-08 16:27:04 +0000954 return
955 if self.name == 'Everyone':
956 raise AclAccessViolation("You cannot modify 'Everyone'!")
showard3dd47c22008-07-10 00:41:36 +0000957 if not user in self.users.all():
958 raise AclAccessViolation("You do not have access to %s"
959 % self.name)
960
961 @staticmethod
showard08f981b2008-06-24 21:59:03 +0000962 def on_host_membership_change():
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800963 """Invoked when host membership changes."""
showard08f981b2008-06-24 21:59:03 +0000964 everyone = AclGroup.objects.get(name='Everyone')
965
showard3dd47c22008-07-10 00:41:36 +0000966 # find hosts that aren't in any ACL group and add them to Everyone
showard08f981b2008-06-24 21:59:03 +0000967 # TODO(showard): this is a bit of a hack, since the fact that this query
968 # works is kind of a coincidence of Django internals. This trick
969 # doesn't work in general (on all foreign key relationships). I'll
970 # replace it with a better technique when the need arises.
showardd9ac4452009-02-07 02:04:37 +0000971 orphaned_hosts = Host.valid_objects.filter(aclgroup__id__isnull=True)
showard08f981b2008-06-24 21:59:03 +0000972 everyone.hosts.add(*orphaned_hosts.distinct())
973
974 # find hosts in both Everyone and another ACL group, and remove them
975 # from Everyone
showarda5288b42009-07-28 20:06:08 +0000976 hosts_in_everyone = Host.valid_objects.filter(aclgroup__name='Everyone')
977 acled_hosts = set()
978 for host in hosts_in_everyone:
979 # Has an ACL group other than Everyone
980 if host.aclgroup_set.count() > 1:
981 acled_hosts.add(host)
982 everyone.hosts.remove(*acled_hosts)
showard08f981b2008-06-24 21:59:03 +0000983
984
985 def delete(self):
showard3dd47c22008-07-10 00:41:36 +0000986 if (self.name == 'Everyone'):
987 raise AclAccessViolation("You cannot delete 'Everyone'!")
988 self.check_for_acl_violation_acl_group()
showard08f981b2008-06-24 21:59:03 +0000989 super(AclGroup, self).delete()
990 self.on_host_membership_change()
991
992
showard04f2cd82008-07-25 20:53:31 +0000993 def add_current_user_if_empty(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -0800994 """Adds the current user if the set of users is empty."""
showard04f2cd82008-07-25 20:53:31 +0000995 if not self.users.count():
showard64a95952010-01-13 21:27:16 +0000996 self.users.add(User.current_user())
showard04f2cd82008-07-25 20:53:31 +0000997
998
showard8cbaf1e2009-09-08 16:27:04 +0000999 def perform_after_save(self, change):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001000 """Called after a save.
1001
1002 @param change: Whether there was a change.
1003 """
showard8cbaf1e2009-09-08 16:27:04 +00001004 if not change:
showard64a95952010-01-13 21:27:16 +00001005 self.users.add(User.current_user())
showard8cbaf1e2009-09-08 16:27:04 +00001006 self.add_current_user_if_empty()
1007 self.on_host_membership_change()
1008
1009
1010 def save(self, *args, **kwargs):
Jakob Juelich116ff0f2014-09-17 18:25:16 -07001011 change = bool(self.id)
1012 if change:
showard8cbaf1e2009-09-08 16:27:04 +00001013 # Check the original object for an ACL violation
Jakob Juelich116ff0f2014-09-17 18:25:16 -07001014 AclGroup.objects.get(id=self.id).check_for_acl_violation_acl_group()
showard8cbaf1e2009-09-08 16:27:04 +00001015 super(AclGroup, self).save(*args, **kwargs)
Jakob Juelich116ff0f2014-09-17 18:25:16 -07001016 self.perform_after_save(change)
showard8cbaf1e2009-09-08 16:27:04 +00001017
showardeb3be4d2008-04-21 20:59:26 +00001018
jadmanski0afbb632008-06-06 21:10:57 +00001019 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001020 """Metadata for class AclGroup."""
showardeab66ce2009-12-23 00:03:56 +00001021 db_table = 'afe_acl_groups'
mblighe8819cd2008-02-15 16:48:40 +00001022
showarda5288b42009-07-28 20:06:08 +00001023 def __unicode__(self):
1024 return unicode(self.name)
mblighe8819cd2008-02-15 16:48:40 +00001025
mblighe8819cd2008-02-15 16:48:40 +00001026
jamesren4a41e012010-07-16 22:33:48 +00001027class Kernel(dbmodels.Model):
1028 """
1029 A kernel configuration for a parameterized job
1030 """
1031 version = dbmodels.CharField(max_length=255)
1032 cmdline = dbmodels.CharField(max_length=255, blank=True)
1033
1034 @classmethod
1035 def create_kernels(cls, kernel_list):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001036 """Creates all kernels in the kernel list.
jamesren4a41e012010-07-16 22:33:48 +00001037
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001038 @param cls: Implicit class object.
1039 @param kernel_list: A list of dictionaries that describe the kernels,
1040 in the same format as the 'kernel' argument to
1041 rpc_interface.generate_control_file.
1042 @return A list of the created kernels.
jamesren4a41e012010-07-16 22:33:48 +00001043 """
1044 if not kernel_list:
1045 return None
1046 return [cls._create(kernel) for kernel in kernel_list]
1047
1048
1049 @classmethod
1050 def _create(cls, kernel_dict):
1051 version = kernel_dict.pop('version')
1052 cmdline = kernel_dict.pop('cmdline', '')
1053
1054 if kernel_dict:
1055 raise Exception('Extraneous kernel arguments remain: %r'
1056 % kernel_dict)
1057
1058 kernel, _ = cls.objects.get_or_create(version=version,
1059 cmdline=cmdline)
1060 return kernel
1061
1062
1063 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001064 """Metadata for class Kernel."""
jamesren4a41e012010-07-16 22:33:48 +00001065 db_table = 'afe_kernels'
1066 unique_together = ('version', 'cmdline')
1067
1068 def __unicode__(self):
1069 return u'%s %s' % (self.version, self.cmdline)
1070
1071
1072class ParameterizedJob(dbmodels.Model):
1073 """
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001074 Auxiliary configuration for a parameterized job.
jamesren4a41e012010-07-16 22:33:48 +00001075 """
1076 test = dbmodels.ForeignKey(Test)
1077 label = dbmodels.ForeignKey(Label, null=True)
1078 use_container = dbmodels.BooleanField(default=False)
1079 profile_only = dbmodels.BooleanField(default=False)
1080 upload_kernel_config = dbmodels.BooleanField(default=False)
1081
1082 kernels = dbmodels.ManyToManyField(
1083 Kernel, db_table='afe_parameterized_job_kernels')
1084 profilers = dbmodels.ManyToManyField(
1085 Profiler, through='ParameterizedJobProfiler')
1086
1087
1088 @classmethod
1089 def smart_get(cls, id_or_name, *args, **kwargs):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001090 """For compatibility with Job.add_object.
1091
1092 @param cls: Implicit class object.
1093 @param id_or_name: The ID or name to get.
1094 @param args: Non-keyword arguments.
1095 @param kwargs: Keyword arguments.
1096 """
jamesren4a41e012010-07-16 22:33:48 +00001097 return cls.objects.get(pk=id_or_name)
1098
1099
1100 def job(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001101 """Returns the job if it exists, or else None."""
jamesren4a41e012010-07-16 22:33:48 +00001102 jobs = self.job_set.all()
1103 assert jobs.count() <= 1
1104 return jobs and jobs[0] or None
1105
1106
1107 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001108 """Metadata for class ParameterizedJob."""
jamesren4a41e012010-07-16 22:33:48 +00001109 db_table = 'afe_parameterized_jobs'
1110
1111 def __unicode__(self):
1112 return u'%s (parameterized) - %s' % (self.test.name, self.job())
1113
1114
1115class ParameterizedJobProfiler(dbmodels.Model):
1116 """
1117 A profiler to run on a parameterized job
1118 """
1119 parameterized_job = dbmodels.ForeignKey(ParameterizedJob)
1120 profiler = dbmodels.ForeignKey(Profiler)
1121
1122 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001123 """Metedata for class ParameterizedJobProfiler."""
jamesren4a41e012010-07-16 22:33:48 +00001124 db_table = 'afe_parameterized_jobs_profilers'
1125 unique_together = ('parameterized_job', 'profiler')
1126
1127
1128class ParameterizedJobProfilerParameter(dbmodels.Model):
1129 """
1130 A parameter for a profiler in a parameterized job
1131 """
1132 parameterized_job_profiler = dbmodels.ForeignKey(ParameterizedJobProfiler)
1133 parameter_name = dbmodels.CharField(max_length=255)
1134 parameter_value = dbmodels.TextField()
1135 parameter_type = dbmodels.CharField(
1136 max_length=8, choices=model_attributes.ParameterTypes.choices())
1137
1138 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001139 """Metadata for class ParameterizedJobProfilerParameter."""
jamesren4a41e012010-07-16 22:33:48 +00001140 db_table = 'afe_parameterized_job_profiler_parameters'
1141 unique_together = ('parameterized_job_profiler', 'parameter_name')
1142
1143 def __unicode__(self):
1144 return u'%s - %s' % (self.parameterized_job_profiler.profiler.name,
1145 self.parameter_name)
1146
1147
1148class ParameterizedJobParameter(dbmodels.Model):
1149 """
1150 Parameters for a parameterized job
1151 """
1152 parameterized_job = dbmodels.ForeignKey(ParameterizedJob)
1153 test_parameter = dbmodels.ForeignKey(TestParameter)
1154 parameter_value = dbmodels.TextField()
1155 parameter_type = dbmodels.CharField(
1156 max_length=8, choices=model_attributes.ParameterTypes.choices())
1157
1158 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001159 """Metadata for class ParameterizedJobParameter."""
jamesren4a41e012010-07-16 22:33:48 +00001160 db_table = 'afe_parameterized_job_parameters'
1161 unique_together = ('parameterized_job', 'test_parameter')
1162
1163 def __unicode__(self):
1164 return u'%s - %s' % (self.parameterized_job.job().name,
1165 self.test_parameter.name)
1166
1167
showard7c785282008-05-29 19:45:12 +00001168class JobManager(model_logic.ExtendedManager):
jadmanski0afbb632008-06-06 21:10:57 +00001169 'Custom manager to provide efficient status counts querying.'
1170 def get_status_counts(self, job_ids):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001171 """Returns a dict mapping the given job IDs to their status count dicts.
1172
1173 @param job_ids: A list of job IDs.
jadmanski0afbb632008-06-06 21:10:57 +00001174 """
1175 if not job_ids:
1176 return {}
1177 id_list = '(%s)' % ','.join(str(job_id) for job_id in job_ids)
1178 cursor = connection.cursor()
1179 cursor.execute("""
showardd3dc1992009-04-22 21:01:40 +00001180 SELECT job_id, status, aborted, complete, COUNT(*)
showardeab66ce2009-12-23 00:03:56 +00001181 FROM afe_host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +00001182 WHERE job_id IN %s
showardd3dc1992009-04-22 21:01:40 +00001183 GROUP BY job_id, status, aborted, complete
jadmanski0afbb632008-06-06 21:10:57 +00001184 """ % id_list)
showard25aaf3f2009-06-08 23:23:40 +00001185 all_job_counts = dict((job_id, {}) for job_id in job_ids)
showardd3dc1992009-04-22 21:01:40 +00001186 for job_id, status, aborted, complete, count in cursor.fetchall():
showard25aaf3f2009-06-08 23:23:40 +00001187 job_dict = all_job_counts[job_id]
showardd3dc1992009-04-22 21:01:40 +00001188 full_status = HostQueueEntry.compute_full_status(status, aborted,
1189 complete)
showardb6d16622009-05-26 19:35:29 +00001190 job_dict.setdefault(full_status, 0)
showard25aaf3f2009-06-08 23:23:40 +00001191 job_dict[full_status] += count
jadmanski0afbb632008-06-06 21:10:57 +00001192 return all_job_counts
mblighe8819cd2008-02-15 16:48:40 +00001193
1194
showard7c785282008-05-29 19:45:12 +00001195class Job(dbmodels.Model, model_logic.ModelExtensions):
jadmanski0afbb632008-06-06 21:10:57 +00001196 """\
1197 owner: username of job owner
1198 name: job name (does not have to be unique)
Alex Miller7d658cf2013-09-04 16:00:35 -07001199 priority: Integer priority value. Higher is more important.
jadmanski0afbb632008-06-06 21:10:57 +00001200 control_file: contents of control file
1201 control_type: Client or Server
1202 created_on: date of job creation
1203 submitted_on: date of job submission
showard2bab8f42008-11-12 18:15:22 +00001204 synch_count: how many hosts should be used per autoserv execution
showard909c7a62008-07-15 21:52:38 +00001205 run_verify: Whether or not to run the verify phase
Dan Shi07e09af2013-04-12 09:31:29 -07001206 run_reset: Whether or not to run the reset phase
Simran Basi94dc0032013-11-12 14:09:46 -08001207 timeout: DEPRECATED - hours from queuing time until job times out
1208 timeout_mins: minutes from job queuing time until the job times out
Simran Basi34217022012-11-06 13:43:15 -08001209 max_runtime_hrs: DEPRECATED - hours from job starting time until job
1210 times out
1211 max_runtime_mins: minutes from job starting time until job times out
showard542e8402008-09-19 20:16:18 +00001212 email_list: list of people to email on completion delimited by any of:
1213 white space, ',', ':', ';'
showard989f25d2008-10-01 11:38:11 +00001214 dependency_labels: many-to-many relationship with labels corresponding to
1215 job dependencies
showard21baa452008-10-21 00:08:39 +00001216 reboot_before: Never, If dirty, or Always
1217 reboot_after: Never, If all tests passed, or Always
showarda1e74b32009-05-12 17:32:04 +00001218 parse_failed_repair: if True, a failed repair launched by this job will have
1219 its results parsed as part of the job.
jamesren76fcf192010-04-21 20:39:50 +00001220 drone_set: The set of drones to run this job on
Aviv Keshet0b9cfc92013-02-05 11:36:02 -08001221 parent_job: Parent job (optional)
Aviv Keshetcd1ff9b2013-03-01 14:55:19 -08001222 test_retry: Number of times to retry test if the test did not complete
1223 successfully. (optional, default: 0)
Dan Shic9e17142015-02-19 11:50:55 -08001224 require_ssp: Require server-side packaging unless require_ssp is set to
1225 False. (optional, default: None)
jadmanski0afbb632008-06-06 21:10:57 +00001226 """
Jakob Juelich3bb7c802014-09-02 16:31:11 -07001227
1228 # TODO: Investigate, if jobkeyval_set is really needed.
1229 # dynamic_suite will write them into an attached file for the drone, but
1230 # it doesn't seem like they are actually used. If they aren't used, remove
1231 # jobkeyval_set here.
1232 SERIALIZATION_LINKS_TO_FOLLOW = set(['dependency_labels',
1233 'hostqueueentry_set',
1234 'jobkeyval_set',
1235 'shard'])
1236
1237
Jakob Juelichf88fa932014-09-03 17:58:04 -07001238 def _deserialize_relation(self, link, data):
1239 if link in ['hostqueueentry_set', 'jobkeyval_set']:
1240 for obj in data:
1241 obj['job_id'] = self.id
1242
1243 super(Job, self)._deserialize_relation(link, data)
1244
1245
1246 def custom_deserialize_relation(self, link, data):
Jakob Juelich116ff0f2014-09-17 18:25:16 -07001247 assert link == 'shard', 'Link %s should not be deserialized' % link
Jakob Juelichf88fa932014-09-03 17:58:04 -07001248 self.shard = Shard.deserialize(data)
1249
1250
Jakob Juelicha94efe62014-09-18 16:02:49 -07001251 def sanity_check_update_from_shard(self, shard, updated_serialized):
Jakob Juelich02e61292014-10-17 12:36:55 -07001252 # If the job got aborted on the master after the client fetched it
1253 # no shard_id will be set. The shard might still push updates though,
1254 # as the job might complete before the abort bit syncs to the shard.
1255 # Alternative considered: The master scheduler could be changed to not
1256 # set aborted jobs to completed that are sharded out. But that would
1257 # require database queries and seemed more complicated to implement.
1258 # This seems safe to do, as there won't be updates pushed from the wrong
1259 # shards should be powered off and wiped hen they are removed from the
1260 # master.
1261 if self.shard_id and self.shard_id != shard.id:
Jakob Juelicha94efe62014-09-18 16:02:49 -07001262 raise error.UnallowedRecordsSentToMaster(
1263 'Job id=%s is assigned to shard (%s). Cannot update it with %s '
1264 'from shard %s.' % (self.id, self.shard_id, updated_serialized,
1265 shard.id))
1266
1267
Simran Basi94dc0032013-11-12 14:09:46 -08001268 # TIMEOUT is deprecated.
showardb1e51872008-10-07 11:08:18 +00001269 DEFAULT_TIMEOUT = global_config.global_config.get_config_value(
Simran Basi94dc0032013-11-12 14:09:46 -08001270 'AUTOTEST_WEB', 'job_timeout_default', default=24)
1271 DEFAULT_TIMEOUT_MINS = global_config.global_config.get_config_value(
1272 'AUTOTEST_WEB', 'job_timeout_mins_default', default=24*60)
Simran Basi34217022012-11-06 13:43:15 -08001273 # MAX_RUNTIME_HRS is deprecated. Will be removed after switch to mins is
1274 # completed.
showard12f3e322009-05-13 21:27:42 +00001275 DEFAULT_MAX_RUNTIME_HRS = global_config.global_config.get_config_value(
1276 'AUTOTEST_WEB', 'job_max_runtime_hrs_default', default=72)
Simran Basi34217022012-11-06 13:43:15 -08001277 DEFAULT_MAX_RUNTIME_MINS = global_config.global_config.get_config_value(
1278 'AUTOTEST_WEB', 'job_max_runtime_mins_default', default=72*60)
showarda1e74b32009-05-12 17:32:04 +00001279 DEFAULT_PARSE_FAILED_REPAIR = global_config.global_config.get_config_value(
1280 'AUTOTEST_WEB', 'parse_failed_repair_default', type=bool,
1281 default=False)
showardb1e51872008-10-07 11:08:18 +00001282
showarda5288b42009-07-28 20:06:08 +00001283 owner = dbmodels.CharField(max_length=255)
1284 name = dbmodels.CharField(max_length=255)
Alex Miller7d658cf2013-09-04 16:00:35 -07001285 priority = dbmodels.SmallIntegerField(default=priorities.Priority.DEFAULT)
jamesren4a41e012010-07-16 22:33:48 +00001286 control_file = dbmodels.TextField(null=True, blank=True)
Aviv Keshet3dd8beb2013-05-13 17:36:04 -07001287 control_type = dbmodels.SmallIntegerField(
1288 choices=control_data.CONTROL_TYPE.choices(),
1289 blank=True, # to allow 0
1290 default=control_data.CONTROL_TYPE.CLIENT)
showard68c7aa02008-10-09 16:49:11 +00001291 created_on = dbmodels.DateTimeField()
Simran Basi8d89b642014-05-02 17:33:20 -07001292 synch_count = dbmodels.IntegerField(blank=True, default=0)
showardb1e51872008-10-07 11:08:18 +00001293 timeout = dbmodels.IntegerField(default=DEFAULT_TIMEOUT)
Dan Shi07e09af2013-04-12 09:31:29 -07001294 run_verify = dbmodels.BooleanField(default=False)
showarda5288b42009-07-28 20:06:08 +00001295 email_list = dbmodels.CharField(max_length=250, blank=True)
showardeab66ce2009-12-23 00:03:56 +00001296 dependency_labels = (
1297 dbmodels.ManyToManyField(Label, blank=True,
1298 db_table='afe_jobs_dependency_labels'))
jamesrendd855242010-03-02 22:23:44 +00001299 reboot_before = dbmodels.SmallIntegerField(
1300 choices=model_attributes.RebootBefore.choices(), blank=True,
1301 default=DEFAULT_REBOOT_BEFORE)
1302 reboot_after = dbmodels.SmallIntegerField(
1303 choices=model_attributes.RebootAfter.choices(), blank=True,
1304 default=DEFAULT_REBOOT_AFTER)
showarda1e74b32009-05-12 17:32:04 +00001305 parse_failed_repair = dbmodels.BooleanField(
1306 default=DEFAULT_PARSE_FAILED_REPAIR)
Simran Basi34217022012-11-06 13:43:15 -08001307 # max_runtime_hrs is deprecated. Will be removed after switch to mins is
1308 # completed.
showard12f3e322009-05-13 21:27:42 +00001309 max_runtime_hrs = dbmodels.IntegerField(default=DEFAULT_MAX_RUNTIME_HRS)
Simran Basi34217022012-11-06 13:43:15 -08001310 max_runtime_mins = dbmodels.IntegerField(default=DEFAULT_MAX_RUNTIME_MINS)
jamesren76fcf192010-04-21 20:39:50 +00001311 drone_set = dbmodels.ForeignKey(DroneSet, null=True, blank=True)
mblighe8819cd2008-02-15 16:48:40 +00001312
jamesren4a41e012010-07-16 22:33:48 +00001313 parameterized_job = dbmodels.ForeignKey(ParameterizedJob, null=True,
1314 blank=True)
1315
Aviv Keshet0b9cfc92013-02-05 11:36:02 -08001316 parent_job = dbmodels.ForeignKey('self', blank=True, null=True)
mblighe8819cd2008-02-15 16:48:40 +00001317
Aviv Keshetcd1ff9b2013-03-01 14:55:19 -08001318 test_retry = dbmodels.IntegerField(blank=True, default=0)
1319
Dan Shi07e09af2013-04-12 09:31:29 -07001320 run_reset = dbmodels.BooleanField(default=True)
1321
Simran Basi94dc0032013-11-12 14:09:46 -08001322 timeout_mins = dbmodels.IntegerField(default=DEFAULT_TIMEOUT_MINS)
1323
Jakob Juelich8421d592014-09-17 15:27:06 -07001324 # If this is None on the master, a slave should be found.
1325 # If this is None on a slave, it should be synced back to the master
Jakob Jülich92c06332014-08-25 19:06:57 +00001326 shard = dbmodels.ForeignKey(Shard, blank=True, null=True)
1327
Dan Shic9e17142015-02-19 11:50:55 -08001328 # If this is None, server-side packaging will be used for server side test,
1329 # unless it's disabled in global config AUTOSERV/enable_ssp_container.
1330 require_ssp = dbmodels.NullBooleanField(default=None, blank=True, null=True)
1331
jadmanski0afbb632008-06-06 21:10:57 +00001332 # custom manager
1333 objects = JobManager()
mblighe8819cd2008-02-15 16:48:40 +00001334
1335
Alex Millerec212252014-02-28 16:48:34 -08001336 @decorators.cached_property
1337 def labels(self):
1338 """All the labels of this job"""
1339 # We need to convert dependency_labels to a list, because all() gives us
1340 # back an iterator, and storing/caching an iterator means we'd only be
1341 # able to read from it once.
1342 return list(self.dependency_labels.all())
1343
1344
jadmanski0afbb632008-06-06 21:10:57 +00001345 def is_server_job(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001346 """Returns whether this job is of type server."""
Aviv Keshet3dd8beb2013-05-13 17:36:04 -07001347 return self.control_type == control_data.CONTROL_TYPE.SERVER
mblighe8819cd2008-02-15 16:48:40 +00001348
1349
jadmanski0afbb632008-06-06 21:10:57 +00001350 @classmethod
jamesren4a41e012010-07-16 22:33:48 +00001351 def parameterized_jobs_enabled(cls):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001352 """Returns whether parameterized jobs are enabled.
1353
1354 @param cls: Implicit class object.
1355 """
jamesren4a41e012010-07-16 22:33:48 +00001356 return global_config.global_config.get_config_value(
1357 'AUTOTEST_WEB', 'parameterized_jobs', type=bool)
1358
1359
1360 @classmethod
1361 def check_parameterized_job(cls, control_file, parameterized_job):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001362 """Checks that the job is valid given the global config settings.
jamesren4a41e012010-07-16 22:33:48 +00001363
1364 First, either control_file must be set, or parameterized_job must be
1365 set, but not both. Second, parameterized_job must be set if and only if
1366 the parameterized_jobs option in the global config is set to True.
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001367
1368 @param cls: Implict class object.
1369 @param control_file: A control file.
1370 @param parameterized_job: A parameterized job.
jamesren4a41e012010-07-16 22:33:48 +00001371 """
1372 if not (bool(control_file) ^ bool(parameterized_job)):
1373 raise Exception('Job must have either control file or '
1374 'parameterization, but not both')
1375
1376 parameterized_jobs_enabled = cls.parameterized_jobs_enabled()
1377 if control_file and parameterized_jobs_enabled:
1378 raise Exception('Control file specified, but parameterized jobs '
1379 'are enabled')
1380 if parameterized_job and not parameterized_jobs_enabled:
1381 raise Exception('Parameterized job specified, but parameterized '
1382 'jobs are not enabled')
1383
1384
1385 @classmethod
showarda1e74b32009-05-12 17:32:04 +00001386 def create(cls, owner, options, hosts):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001387 """Creates a job.
1388
1389 The job is created by taking some information (the listed args) and
1390 filling in the rest of the necessary information.
1391
1392 @param cls: Implicit class object.
1393 @param owner: The owner for the job.
1394 @param options: An options object.
1395 @param hosts: The hosts to use.
jadmanski0afbb632008-06-06 21:10:57 +00001396 """
showard3dd47c22008-07-10 00:41:36 +00001397 AclGroup.check_for_acl_violation_hosts(hosts)
showard4d233752010-01-20 19:06:40 +00001398
jamesren4a41e012010-07-16 22:33:48 +00001399 control_file = options.get('control_file')
1400 parameterized_job = options.get('parameterized_job')
jamesren4a41e012010-07-16 22:33:48 +00001401
Paul Pendlebury5a8c6ad2011-02-01 07:20:17 -08001402 # The current implementation of parameterized jobs requires that only
1403 # control files or parameterized jobs are used. Using the image
1404 # parameter on autoupdate_ParameterizedJob doesn't mix pure
1405 # parameterized jobs and control files jobs, it does muck enough with
1406 # normal jobs by adding a parameterized id to them that this check will
1407 # fail. So for now we just skip this check.
1408 # cls.check_parameterized_job(control_file=control_file,
1409 # parameterized_job=parameterized_job)
showard4d233752010-01-20 19:06:40 +00001410 user = User.current_user()
1411 if options.get('reboot_before') is None:
1412 options['reboot_before'] = user.get_reboot_before_display()
1413 if options.get('reboot_after') is None:
1414 options['reboot_after'] = user.get_reboot_after_display()
1415
jamesren76fcf192010-04-21 20:39:50 +00001416 drone_set = DroneSet.resolve_name(options.get('drone_set'))
1417
Simran Basi94dc0032013-11-12 14:09:46 -08001418 if options.get('timeout_mins') is None and options.get('timeout'):
1419 options['timeout_mins'] = options['timeout'] * 60
1420
jadmanski0afbb632008-06-06 21:10:57 +00001421 job = cls.add_object(
showarda1e74b32009-05-12 17:32:04 +00001422 owner=owner,
1423 name=options['name'],
1424 priority=options['priority'],
jamesren4a41e012010-07-16 22:33:48 +00001425 control_file=control_file,
showarda1e74b32009-05-12 17:32:04 +00001426 control_type=options['control_type'],
1427 synch_count=options.get('synch_count'),
Simran Basi94dc0032013-11-12 14:09:46 -08001428 # timeout needs to be deleted in the future.
showarda1e74b32009-05-12 17:32:04 +00001429 timeout=options.get('timeout'),
Simran Basi94dc0032013-11-12 14:09:46 -08001430 timeout_mins=options.get('timeout_mins'),
Simran Basi34217022012-11-06 13:43:15 -08001431 max_runtime_mins=options.get('max_runtime_mins'),
showarda1e74b32009-05-12 17:32:04 +00001432 run_verify=options.get('run_verify'),
1433 email_list=options.get('email_list'),
1434 reboot_before=options.get('reboot_before'),
1435 reboot_after=options.get('reboot_after'),
1436 parse_failed_repair=options.get('parse_failed_repair'),
jamesren76fcf192010-04-21 20:39:50 +00001437 created_on=datetime.now(),
jamesren4a41e012010-07-16 22:33:48 +00001438 drone_set=drone_set,
Aviv Keshet18308922013-02-19 17:49:49 -08001439 parameterized_job=parameterized_job,
Aviv Keshetcd1ff9b2013-03-01 14:55:19 -08001440 parent_job=options.get('parent_job_id'),
Dan Shi07e09af2013-04-12 09:31:29 -07001441 test_retry=options.get('test_retry'),
Dan Shic9e17142015-02-19 11:50:55 -08001442 run_reset=options.get('run_reset'),
1443 require_ssp=options.get('require_ssp'))
mblighe8819cd2008-02-15 16:48:40 +00001444
showarda1e74b32009-05-12 17:32:04 +00001445 job.dependency_labels = options['dependencies']
showardc1a98d12010-01-15 00:22:22 +00001446
jamesrend8b6e172010-04-16 23:45:00 +00001447 if options.get('keyvals'):
showardc1a98d12010-01-15 00:22:22 +00001448 for key, value in options['keyvals'].iteritems():
1449 JobKeyval.objects.create(job=job, key=key, value=value)
1450
jadmanski0afbb632008-06-06 21:10:57 +00001451 return job
mblighe8819cd2008-02-15 16:48:40 +00001452
1453
Jakob Juelich59cfe542014-09-02 16:37:46 -07001454 @classmethod
Prashanth Balasubramanian8c98ac12014-12-23 11:26:44 -08001455 def _add_filters_for_shard_assignment(cls, query, known_ids):
1456 """Exclude jobs that should be not sent to shard.
1457
1458 This is a helper that filters out the following jobs:
1459 - Non-aborted jobs known to shard as specified in |known_ids|.
1460 Note for jobs aborted on master, even if already known to shard,
1461 will be sent to shard again so that shard can abort them.
1462 - Completed jobs
1463 - Active jobs
1464 @param query: A query that finds jobs for shards, to which the 'exclude'
1465 filters will be applied.
1466 @param known_ids: List of all ids of incomplete jobs, the shard already
1467 knows about.
1468
1469 @returns: A django QuerySet after filtering out unnecessary jobs.
1470
1471 """
1472 return query.exclude(
1473 id__in=known_ids,
1474 hostqueueentry__aborted=False
1475 ).exclude(
1476 hostqueueentry__complete=True
1477 ).exclude(
1478 hostqueueentry__active=True)
1479
1480
1481 @classmethod
Jakob Juelich1b525742014-09-30 13:08:07 -07001482 def assign_to_shard(cls, shard, known_ids):
Jakob Juelich59cfe542014-09-02 16:37:46 -07001483 """Assigns unassigned jobs to a shard.
1484
Jakob Juelich1b525742014-09-30 13:08:07 -07001485 For all labels that have been assigned to this shard, all jobs that
1486 have this label, are assigned to this shard.
1487
1488 Jobs that are assigned to the shard but aren't already present on the
1489 shard are returned.
1490
Jakob Juelich59cfe542014-09-02 16:37:46 -07001491 @param shard: The shard to assign jobs to.
Jakob Juelich1b525742014-09-30 13:08:07 -07001492 @param known_ids: List of all ids of incomplete jobs, the shard already
1493 knows about.
1494 This is used to figure out which jobs should be sent
1495 to the shard. If shard_ids were used instead, jobs
1496 would only be transferred once, even if the client
1497 failed persisting them.
1498 The number of unfinished jobs usually lies in O(1000).
1499 Assuming one id takes 8 chars in the json, this means
1500 overhead that lies in the lower kilobyte range.
1501 A not in query with 5000 id's takes about 30ms.
1502
Jakob Juelich59cfe542014-09-02 16:37:46 -07001503 @returns The job objects that should be sent to the shard.
1504 """
1505 # Disclaimer: Concurrent heartbeats should not occur in today's setup.
1506 # If this changes or they are triggered manually, this applies:
1507 # Jobs may be returned more than once by concurrent calls of this
1508 # function, as there is a race condition between SELECT and UPDATE.
MK Ryu06a4b522015-04-24 15:06:10 -07001509 query = Job.objects.filter(
1510 dependency_labels=shard.labels.all(),
1511 # If an HQE associated with a job is removed in some reasons,
1512 # such jobs should be excluded. Refer crbug.com/479766
1513 hostqueueentry__isnull=False
1514 )
Prashanth Balasubramanian8c98ac12014-12-23 11:26:44 -08001515 query = cls._add_filters_for_shard_assignment(query, known_ids)
1516 job_ids = set(query.distinct().values_list('pk', flat=True))
1517
1518 # Combine frontend jobs in the heartbeat.
1519 query = Job.objects.filter(
1520 hostqueueentry__meta_host__isnull=True,
1521 hostqueueentry__host__isnull=False,
1522 hostqueueentry__host__labels=shard.labels.all()
1523 )
1524 query = cls._add_filters_for_shard_assignment(query, known_ids)
1525 job_ids |= set(query.distinct().values_list('pk', flat=True))
Jakob Juelich59cfe542014-09-02 16:37:46 -07001526 if job_ids:
1527 Job.objects.filter(pk__in=job_ids).update(shard=shard)
1528 return list(Job.objects.filter(pk__in=job_ids).all())
1529 return []
1530
1531
jamesren4a41e012010-07-16 22:33:48 +00001532 def save(self, *args, **kwargs):
Paul Pendlebury5a8c6ad2011-02-01 07:20:17 -08001533 # The current implementation of parameterized jobs requires that only
1534 # control files or parameterized jobs are used. Using the image
1535 # parameter on autoupdate_ParameterizedJob doesn't mix pure
1536 # parameterized jobs and control files jobs, it does muck enough with
1537 # normal jobs by adding a parameterized id to them that this check will
1538 # fail. So for now we just skip this check.
1539 # cls.check_parameterized_job(control_file=self.control_file,
1540 # parameterized_job=self.parameterized_job)
jamesren4a41e012010-07-16 22:33:48 +00001541 super(Job, self).save(*args, **kwargs)
1542
1543
showard29f7cd22009-04-29 21:16:24 +00001544 def queue(self, hosts, atomic_group=None, is_template=False):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001545 """Enqueue a job on the given hosts.
1546
1547 @param hosts: The hosts to use.
1548 @param atomic_group: The associated atomic group.
1549 @param is_template: Whether the status should be "Template".
1550 """
showarda9545c02009-12-18 22:44:26 +00001551 if not hosts:
1552 if atomic_group:
1553 # No hosts or labels are required to queue an atomic group
1554 # Job. However, if they are given, we respect them below.
1555 atomic_group.enqueue_job(self, is_template=is_template)
1556 else:
1557 # hostless job
1558 entry = HostQueueEntry.create(job=self, is_template=is_template)
1559 entry.save()
1560 return
1561
jadmanski0afbb632008-06-06 21:10:57 +00001562 for host in hosts:
showard29f7cd22009-04-29 21:16:24 +00001563 host.enqueue_job(self, atomic_group=atomic_group,
1564 is_template=is_template)
1565
1566
1567 def create_recurring_job(self, start_date, loop_period, loop_count, owner):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001568 """Creates a recurring job.
1569
1570 @param start_date: The starting date of the job.
1571 @param loop_period: How often to re-run the job, in seconds.
1572 @param loop_count: The re-run count.
1573 @param owner: The owner of the job.
1574 """
showard29f7cd22009-04-29 21:16:24 +00001575 rec = RecurringRun(job=self, start_date=start_date,
1576 loop_period=loop_period,
1577 loop_count=loop_count,
1578 owner=User.objects.get(login=owner))
1579 rec.save()
1580 return rec.id
mblighe8819cd2008-02-15 16:48:40 +00001581
1582
jadmanski0afbb632008-06-06 21:10:57 +00001583 def user(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001584 """Gets the user of this job, or None if it doesn't exist."""
jadmanski0afbb632008-06-06 21:10:57 +00001585 try:
1586 return User.objects.get(login=self.owner)
1587 except self.DoesNotExist:
1588 return None
mblighe8819cd2008-02-15 16:48:40 +00001589
1590
showard64a95952010-01-13 21:27:16 +00001591 def abort(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001592 """Aborts this job."""
showard98863972008-10-29 21:14:56 +00001593 for queue_entry in self.hostqueueentry_set.all():
showard64a95952010-01-13 21:27:16 +00001594 queue_entry.abort()
showard98863972008-10-29 21:14:56 +00001595
1596
showardd1195652009-12-08 22:21:02 +00001597 def tag(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001598 """Returns a string tag for this job."""
showardd1195652009-12-08 22:21:02 +00001599 return '%s-%s' % (self.id, self.owner)
1600
1601
showardc1a98d12010-01-15 00:22:22 +00001602 def keyval_dict(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001603 """Returns all keyvals for this job as a dictionary."""
showardc1a98d12010-01-15 00:22:22 +00001604 return dict((keyval.key, keyval.value)
1605 for keyval in self.jobkeyval_set.all())
1606
1607
Fang Dengff361592015-02-02 15:27:34 -08001608 @classmethod
1609 def get_attribute_model(cls):
1610 """Return the attribute model.
1611
1612 Override method in parent class. This class is called when
1613 deserializing the one-to-many relationship betwen Job and JobKeyval.
1614 On deserialization, we will try to clear any existing job keyvals
1615 associated with a job to avoid any inconsistency.
1616 Though Job doesn't implement ModelWithAttribute, we still treat
1617 it as an attribute model for this purpose.
1618
1619 @returns: The attribute model of Job.
1620 """
1621 return JobKeyval
1622
1623
jadmanski0afbb632008-06-06 21:10:57 +00001624 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001625 """Metadata for class Job."""
showardeab66ce2009-12-23 00:03:56 +00001626 db_table = 'afe_jobs'
mblighe8819cd2008-02-15 16:48:40 +00001627
showarda5288b42009-07-28 20:06:08 +00001628 def __unicode__(self):
1629 return u'%s (%s-%s)' % (self.name, self.id, self.owner)
mblighe8819cd2008-02-15 16:48:40 +00001630
1631
showardc1a98d12010-01-15 00:22:22 +00001632class JobKeyval(dbmodels.Model, model_logic.ModelExtensions):
1633 """Keyvals associated with jobs"""
Fang Dengff361592015-02-02 15:27:34 -08001634
1635 SERIALIZATION_LINKS_TO_KEEP = set(['job'])
1636 SERIALIZATION_LOCAL_LINKS_TO_UPDATE = set(['value'])
1637
showardc1a98d12010-01-15 00:22:22 +00001638 job = dbmodels.ForeignKey(Job)
1639 key = dbmodels.CharField(max_length=90)
1640 value = dbmodels.CharField(max_length=300)
1641
1642 objects = model_logic.ExtendedManager()
1643
Fang Dengff361592015-02-02 15:27:34 -08001644
1645 @classmethod
1646 def get_record(cls, data):
1647 """Check the database for an identical record.
1648
1649 Use job_id and key to search for a existing record.
1650
1651 @raises: DoesNotExist, if no record found
1652 @raises: MultipleObjectsReturned if multiple records found.
1653 """
1654 # TODO(fdeng): We should use job_id and key together as
1655 # a primary key in the db.
1656 return cls.objects.get(job_id=data['job_id'], key=data['key'])
1657
1658
1659 @classmethod
1660 def deserialize(cls, data):
1661 """Override deserialize in parent class.
1662
1663 Do not deserialize id as id is not kept consistent on master and shards.
1664
1665 @param data: A dictionary of data to deserialize.
1666
1667 @returns: A JobKeyval object.
1668 """
1669 if data:
1670 data.pop('id')
1671 return super(JobKeyval, cls).deserialize(data)
1672
1673
showardc1a98d12010-01-15 00:22:22 +00001674 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001675 """Metadata for class JobKeyval."""
showardc1a98d12010-01-15 00:22:22 +00001676 db_table = 'afe_job_keyvals'
1677
1678
showard7c785282008-05-29 19:45:12 +00001679class IneligibleHostQueue(dbmodels.Model, model_logic.ModelExtensions):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001680 """Represents an ineligible host queue."""
jadmanski0afbb632008-06-06 21:10:57 +00001681 job = dbmodels.ForeignKey(Job)
1682 host = dbmodels.ForeignKey(Host)
mblighe8819cd2008-02-15 16:48:40 +00001683
jadmanski0afbb632008-06-06 21:10:57 +00001684 objects = model_logic.ExtendedManager()
showardeb3be4d2008-04-21 20:59:26 +00001685
jadmanski0afbb632008-06-06 21:10:57 +00001686 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001687 """Metadata for class IneligibleHostQueue."""
showardeab66ce2009-12-23 00:03:56 +00001688 db_table = 'afe_ineligible_host_queues'
mblighe8819cd2008-02-15 16:48:40 +00001689
mblighe8819cd2008-02-15 16:48:40 +00001690
showard7c785282008-05-29 19:45:12 +00001691class HostQueueEntry(dbmodels.Model, model_logic.ModelExtensions):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001692 """Represents a host queue entry."""
Jakob Juelich3bb7c802014-09-02 16:31:11 -07001693
1694 SERIALIZATION_LINKS_TO_FOLLOW = set(['meta_host'])
Prashanth Balasubramanian8c98ac12014-12-23 11:26:44 -08001695 SERIALIZATION_LINKS_TO_KEEP = set(['host'])
Jakob Juelichf865d332014-09-29 10:47:49 -07001696 SERIALIZATION_LOCAL_LINKS_TO_UPDATE = set(['aborted'])
Jakob Juelich3bb7c802014-09-02 16:31:11 -07001697
Jakob Juelichf88fa932014-09-03 17:58:04 -07001698
1699 def custom_deserialize_relation(self, link, data):
1700 assert link == 'meta_host'
1701 self.meta_host = Label.deserialize(data)
1702
1703
Jakob Juelicha94efe62014-09-18 16:02:49 -07001704 def sanity_check_update_from_shard(self, shard, updated_serialized,
1705 job_ids_sent):
1706 if self.job_id not in job_ids_sent:
1707 raise error.UnallowedRecordsSentToMaster(
1708 'Sent HostQueueEntry without corresponding '
1709 'job entry: %s' % updated_serialized)
1710
1711
showardeaa408e2009-09-11 18:45:31 +00001712 Status = host_queue_entry_states.Status
1713 ACTIVE_STATUSES = host_queue_entry_states.ACTIVE_STATUSES
showardeab66ce2009-12-23 00:03:56 +00001714 COMPLETE_STATUSES = host_queue_entry_states.COMPLETE_STATUSES
showarda3ab0d52008-11-03 19:03:47 +00001715
jadmanski0afbb632008-06-06 21:10:57 +00001716 job = dbmodels.ForeignKey(Job)
1717 host = dbmodels.ForeignKey(Host, blank=True, null=True)
showarda5288b42009-07-28 20:06:08 +00001718 status = dbmodels.CharField(max_length=255)
jadmanski0afbb632008-06-06 21:10:57 +00001719 meta_host = dbmodels.ForeignKey(Label, blank=True, null=True,
1720 db_column='meta_host')
1721 active = dbmodels.BooleanField(default=False)
1722 complete = dbmodels.BooleanField(default=False)
showardb8471e32008-07-03 19:51:08 +00001723 deleted = dbmodels.BooleanField(default=False)
showarda5288b42009-07-28 20:06:08 +00001724 execution_subdir = dbmodels.CharField(max_length=255, blank=True,
1725 default='')
showard89f84db2009-03-12 20:39:13 +00001726 # If atomic_group is set, this is a virtual HostQueueEntry that will
1727 # be expanded into many actual hosts within the group at schedule time.
1728 atomic_group = dbmodels.ForeignKey(AtomicGroup, blank=True, null=True)
showardd3dc1992009-04-22 21:01:40 +00001729 aborted = dbmodels.BooleanField(default=False)
showardd3771cc2009-10-07 20:48:22 +00001730 started_on = dbmodels.DateTimeField(null=True, blank=True)
Fang Deng51599032014-06-23 17:24:27 -07001731 finished_on = dbmodels.DateTimeField(null=True, blank=True)
mblighe8819cd2008-02-15 16:48:40 +00001732
jadmanski0afbb632008-06-06 21:10:57 +00001733 objects = model_logic.ExtendedManager()
showardeb3be4d2008-04-21 20:59:26 +00001734
mblighe8819cd2008-02-15 16:48:40 +00001735
showard2bab8f42008-11-12 18:15:22 +00001736 def __init__(self, *args, **kwargs):
1737 super(HostQueueEntry, self).__init__(*args, **kwargs)
1738 self._record_attributes(['status'])
1739
1740
showard29f7cd22009-04-29 21:16:24 +00001741 @classmethod
1742 def create(cls, job, host=None, meta_host=None, atomic_group=None,
1743 is_template=False):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001744 """Creates a new host queue entry.
1745
1746 @param cls: Implicit class object.
1747 @param job: The associated job.
1748 @param host: The associated host.
1749 @param meta_host: The associated meta host.
1750 @param atomic_group: The associated atomic group.
1751 @param is_template: Whether the status should be "Template".
1752 """
showard29f7cd22009-04-29 21:16:24 +00001753 if is_template:
1754 status = cls.Status.TEMPLATE
1755 else:
1756 status = cls.Status.QUEUED
1757
1758 return cls(job=job, host=host, meta_host=meta_host,
1759 atomic_group=atomic_group, status=status)
1760
1761
showarda5288b42009-07-28 20:06:08 +00001762 def save(self, *args, **kwargs):
showard2bab8f42008-11-12 18:15:22 +00001763 self._set_active_and_complete()
showarda5288b42009-07-28 20:06:08 +00001764 super(HostQueueEntry, self).save(*args, **kwargs)
showard2bab8f42008-11-12 18:15:22 +00001765 self._check_for_updated_attributes()
1766
1767
showardc0ac3a72009-07-08 21:14:45 +00001768 def execution_path(self):
1769 """
1770 Path to this entry's results (relative to the base results directory).
1771 """
showardd1195652009-12-08 22:21:02 +00001772 return os.path.join(self.job.tag(), self.execution_subdir)
showardc0ac3a72009-07-08 21:14:45 +00001773
1774
showard3f15eed2008-11-14 22:40:48 +00001775 def host_or_metahost_name(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001776 """Returns the first non-None name found in priority order.
1777
1778 The priority order checked is: (1) host name; (2) meta host name; and
1779 (3) atomic group name.
1780 """
showard3f15eed2008-11-14 22:40:48 +00001781 if self.host:
1782 return self.host.hostname
showard7890e792009-07-28 20:10:20 +00001783 elif self.meta_host:
showard3f15eed2008-11-14 22:40:48 +00001784 return self.meta_host.name
showard7890e792009-07-28 20:10:20 +00001785 else:
1786 assert self.atomic_group, "no host, meta_host or atomic group!"
1787 return self.atomic_group.name
showard3f15eed2008-11-14 22:40:48 +00001788
1789
showard2bab8f42008-11-12 18:15:22 +00001790 def _set_active_and_complete(self):
showardd3dc1992009-04-22 21:01:40 +00001791 if self.status in self.ACTIVE_STATUSES:
showard2bab8f42008-11-12 18:15:22 +00001792 self.active, self.complete = True, False
1793 elif self.status in self.COMPLETE_STATUSES:
1794 self.active, self.complete = False, True
1795 else:
1796 self.active, self.complete = False, False
1797
1798
1799 def on_attribute_changed(self, attribute, old_value):
1800 assert attribute == 'status'
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001801 logging.info('%s/%d (%d) -> %s', self.host, self.job.id, self.id,
1802 self.status)
showard2bab8f42008-11-12 18:15:22 +00001803
1804
jadmanski0afbb632008-06-06 21:10:57 +00001805 def is_meta_host_entry(self):
1806 'True if this is a entry has a meta_host instead of a host.'
1807 return self.host is None and self.meta_host is not None
mblighe8819cd2008-02-15 16:48:40 +00001808
showarda3ab0d52008-11-03 19:03:47 +00001809
Simran Basic1b26762013-06-26 14:23:21 -07001810 # This code is shared between rpc_interface and models.HostQueueEntry.
1811 # Sadly due to circular imports between the 2 (crbug.com/230100) making it
1812 # a class method was the best way to refactor it. Attempting to put it in
1813 # rpc_utils or a new utils module failed as that would require us to import
1814 # models.py but to call it from here we would have to import the utils.py
1815 # thus creating a cycle.
1816 @classmethod
1817 def abort_host_queue_entries(cls, host_queue_entries):
1818 """Aborts a collection of host_queue_entries.
1819
1820 Abort these host queue entry and all host queue entries of jobs created
1821 by them.
1822
1823 @param host_queue_entries: List of host queue entries we want to abort.
1824 """
1825 # This isn't completely immune to race conditions since it's not atomic,
1826 # but it should be safe given the scheduler's behavior.
1827
1828 # TODO(milleral): crbug.com/230100
1829 # The |abort_host_queue_entries| rpc does nearly exactly this,
1830 # however, trying to re-use the code generates some horrible
1831 # circular import error. I'd be nice to refactor things around
1832 # sometime so the code could be reused.
1833
1834 # Fixpoint algorithm to find the whole tree of HQEs to abort to
1835 # minimize the total number of database queries:
1836 children = set()
1837 new_children = set(host_queue_entries)
1838 while new_children:
1839 children.update(new_children)
1840 new_child_ids = [hqe.job_id for hqe in new_children]
1841 new_children = HostQueueEntry.objects.filter(
1842 job__parent_job__in=new_child_ids,
1843 complete=False, aborted=False).all()
1844 # To handle circular parental relationships
1845 new_children = set(new_children) - children
1846
1847 # Associate a user with the host queue entries that we're about
1848 # to abort so that we can look up who to blame for the aborts.
1849 now = datetime.now()
1850 user = User.current_user()
1851 aborted_hqes = [AbortedHostQueueEntry(queue_entry=hqe,
1852 aborted_by=user, aborted_on=now) for hqe in children]
1853 AbortedHostQueueEntry.objects.bulk_create(aborted_hqes)
1854 # Bulk update all of the HQEs to set the abort bit.
1855 child_ids = [hqe.id for hqe in children]
1856 HostQueueEntry.objects.filter(id__in=child_ids).update(aborted=True)
1857
1858
Scott Zawalski23041432013-04-17 07:39:09 -07001859 def abort(self):
Alex Millerdea67042013-04-22 17:23:34 -07001860 """ Aborts this host queue entry.
Simran Basic1b26762013-06-26 14:23:21 -07001861
Alex Millerdea67042013-04-22 17:23:34 -07001862 Abort this host queue entry and all host queue entries of jobs created by
1863 this one.
1864
1865 """
showardd3dc1992009-04-22 21:01:40 +00001866 if not self.complete and not self.aborted:
Simran Basi97582a22013-06-27 12:03:21 -07001867 HostQueueEntry.abort_host_queue_entries([self])
mblighe8819cd2008-02-15 16:48:40 +00001868
showardd3dc1992009-04-22 21:01:40 +00001869
1870 @classmethod
1871 def compute_full_status(cls, status, aborted, complete):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001872 """Returns a modified status msg if the host queue entry was aborted.
1873
1874 @param cls: Implicit class object.
1875 @param status: The original status message.
1876 @param aborted: Whether the host queue entry was aborted.
1877 @param complete: Whether the host queue entry was completed.
1878 """
showardd3dc1992009-04-22 21:01:40 +00001879 if aborted and not complete:
1880 return 'Aborted (%s)' % status
1881 return status
1882
1883
1884 def full_status(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001885 """Returns the full status of this host queue entry, as a string."""
showardd3dc1992009-04-22 21:01:40 +00001886 return self.compute_full_status(self.status, self.aborted,
1887 self.complete)
1888
1889
1890 def _postprocess_object_dict(self, object_dict):
1891 object_dict['full_status'] = self.full_status()
1892
1893
jadmanski0afbb632008-06-06 21:10:57 +00001894 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001895 """Metadata for class HostQueueEntry."""
showardeab66ce2009-12-23 00:03:56 +00001896 db_table = 'afe_host_queue_entries'
mblighe8819cd2008-02-15 16:48:40 +00001897
showard12f3e322009-05-13 21:27:42 +00001898
showard4c119042008-09-29 19:16:18 +00001899
showarda5288b42009-07-28 20:06:08 +00001900 def __unicode__(self):
showard12f3e322009-05-13 21:27:42 +00001901 hostname = None
1902 if self.host:
1903 hostname = self.host.hostname
showarda5288b42009-07-28 20:06:08 +00001904 return u"%s/%d (%d)" % (hostname, self.job.id, self.id)
showard12f3e322009-05-13 21:27:42 +00001905
1906
showard4c119042008-09-29 19:16:18 +00001907class AbortedHostQueueEntry(dbmodels.Model, model_logic.ModelExtensions):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001908 """Represents an aborted host queue entry."""
showard4c119042008-09-29 19:16:18 +00001909 queue_entry = dbmodels.OneToOneField(HostQueueEntry, primary_key=True)
1910 aborted_by = dbmodels.ForeignKey(User)
showard68c7aa02008-10-09 16:49:11 +00001911 aborted_on = dbmodels.DateTimeField()
showard4c119042008-09-29 19:16:18 +00001912
1913 objects = model_logic.ExtendedManager()
1914
showard68c7aa02008-10-09 16:49:11 +00001915
showarda5288b42009-07-28 20:06:08 +00001916 def save(self, *args, **kwargs):
showard68c7aa02008-10-09 16:49:11 +00001917 self.aborted_on = datetime.now()
showarda5288b42009-07-28 20:06:08 +00001918 super(AbortedHostQueueEntry, self).save(*args, **kwargs)
showard68c7aa02008-10-09 16:49:11 +00001919
showard4c119042008-09-29 19:16:18 +00001920 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001921 """Metadata for class AbortedHostQueueEntry."""
showardeab66ce2009-12-23 00:03:56 +00001922 db_table = 'afe_aborted_host_queue_entries'
showard29f7cd22009-04-29 21:16:24 +00001923
1924
1925class RecurringRun(dbmodels.Model, model_logic.ModelExtensions):
1926 """\
1927 job: job to use as a template
1928 owner: owner of the instantiated template
1929 start_date: Run the job at scheduled date
1930 loop_period: Re-run (loop) the job periodically
1931 (in every loop_period seconds)
1932 loop_count: Re-run (loop) count
1933 """
1934
1935 job = dbmodels.ForeignKey(Job)
1936 owner = dbmodels.ForeignKey(User)
1937 start_date = dbmodels.DateTimeField()
1938 loop_period = dbmodels.IntegerField(blank=True)
1939 loop_count = dbmodels.IntegerField(blank=True)
1940
1941 objects = model_logic.ExtendedManager()
1942
1943 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08001944 """Metadata for class RecurringRun."""
showardeab66ce2009-12-23 00:03:56 +00001945 db_table = 'afe_recurring_run'
showard29f7cd22009-04-29 21:16:24 +00001946
showarda5288b42009-07-28 20:06:08 +00001947 def __unicode__(self):
1948 return u'RecurringRun(job %s, start %s, period %s, count %s)' % (
showard29f7cd22009-04-29 21:16:24 +00001949 self.job.id, self.start_date, self.loop_period, self.loop_count)
showard6d7b2ff2009-06-10 00:16:47 +00001950
1951
1952class SpecialTask(dbmodels.Model, model_logic.ModelExtensions):
1953 """\
1954 Tasks to run on hosts at the next time they are in the Ready state. Use this
1955 for high-priority tasks, such as forced repair or forced reinstall.
1956
1957 host: host to run this task on
showard2fe3f1d2009-07-06 20:19:11 +00001958 task: special task to run
showard6d7b2ff2009-06-10 00:16:47 +00001959 time_requested: date and time the request for this task was made
1960 is_active: task is currently running
1961 is_complete: task has finished running
beeps8bb1f7d2013-08-05 01:30:09 -07001962 is_aborted: task was aborted
showard2fe3f1d2009-07-06 20:19:11 +00001963 time_started: date and time the task started
Dan Shid0725542014-06-23 15:34:27 -07001964 time_finished: date and time the task finished
showard2fe3f1d2009-07-06 20:19:11 +00001965 queue_entry: Host queue entry waiting on this task (or None, if task was not
1966 started in preparation of a job)
showard6d7b2ff2009-06-10 00:16:47 +00001967 """
Alex Millerdfff2fd2013-05-28 13:05:06 -07001968 Task = enum.Enum('Verify', 'Cleanup', 'Repair', 'Reset', 'Provision',
Dan Shi07e09af2013-04-12 09:31:29 -07001969 string_values=True)
showard6d7b2ff2009-06-10 00:16:47 +00001970
1971 host = dbmodels.ForeignKey(Host, blank=False, null=False)
showarda5288b42009-07-28 20:06:08 +00001972 task = dbmodels.CharField(max_length=64, choices=Task.choices(),
showard6d7b2ff2009-06-10 00:16:47 +00001973 blank=False, null=False)
jamesren76fcf192010-04-21 20:39:50 +00001974 requested_by = dbmodels.ForeignKey(User)
showard6d7b2ff2009-06-10 00:16:47 +00001975 time_requested = dbmodels.DateTimeField(auto_now_add=True, blank=False,
1976 null=False)
1977 is_active = dbmodels.BooleanField(default=False, blank=False, null=False)
1978 is_complete = dbmodels.BooleanField(default=False, blank=False, null=False)
beeps8bb1f7d2013-08-05 01:30:09 -07001979 is_aborted = dbmodels.BooleanField(default=False, blank=False, null=False)
showardc0ac3a72009-07-08 21:14:45 +00001980 time_started = dbmodels.DateTimeField(null=True, blank=True)
showard2fe3f1d2009-07-06 20:19:11 +00001981 queue_entry = dbmodels.ForeignKey(HostQueueEntry, blank=True, null=True)
showarde60e44e2009-11-13 20:45:38 +00001982 success = dbmodels.BooleanField(default=False, blank=False, null=False)
Dan Shid0725542014-06-23 15:34:27 -07001983 time_finished = dbmodels.DateTimeField(null=True, blank=True)
showard6d7b2ff2009-06-10 00:16:47 +00001984
1985 objects = model_logic.ExtendedManager()
1986
1987
showard9bb960b2009-11-19 01:02:11 +00001988 def save(self, **kwargs):
1989 if self.queue_entry:
1990 self.requested_by = User.objects.get(
1991 login=self.queue_entry.job.owner)
1992 super(SpecialTask, self).save(**kwargs)
1993
1994
showarded2afea2009-07-07 20:54:07 +00001995 def execution_path(self):
Prashanth Balasubramaniande87dea2014-11-09 17:47:10 -08001996 """Get the execution path of the SpecialTask.
1997
1998 This method returns different paths depending on where a
1999 the task ran:
2000 * Master: hosts/hostname/task_id-task_type
2001 * Shard: Master_path/time_created
2002 This is to work around the fact that a shard can fail independent
2003 of the master, and be replaced by another shard that has the same
2004 hosts. Without the time_created stamp the logs of the tasks running
2005 on the second shard will clobber the logs from the first in google
2006 storage, because task ids are not globally unique.
2007
2008 @return: An execution path for the task.
2009 """
2010 results_path = 'hosts/%s/%s-%s' % (self.host.hostname, self.id,
2011 self.task.lower())
2012
2013 # If we do this on the master it will break backward compatibility,
2014 # as there are tasks that currently don't have timestamps. If a host
2015 # or job has been sent to a shard, the rpc for that host/job will
2016 # be redirected to the shard, so this global_config check will happen
2017 # on the shard the logs are on.
2018 is_shard = global_config.global_config.get_config_value(
2019 'SHARD', 'shard_hostname', type=str, default='')
2020 if not is_shard:
2021 return results_path
2022
2023 # Generate a uid to disambiguate special task result directories
2024 # in case this shard fails. The simplest uid is the job_id, however
2025 # in rare cases tasks do not have jobs associated with them (eg:
2026 # frontend verify), so just use the creation timestamp. The clocks
2027 # between a shard and master should always be in sync. Any discrepancies
2028 # will be brought to our attention in the form of job timeouts.
2029 uid = self.time_requested.strftime('%Y%d%m%H%M%S')
2030
2031 # TODO: This is a hack, however it is the easiest way to achieve
2032 # correctness. There is currently some debate over the future of
2033 # tasks in our infrastructure and refactoring everything right
2034 # now isn't worth the time.
2035 return '%s/%s' % (results_path, uid)
showarded2afea2009-07-07 20:54:07 +00002036
2037
showardc0ac3a72009-07-08 21:14:45 +00002038 # property to emulate HostQueueEntry.status
2039 @property
2040 def status(self):
2041 """
2042 Return a host queue entry status appropriate for this task. Although
2043 SpecialTasks are not HostQueueEntries, it is helpful to the user to
2044 present similar statuses.
2045 """
2046 if self.is_complete:
showarde60e44e2009-11-13 20:45:38 +00002047 if self.success:
2048 return HostQueueEntry.Status.COMPLETED
2049 return HostQueueEntry.Status.FAILED
showardc0ac3a72009-07-08 21:14:45 +00002050 if self.is_active:
2051 return HostQueueEntry.Status.RUNNING
2052 return HostQueueEntry.Status.QUEUED
2053
2054
2055 # property to emulate HostQueueEntry.started_on
2056 @property
2057 def started_on(self):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08002058 """Returns the time at which this special task started."""
showardc0ac3a72009-07-08 21:14:45 +00002059 return self.time_started
2060
2061
showard6d7b2ff2009-06-10 00:16:47 +00002062 @classmethod
showardc5103442010-01-15 00:20:26 +00002063 def schedule_special_task(cls, host, task):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08002064 """Schedules a special task on a host if not already scheduled.
2065
2066 @param cls: Implicit class object.
2067 @param host: The host to use.
2068 @param task: The task to schedule.
showard6d7b2ff2009-06-10 00:16:47 +00002069 """
showardc5103442010-01-15 00:20:26 +00002070 existing_tasks = SpecialTask.objects.filter(host__id=host.id, task=task,
2071 is_active=False,
2072 is_complete=False)
2073 if existing_tasks:
2074 return existing_tasks[0]
2075
2076 special_task = SpecialTask(host=host, task=task,
2077 requested_by=User.current_user())
2078 special_task.save()
2079 return special_task
showard2fe3f1d2009-07-06 20:19:11 +00002080
2081
beeps8bb1f7d2013-08-05 01:30:09 -07002082 def abort(self):
2083 """ Abort this special task."""
2084 self.is_aborted = True
2085 self.save()
2086
2087
showarded2afea2009-07-07 20:54:07 +00002088 def activate(self):
showard474d1362009-08-20 23:32:01 +00002089 """
2090 Sets a task as active and sets the time started to the current time.
showard2fe3f1d2009-07-06 20:19:11 +00002091 """
showard97446882009-07-20 22:37:28 +00002092 logging.info('Starting: %s', self)
showard2fe3f1d2009-07-06 20:19:11 +00002093 self.is_active = True
2094 self.time_started = datetime.now()
2095 self.save()
2096
2097
showarde60e44e2009-11-13 20:45:38 +00002098 def finish(self, success):
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08002099 """Sets a task as completed.
2100
2101 @param success: Whether or not the task was successful.
showard2fe3f1d2009-07-06 20:19:11 +00002102 """
showard97446882009-07-20 22:37:28 +00002103 logging.info('Finished: %s', self)
showarded2afea2009-07-07 20:54:07 +00002104 self.is_active = False
showard2fe3f1d2009-07-06 20:19:11 +00002105 self.is_complete = True
showarde60e44e2009-11-13 20:45:38 +00002106 self.success = success
Dan Shid85d6112014-07-14 10:32:55 -07002107 if self.time_started:
2108 self.time_finished = datetime.now()
showard2fe3f1d2009-07-06 20:19:11 +00002109 self.save()
showard6d7b2ff2009-06-10 00:16:47 +00002110
2111
2112 class Meta:
Dennis Jeffrey7db38ba2013-02-13 10:03:17 -08002113 """Metadata for class SpecialTask."""
showardeab66ce2009-12-23 00:03:56 +00002114 db_table = 'afe_special_tasks'
showard6d7b2ff2009-06-10 00:16:47 +00002115
showard474d1362009-08-20 23:32:01 +00002116
showarda5288b42009-07-28 20:06:08 +00002117 def __unicode__(self):
2118 result = u'Special Task %s (host %s, task %s, time %s)' % (
showarded2afea2009-07-07 20:54:07 +00002119 self.id, self.host, self.task, self.time_requested)
showard6d7b2ff2009-06-10 00:16:47 +00002120 if self.is_complete:
showarda5288b42009-07-28 20:06:08 +00002121 result += u' (completed)'
showard6d7b2ff2009-06-10 00:16:47 +00002122 elif self.is_active:
showarda5288b42009-07-28 20:06:08 +00002123 result += u' (active)'
showard6d7b2ff2009-06-10 00:16:47 +00002124
2125 return result
Dan Shi6964fa52014-12-18 11:04:27 -08002126
2127
2128class StableVersion(dbmodels.Model, model_logic.ModelExtensions):
2129
2130 board = dbmodels.CharField(max_length=255, unique=True)
2131 version = dbmodels.CharField(max_length=255)
2132
2133 class Meta:
2134 """Metadata for class StableVersion."""
Fang Deng86248502014-12-18 16:38:00 -08002135 db_table = 'afe_stable_versions'