models.py revision d5afc2f14dad583057f1eaffbc0366eb389f70d6
1from datetime import datetime 2from django.db import models as dbmodels, connection 3from frontend.afe import model_logic 4from frontend import settings, thread_local 5from autotest_lib.client.common_lib import enum, host_protections 6 7 8class AclAccessViolation(Exception): 9 """\ 10 Raised when an operation is attempted with proper permissions as 11 dictated by ACLs. 12 """ 13 14 15class Label(model_logic.ModelWithInvalid, dbmodels.Model): 16 """\ 17 Required: 18 name: label name 19 20 Optional: 21 kernel_config: url/path to kernel config to use for jobs run on this 22 label 23 platform: if True, this is a platform label (defaults to False) 24 """ 25 name = dbmodels.CharField(maxlength=255, unique=True) 26 kernel_config = dbmodels.CharField(maxlength=255, blank=True) 27 platform = dbmodels.BooleanField(default=False) 28 invalid = dbmodels.BooleanField(default=False, 29 editable=settings.FULL_ADMIN) 30 31 name_field = 'name' 32 objects = model_logic.ExtendedManager() 33 valid_objects = model_logic.ValidObjectsManager() 34 35 def clean_object(self): 36 self.host_set.clear() 37 38 39 def enqueue_job(self, job): 40 'Enqueue a job on any host of this label.' 41 queue_entry = HostQueueEntry(meta_host=self, job=job, 42 status=Job.Status.QUEUED, 43 priority=job.priority) 44 queue_entry.save() 45 46 47 class Meta: 48 db_table = 'labels' 49 50 class Admin: 51 list_display = ('name', 'kernel_config') 52 # see Host.Admin 53 manager = model_logic.ValidObjectsManager() 54 55 def __str__(self): 56 return self.name 57 58 59class User(dbmodels.Model, model_logic.ModelExtensions): 60 """\ 61 Required: 62 login :user login name 63 64 Optional: 65 access_level: 0=User (default), 1=Admin, 100=Root 66 """ 67 ACCESS_ROOT = 100 68 ACCESS_ADMIN = 1 69 ACCESS_USER = 0 70 71 login = dbmodels.CharField(maxlength=255, unique=True) 72 access_level = dbmodels.IntegerField(default=ACCESS_USER, blank=True) 73 74 name_field = 'login' 75 objects = model_logic.ExtendedManager() 76 77 78 def save(self): 79 # is this a new object being saved for the first time? 80 first_time = (self.id is None) 81 user = thread_local.get_user() 82 if user and not user.is_superuser(): 83 raise AclAccessViolation("You cannot modify users!") 84 super(User, self).save() 85 if first_time: 86 everyone = AclGroup.objects.get(name='Everyone') 87 everyone.users.add(self) 88 89 90 def is_superuser(self): 91 return self.access_level >= self.ACCESS_ROOT 92 93 94 class Meta: 95 db_table = 'users' 96 97 class Admin: 98 list_display = ('login', 'access_level') 99 search_fields = ('login',) 100 101 def __str__(self): 102 return self.login 103 104 105class Host(model_logic.ModelWithInvalid, dbmodels.Model): 106 """\ 107 Required: 108 hostname 109 110 optional: 111 locked: host is locked and will not be queued 112 113 Internal: 114 synch_id: currently unused 115 status: string describing status of host 116 """ 117 Status = enum.Enum('Verifying', 'Running', 'Ready', 'Repairing', 118 'Repair Failed', 'Dead', 'Rebooting', 119 string_values=True) 120 121 hostname = dbmodels.CharField(maxlength=255, unique=True) 122 labels = dbmodels.ManyToManyField(Label, blank=True, 123 filter_interface=dbmodels.HORIZONTAL) 124 locked = dbmodels.BooleanField(default=False) 125 synch_id = dbmodels.IntegerField(blank=True, null=True, 126 editable=settings.FULL_ADMIN) 127 status = dbmodels.CharField(maxlength=255, default=Status.READY, 128 choices=Status.choices(), 129 editable=settings.FULL_ADMIN) 130 invalid = dbmodels.BooleanField(default=False, 131 editable=settings.FULL_ADMIN) 132 protection = dbmodels.SmallIntegerField(null=False, blank=True, 133 choices=host_protections.choices, 134 default=host_protections.default) 135 locked_by = dbmodels.ForeignKey(User, null=True, blank=True, editable=False) 136 lock_time = dbmodels.DateTimeField(null=True, blank=True, editable=False) 137 138 name_field = 'hostname' 139 objects = model_logic.ExtendedManager() 140 valid_objects = model_logic.ValidObjectsManager() 141 142 @staticmethod 143 def create_one_time_host(hostname): 144 query = Host.objects.filter(hostname=hostname) 145 if query.count() == 0: 146 host = Host(hostname=hostname, invalid=True) 147 host.do_validate() 148 else: 149 host = query[0] 150 if not host.invalid: 151 raise model_logic.ValidationError({ 152 'hostname' : '%s already exists!' % hostname 153 }) 154 host.clean_object() 155 AclGroup.objects.get(name='Everyone').hosts.add(host) 156 host.status = Host.Status.READY 157 host.protection = host_protections.Protection.DO_NOT_REPAIR 158 host.save() 159 return host 160 161 def clean_object(self): 162 self.aclgroup_set.clear() 163 self.labels.clear() 164 165 166 def save(self): 167 # extra spaces in the hostname can be a sneaky source of errors 168 self.hostname = self.hostname.strip() 169 # is this a new object being saved for the first time? 170 first_time = (self.id is None) 171 if not first_time: 172 AclGroup.check_for_acl_violation_hosts([self]) 173 if self.locked and not self.locked_by: 174 self.locked_by = thread_local.get_user() 175 self.lock_time = datetime.now() 176 elif not self.locked and self.locked_by: 177 self.locked_by = None 178 self.lock_time = None 179 super(Host, self).save() 180 if first_time: 181 everyone = AclGroup.objects.get(name='Everyone') 182 everyone.hosts.add(self) 183 184 def delete(self): 185 AclGroup.check_for_acl_violation_hosts([self]) 186 for queue_entry in self.hostqueueentry_set.all(): 187 queue_entry.deleted = True 188 queue_entry.abort() 189 super(Host, self).delete() 190 191 192 def enqueue_job(self, job): 193 ' Enqueue a job on this host.' 194 queue_entry = HostQueueEntry(host=self, job=job, 195 status=Job.Status.QUEUED, 196 priority=job.priority) 197 # allow recovery of dead hosts from the frontend 198 if not self.active_queue_entry() and self.is_dead(): 199 self.status = Host.Status.READY 200 self.save() 201 queue_entry.save() 202 203 block = IneligibleHostQueue(job=job, host=self) 204 block.save() 205 206 207 def platform(self): 208 # TODO(showard): slighly hacky? 209 platforms = self.labels.filter(platform=True) 210 if len(platforms) == 0: 211 return None 212 return platforms[0] 213 platform.short_description = 'Platform' 214 215 216 def is_dead(self): 217 return self.status == Host.Status.REPAIR_FAILED 218 219 220 def active_queue_entry(self): 221 active = list(self.hostqueueentry_set.filter(active=True)) 222 if not active: 223 return None 224 assert len(active) == 1, ('More than one active entry for ' 225 'host ' + self.hostname) 226 return active[0] 227 228 229 class Meta: 230 db_table = 'hosts' 231 232 class Admin: 233 # TODO(showard) - showing platform requires a SQL query for 234 # each row (since labels are many-to-many) - should we remove 235 # it? 236 list_display = ('hostname', 'platform', 'locked', 'status') 237 list_filter = ('labels', 'locked', 'protection') 238 search_fields = ('hostname', 'status') 239 # undocumented Django feature - if you set manager here, the 240 # admin code will use it, otherwise it'll use a default Manager 241 manager = model_logic.ValidObjectsManager() 242 243 def __str__(self): 244 return self.hostname 245 246 247class Test(dbmodels.Model, model_logic.ModelExtensions): 248 """\ 249 Required: 250 author: author name 251 description: description of the test 252 name: test name 253 time: short, medium, long 254 test_class: This describes the class for your the test belongs in. 255 test_category: This describes the category for your tests 256 test_type: Client or Server 257 path: path to pass to run_test() 258 synch_type: whether the test should run synchronously or asynchronously 259 sync_count: is a number >=1 (1 being the default). If it's 1, then it's an 260 async job. If it's >1 it's sync job for that number of machines 261 i.e. if sync_count = 2 it is a sync job that requires two 262 machines. 263 Optional: 264 dependencies: What the test requires to run. Comma deliminated list 265 experimental: If this is set to True production servers will ignore the test 266 run_verify: Whether or not the scheduler should run the verify stage 267 """ 268 TestTime = enum.Enum('SHORT', 'MEDIUM', 'LONG', start_value=1) 269 SynchType = enum.Enum('Asynchronous', 'Synchronous', start_value=1) 270 # TODO(showard) - this should be merged with Job.ControlType (but right 271 # now they use opposite values) 272 Types = enum.Enum('Client', 'Server', start_value=1) 273 274 name = dbmodels.CharField(maxlength=255, unique=True) 275 author = dbmodels.CharField(maxlength=255) 276 test_class = dbmodels.CharField(maxlength=255) 277 test_category = dbmodels.CharField(maxlength=255) 278 dependencies = dbmodels.CharField(maxlength=255, blank=True) 279 description = dbmodels.TextField(blank=True) 280 experimental = dbmodels.BooleanField(default=True) 281 run_verify = dbmodels.BooleanField(default=True) 282 test_time = dbmodels.SmallIntegerField(choices=TestTime.choices(), 283 default=TestTime.MEDIUM) 284 test_type = dbmodels.SmallIntegerField(choices=Types.choices()) 285 sync_count = dbmodels.IntegerField(default=1) 286 synch_type = dbmodels.SmallIntegerField(choices=SynchType.choices(), 287 default=SynchType.ASYNCHRONOUS) 288 path = dbmodels.CharField(maxlength=255, unique=True) 289 290 name_field = 'name' 291 objects = model_logic.ExtendedManager() 292 293 294 class Meta: 295 db_table = 'autotests' 296 297 class Admin: 298 fields = ( 299 (None, {'fields' : 300 ('name', 'author', 'test_category', 'test_class', 301 'test_time', 'synch_type', 'test_type', 'sync_count', 302 'path', 'dependencies', 'experimental', 'run_verify', 303 'description')}), 304 ) 305 list_display = ('name', 'test_type', 'description', 'synch_type') 306 search_fields = ('name',) 307 308 def __str__(self): 309 return self.name 310 311 312class Profiler(dbmodels.Model, model_logic.ModelExtensions): 313 """\ 314 Required: 315 name: profiler name 316 test_type: Client or Server 317 318 Optional: 319 description: arbirary text description 320 """ 321 name = dbmodels.CharField(maxlength=255, unique=True) 322 description = dbmodels.TextField(blank=True) 323 324 name_field = 'name' 325 objects = model_logic.ExtendedManager() 326 327 328 class Meta: 329 db_table = 'profilers' 330 331 class Admin: 332 list_display = ('name', 'description') 333 search_fields = ('name',) 334 335 def __str__(self): 336 return self.name 337 338 339class AclGroup(dbmodels.Model, model_logic.ModelExtensions): 340 """\ 341 Required: 342 name: name of ACL group 343 344 Optional: 345 description: arbitrary description of group 346 """ 347 name = dbmodels.CharField(maxlength=255, unique=True) 348 description = dbmodels.CharField(maxlength=255, blank=True) 349 users = dbmodels.ManyToManyField(User, blank=True, 350 filter_interface=dbmodels.HORIZONTAL) 351 hosts = dbmodels.ManyToManyField(Host, 352 filter_interface=dbmodels.HORIZONTAL) 353 354 name_field = 'name' 355 objects = model_logic.ExtendedManager() 356 357 @staticmethod 358 def check_for_acl_violation_hosts(hosts): 359 user = thread_local.get_user() 360 if user.is_superuser(): 361 return None 362 accessible_host_ids = set( 363 host.id for host in Host.objects.filter(acl_group__users=user)) 364 for host in hosts: 365 # Check if the user has access to this host, 366 # but only if it is not a metahost 367 if (isinstance(host, Host) 368 and int(host.id) not in accessible_host_ids): 369 raise AclAccessViolation("You do not have access to %s" 370 % str(host)) 371 372 def check_for_acl_violation_acl_group(self): 373 user = thread_local.get_user() 374 if user.is_superuser(): 375 return None 376 if not user in self.users.all(): 377 raise AclAccessViolation("You do not have access to %s" 378 % self.name) 379 380 @staticmethod 381 def on_host_membership_change(): 382 everyone = AclGroup.objects.get(name='Everyone') 383 384 # find hosts that aren't in any ACL group and add them to Everyone 385 # TODO(showard): this is a bit of a hack, since the fact that this query 386 # works is kind of a coincidence of Django internals. This trick 387 # doesn't work in general (on all foreign key relationships). I'll 388 # replace it with a better technique when the need arises. 389 orphaned_hosts = Host.valid_objects.filter(acl_group__id__isnull=True) 390 everyone.hosts.add(*orphaned_hosts.distinct()) 391 392 # find hosts in both Everyone and another ACL group, and remove them 393 # from Everyone 394 hosts_in_everyone = Host.valid_objects.filter_custom_join( 395 '_everyone', acl_group__name='Everyone') 396 acled_hosts = hosts_in_everyone.exclude(acl_group__name='Everyone') 397 everyone.hosts.remove(*acled_hosts.distinct()) 398 399 400 def delete(self): 401 if (self.name == 'Everyone'): 402 raise AclAccessViolation("You cannot delete 'Everyone'!") 403 self.check_for_acl_violation_acl_group() 404 super(AclGroup, self).delete() 405 self.on_host_membership_change() 406 407 408 def add_current_user_if_empty(self): 409 if not self.users.count(): 410 self.users.add(thread_local.get_user()) 411 412 413 # if you have a model attribute called "Manipulator", Django will 414 # automatically insert it into the beginning of the superclass list 415 # for the model's manipulators 416 class Manipulator(object): 417 """ 418 Custom manipulator to get notification when ACLs are changed through 419 the admin interface. 420 """ 421 def save(self, new_data): 422 user = thread_local.get_user() 423 if hasattr(self, 'original_object'): 424 if (not user.is_superuser() 425 and self.original_object.name == 'Everyone'): 426 raise AclAccessViolation("You cannot modify 'Everyone'!") 427 self.original_object.check_for_acl_violation_acl_group() 428 obj = super(AclGroup.Manipulator, self).save(new_data) 429 if not hasattr(self, 'original_object'): 430 obj.users.add(thread_local.get_user()) 431 obj.add_current_user_if_empty() 432 obj.on_host_membership_change() 433 return obj 434 435 class Meta: 436 db_table = 'acl_groups' 437 438 class Admin: 439 list_display = ('name', 'description') 440 search_fields = ('name',) 441 442 def __str__(self): 443 return self.name 444 445# hack to make the column name in the many-to-many DB tables match the one 446# generated by ruby 447AclGroup._meta.object_name = 'acl_group' 448 449 450class JobManager(model_logic.ExtendedManager): 451 'Custom manager to provide efficient status counts querying.' 452 def get_status_counts(self, job_ids): 453 """\ 454 Returns a dictionary mapping the given job IDs to their status 455 count dictionaries. 456 """ 457 if not job_ids: 458 return {} 459 id_list = '(%s)' % ','.join(str(job_id) for job_id in job_ids) 460 cursor = connection.cursor() 461 cursor.execute(""" 462 SELECT job_id, status, COUNT(*) 463 FROM host_queue_entries 464 WHERE job_id IN %s 465 GROUP BY job_id, status 466 """ % id_list) 467 all_job_counts = {} 468 for job_id in job_ids: 469 all_job_counts[job_id] = {} 470 for job_id, status, count in cursor.fetchall(): 471 all_job_counts[job_id][status] = count 472 return all_job_counts 473 474 475class Job(dbmodels.Model, model_logic.ModelExtensions): 476 """\ 477 owner: username of job owner 478 name: job name (does not have to be unique) 479 priority: Low, Medium, High, Urgent (or 0-3) 480 control_file: contents of control file 481 control_type: Client or Server 482 created_on: date of job creation 483 submitted_on: date of job submission 484 synch_type: Asynchronous or Synchronous (i.e. job must run on all hosts 485 simultaneously; used for server-side control files) 486 synch_count: ??? 487 run_verify: Whether or not to run the verify phase 488 synchronizing: for scheduler use 489 timeout: hours until job times out 490 """ 491 Priority = enum.Enum('Low', 'Medium', 'High', 'Urgent') 492 ControlType = enum.Enum('Server', 'Client', start_value=1) 493 Status = enum.Enum('Created', 'Queued', 'Pending', 'Running', 494 'Completed', 'Abort', 'Aborting', 'Aborted', 495 'Failed', 'Starting', string_values=True) 496 497 owner = dbmodels.CharField(maxlength=255) 498 name = dbmodels.CharField(maxlength=255) 499 priority = dbmodels.SmallIntegerField(choices=Priority.choices(), 500 blank=True, # to allow 0 501 default=Priority.MEDIUM) 502 control_file = dbmodels.TextField() 503 control_type = dbmodels.SmallIntegerField(choices=ControlType.choices(), 504 blank=True) # to allow 0 505 created_on = dbmodels.DateTimeField(auto_now_add=True) 506 synch_type = dbmodels.SmallIntegerField( 507 blank=True, null=True, choices=Test.SynchType.choices()) 508 synch_count = dbmodels.IntegerField(blank=True, null=True) 509 synchronizing = dbmodels.BooleanField(default=False) 510 run_verify = dbmodels.BooleanField(default=True) 511 timeout = dbmodels.IntegerField() 512 513 514 # custom manager 515 objects = JobManager() 516 517 518 def is_server_job(self): 519 return self.control_type == self.ControlType.SERVER 520 521 522 @classmethod 523 def create(cls, owner, name, priority, control_file, control_type, 524 hosts, synch_type, timeout, run_verify): 525 """\ 526 Creates a job by taking some information (the listed args) 527 and filling in the rest of the necessary information. 528 """ 529 AclGroup.check_for_acl_violation_hosts(hosts) 530 job = cls.add_object( 531 owner=owner, name=name, priority=priority, 532 control_file=control_file, control_type=control_type, 533 synch_type=synch_type, timeout=timeout, 534 run_verify=run_verify) 535 536 if job.synch_type == Test.SynchType.SYNCHRONOUS: 537 job.synch_count = len(hosts) 538 else: 539 if len(hosts) == 0: 540 errors = {'hosts': 541 'asynchronous jobs require at least' 542 + ' one host to run on'} 543 raise model_logic.ValidationError(errors) 544 job.save() 545 return job 546 547 548 def queue(self, hosts): 549 'Enqueue a job on the given hosts.' 550 for host in hosts: 551 host.enqueue_job(self) 552 553 554 def abort(self): 555 user = thread_local.get_user() 556 if not user.is_superuser() and user.login != self.owner: 557 raise AclAccessViolation("You cannot abort other people's jobs!") 558 for queue_entry in self.hostqueueentry_set.all(): 559 queue_entry.abort() 560 561 562 def user(self): 563 try: 564 return User.objects.get(login=self.owner) 565 except self.DoesNotExist: 566 return None 567 568 569 class Meta: 570 db_table = 'jobs' 571 572 if settings.FULL_ADMIN: 573 class Admin: 574 list_display = ('id', 'owner', 'name', 'control_type') 575 576 def __str__(self): 577 return '%s (%s-%s)' % (self.name, self.id, self.owner) 578 579 580class IneligibleHostQueue(dbmodels.Model, model_logic.ModelExtensions): 581 job = dbmodels.ForeignKey(Job) 582 host = dbmodels.ForeignKey(Host) 583 584 objects = model_logic.ExtendedManager() 585 586 class Meta: 587 db_table = 'ineligible_host_queues' 588 589 if settings.FULL_ADMIN: 590 class Admin: 591 list_display = ('id', 'job', 'host') 592 593 594class HostQueueEntry(dbmodels.Model, model_logic.ModelExtensions): 595 job = dbmodels.ForeignKey(Job) 596 host = dbmodels.ForeignKey(Host, blank=True, null=True) 597 priority = dbmodels.SmallIntegerField() 598 status = dbmodels.CharField(maxlength=255) 599 meta_host = dbmodels.ForeignKey(Label, blank=True, null=True, 600 db_column='meta_host') 601 active = dbmodels.BooleanField(default=False) 602 complete = dbmodels.BooleanField(default=False) 603 deleted = dbmodels.BooleanField(default=False) 604 605 objects = model_logic.ExtendedManager() 606 607 608 def is_meta_host_entry(self): 609 'True if this is a entry has a meta_host instead of a host.' 610 return self.host is None and self.meta_host is not None 611 612 def abort(self): 613 if self.active: 614 self.status = Job.Status.ABORT 615 elif not self.complete: 616 self.status = Job.Status.ABORTED 617 self.active = False 618 self.complete = True 619 self.save() 620 621 class Meta: 622 db_table = 'host_queue_entries' 623 624 if settings.FULL_ADMIN: 625 class Admin: 626 list_display = ('id', 'job', 'host', 'status', 627 'meta_host') 628