13 log
= logging
.getLogger("builds")
21 from .constants
import *
22 from .decorators
import *
24 class Jobs(base
.Object
):
25 def _get_job(self
, query
, *args
):
26 res
= self
.db
.get(query
, *args
)
29 return Job(self
.backend
, res
.id, data
=res
)
31 def _get_jobs(self
, query
, *args
):
32 res
= self
.db
.query(query
, *args
)
35 yield Job(self
.backend
, row
.id, data
=row
)
37 def create(self
, build
, arch
, type="build", superseeds
=None):
38 job
= self
._get
_job
("INSERT INTO jobs(uuid, type, build_id, arch, time_created) \
39 VALUES(%s, %s, %s, %s, NOW()) RETURNING *", "%s" % uuid
.uuid4(), type, build
.id, arch
)
42 # Set cache for Build object.
45 # Mark if the new job superseeds some other job
47 superseeds
.superseeded_by
= job
49 # Jobs are by default in state "new" and wait for being checked
50 # for dependencies. Packages that do have no build dependencies
51 # can directly be forwarded to "pending" state.
52 if not job
.pkg
.requires
:
57 def get_by_id(self
, id, data
=None):
58 return Job(self
.backend
, id, data
)
60 def get_by_uuid(self
, uuid
):
61 job
= self
.db
.get("SELECT id FROM jobs WHERE uuid = %s", uuid
)
64 return self
.get_by_id(job
.id)
66 def get_by_build(self
, build_id
, build
=None, type=None):
68 Get all jobs in the specifies build.
70 query
= "SELECT * FROM jobs WHERE build_id = %s"
74 query
+= " AND type = %s"
77 # Get IDs of all builds in this group.
79 for job
in self
.db
.query(query
, *args
):
80 job
= Job(self
.backend
, job
.id, job
)
82 # If the Build object was set, we set it so it won't be retrieved
83 # from the database again.
89 # Return sorted list of jobs.
92 def get_active(self
, host_id
=None, builder
=None, states
=None):
97 states
= ["dispatching", "running", "uploading"]
99 query
= "SELECT * FROM jobs WHERE state IN (%s)" % ", ".join(["%s"] * len(states
))
103 query
+= " AND builder_id = %s" % host_id
105 query
+= " ORDER BY \
107 WHEN jobs.state = 'running' THEN 0 \
108 WHEN jobs.state = 'uploading' THEN 1 \
109 WHEN jobs.state = 'dispatching' THEN 2 \
110 WHEN jobs.state = 'pending' THEN 3 \
111 WHEN jobs.state = 'new' THEN 4 \
112 END, time_started ASC"
114 return [Job(self
.backend
, j
.id, j
) for j
in self
.db
.query(query
, *args
)]
116 def get_latest(self
, arch
=None, builder
=None, limit
=None, age
=None, date
=None):
117 query
= "SELECT * FROM jobs"
120 where
= ["(state = 'finished' OR state = 'failed' OR state = 'aborted')"]
123 where
.append("arch = %s")
127 where
.append("builder_id = %s")
128 args
.append(builder
.id)
132 year
, month
, day
= date
.split("-", 2)
133 date
= datetime
.date(int(year
), int(month
), int(day
))
137 where
.append("(time_created::date = %s OR \
138 time_started::date = %s OR time_finished::date = %s)")
139 args
+= (date
, date
, date
)
142 where
.append("time_finished >= NOW() - '%s'::interval" % age
)
145 query
+= " WHERE %s" % " AND ".join(where
)
147 query
+= " ORDER BY time_finished DESC"
153 return [Job(self
.backend
, j
.id, j
) for j
in self
.db
.query(query
, *args
)]
155 def get_average_build_time(self
):
157 Returns the average build time of all finished builds from the
160 result
= self
.db
.get("SELECT AVG(time_finished - time_started) as average \
161 FROM jobs WHERE type = 'build' AND state = 'finished' AND \
162 time_finished >= NOW() - '3 months'::interval")
165 return result
.average
167 def count(self
, *states
):
168 query
= "SELECT COUNT(*) AS count FROM jobs"
172 query
+= " WHERE state IN %s"
175 jobs
= self
.db
.get(query
, *args
)
179 def restart_failed(self
):
180 jobs
= self
._get
_jobs
("SELECT jobs.* FROM jobs \
181 JOIN builds ON builds.id = jobs.build_id \
183 jobs.type = 'build' AND \
184 jobs.state = 'failed' AND \
185 NOT builds.state = 'broken' AND \
186 jobs.time_finished < NOW() - '72 hours'::interval \
189 WHEN jobs.type = 'build' THEN 0 \
190 WHEN jobs.type = 'test' THEN 1 \
192 builds.priority DESC, jobs.time_created ASC")
196 job
.set_state("new", log
=False)
199 class Job(base
.DataObject
):
203 return "<%s id=%s %s>" % (self
.__class
__.__name
__, self
.id, self
.name
)
205 def __eq__(self
, other
):
206 if isinstance(other
, self
.__class
__):
207 return self
.id == other
.id
209 def __lt__(self
, other
):
210 if isinstance(other
, self
.__class
__):
211 if not self
.test
and other
.test
:
214 if self
.build
== other
.build
:
215 return arches
.priority(self
.arch
) < arches
.priority(other
.arch
)
217 return self
.time_created
< other
.time_created
220 packages
= self
.backend
.packages
._get
_packages
("SELECT packages.* FROM jobs_packages \
221 LEFT JOIN packages ON jobs_packages.pkg_id = packages.id \
222 WHERE jobs_packages.job_id = %s ORDER BY packages.name", self
.id)
224 return iter(packages
)
226 def __nonzero__(self
):
230 res
= self
.db
.get("SELECT COUNT(*) AS len FROM jobs_packages \
231 WHERE job_id = %s", self
.id)
237 return self
.build
.distro
239 def get_superseeded_by(self
):
240 if self
.data
.superseeded_by
:
241 return self
.backend
.jobs
.get_by_id(self
.data
.superseeded_by
)
243 def set_superseeded_by(self
, superseeded_by
):
244 assert isinstance(superseeded_by
, self
.__class
__)
246 self
._set
_attribute
("superseeded_by", superseeded_by
.id)
247 self
.superseeded_by
= superseeded_by
249 superseeded_by
= lazy_property(get_superseeded_by
, set_superseeded_by
)
252 self
._set
_attribute
("delete", True)
256 Removes a job from the database
258 self
.__remove
_buildroots
()
259 self
.__remove
_history
()
260 self
.__remove
_packages
()
261 self
.__remove
_logfiles
()
263 # Delete the job itself.
264 self
.db
.execute("DELETE FROM jobs WHERE id = %s", self
.id)
266 def __remove_buildroots(self
):
268 Removes all buildroots.
270 self
.db
.execute("DELETE FROM jobs_buildroots WHERE job_id = %s", self
.id)
272 def __remove_history(self
):
274 Removes all references in the history to this build job.
276 self
.db
.execute("DELETE FROM jobs_history WHERE job_id = %s", self
.id)
278 def __remove_packages(self
):
280 Deletes all uploaded files from the job.
282 for pkg
in self
.packages
:
285 self
.db
.execute("DELETE FROM jobs_packages WHERE job_id = %s", self
.id)
287 def __remove_logfiles(self
):
288 for logfile
in self
.logfiles
:
289 self
.db
.execute("INSERT INTO queue_delete(path) VALUES(%s)", logfile
.path
)
293 def log(self
, action
, user
=None, state
=None, builder
=None, test_job
=None):
300 builder_id
= builder
.id
304 test_job_id
= test_job
.id
306 self
.db
.execute("INSERT INTO jobs_history(job_id, action, state, user_id, \
307 time, builder_id, test_job_id) VALUES(%s, %s, %s, %s, NOW(), %s, %s)",
308 self
.id, action
, state
, user_id
, builder_id
, test_job_id
)
310 def get_log(self
, limit
=None, offset
=None, user
=None):
311 query
= "SELECT * FROM jobs_history"
313 conditions
= ["job_id = %s",]
317 conditions
.append("user_id = %s")
321 query
+= " WHERE %s" % " AND ".join(conditions
)
323 query
+= " ORDER BY time DESC"
327 query
+= " LIMIT %s,%s"
328 args
+= [offset
, limit
,]
334 for entry
in self
.db
.query(query
, *args
):
335 entry
= logs
.JobLogEntry(self
.backend
, entry
)
336 entries
.append(entry
)
342 return self
.data
.uuid
346 return self
.data
.test
350 return self
.data
.build_id
354 return self
.backend
.builds
.get_by_id(self
.build_id
)
357 def related_jobs(self
):
360 for job
in self
.build
.jobs
:
370 return self
.build
.pkg
374 return "%s-%s.%s" % (self
.pkg
.name
, self
.pkg
.friendly_version
, self
.arch
)
378 return sum((p
.size
for p
in self
.packages
))
383 Returns the rank in the build queue
385 if not self
.state
== "pending":
388 res
= self
.db
.get("SELECT rank FROM jobs_queue WHERE job_id = %s", self
.id)
393 def is_running(self
):
395 Returns True if job is in a running state.
397 return self
.state
in ("pending", "dispatching", "running", "uploading")
400 return self
.data
.state
402 def set_state(self
, state
, user
=None, log
=True):
403 # Nothing to do if the state remains.
404 if not self
.state
== state
:
405 self
.db
.execute("UPDATE jobs SET state = %s WHERE id = %s", state
, self
.id)
408 if log
and not state
== "new":
409 self
.log("state_change", state
=state
, user
=user
)
413 self
._data
["state"] = state
415 # Always clear the message when the status is changed.
416 self
.update_message(None)
418 # Update some more informations.
419 if state
== "dispatching":
421 self
.db
.execute("UPDATE jobs SET time_started = NOW(), time_finished = NULL \
422 WHERE id = %s", self
.id)
424 elif state
== "pending":
425 self
.db
.execute("UPDATE jobs SET time_started = NULL, \
426 time_finished = NULL WHERE id = %s", self
.id)
428 elif state
in ("aborted", "dependency_error", "finished", "failed"):
429 # Set finish time and reset builder..
430 self
.db
.execute("UPDATE jobs SET time_finished = NOW() WHERE id = %s", self
.id)
432 # Send messages to the user.
433 if state
== "finished":
434 self
.send_finished_message()
436 elif state
== "failed":
437 # Remove all package files if a job is set to failed state.
438 self
.__delete
_packages
()
440 self
.send_failed_message()
442 # Automatically update the state of the build (not on test builds).
444 self
.build
.auto_update_state()
446 state
= property(get_state
, set_state
)
450 return self
.data
.message
452 def update_message(self
, msg
):
453 self
.db
.execute("UPDATE jobs SET message = %s WHERE id = %s",
457 self
._data
["message"] = msg
459 def get_builder(self
):
460 if self
.data
.builder_id
:
461 return self
.backend
.builders
.get_by_id(self
.data
.builder_id
)
463 def set_builder(self
, builder
, user
=None):
464 self
.db
.execute("UPDATE jobs SET builder_id = %s WHERE id = %s",
469 self
._data
["builder_id"] = builder
.id
471 self
._builder
= builder
475 self
.log("builder_assigned", builder
=builder
, user
=user
)
477 builder
= lazy_property(get_builder
, set_builder
)
481 return self
.data
.arch
485 if not self
.time_started
:
488 if self
.time_finished
:
489 delta
= self
.time_finished
- self
.time_started
491 delta
= datetime
.datetime
.utcnow() - self
.time_started
493 return delta
.total_seconds()
496 def time_created(self
):
497 return self
.data
.time_created
500 def time_started(self
):
501 return self
.data
.time_started
504 def time_finished(self
):
505 return self
.data
.time_finished
508 def expected_runtime(self
):
510 Returns the estimated time and stddev, this job takes to finish.
512 # Get the average build time.
513 build_times
= self
.backend
.builds
.get_build_times_by_arch(self
.arch
,
516 # If there is no statistical data, we cannot estimate anything.
520 return build_times
.average
, build_times
.stddev
524 expected_runtime
, stddev
= self
.expected_runtime
527 return expected_runtime
- int(self
.duration
), stddev
529 def get_pkg_by_uuid(self
, uuid
):
530 pkg
= self
.backend
.packages
._get
_package
("SELECT packages.id FROM packages \
531 JOIN jobs_packages ON jobs_packages.pkg_id = packages.id \
532 WHERE jobs_packages.job_id = %s AND packages.uuid = %s",
543 for log
in self
.db
.query("SELECT id FROM logfiles WHERE job_id = %s", self
.id):
544 log
= logs
.LogFile(self
.backend
, log
.id)
551 def add_file(self
, filename
):
553 Add the specified file to this job.
555 The file is copied to the right directory by this function.
557 assert os
.path
.exists(filename
)
559 if filename
.endswith(".log"):
560 self
._add
_file
_log
(filename
)
562 elif filename
.endswith(".%s" % PACKAGE_EXTENSION
):
563 # It is not allowed to upload packages on test builds.
567 self
._add
_file
_package
(filename
)
569 def _add_file_log(self
, filename
):
571 Attach a log file to this job.
573 target_dirname
= os
.path
.join(self
.build
.path
, "logs")
578 target_filename
= os
.path
.join(target_dirname
,
579 "test.%s.%s.%s.log" % (self
.arch
, i
, self
.uuid
))
581 if os
.path
.exists(target_filename
):
586 target_filename
= os
.path
.join(target_dirname
,
587 "build.%s.%s.log" % (self
.arch
, self
.uuid
))
589 # Make sure the target directory exists.
590 if not os
.path
.exists(target_dirname
):
591 os
.makedirs(target_dirname
)
593 # Calculate a SHA512 hash from that file.
594 f
= open(filename
, "rb")
597 buf
= f
.read(BUFFER_SIZE
)
604 # Copy the file to the final location.
605 shutil
.copy2(filename
, target_filename
)
607 # Create an entry in the database.
608 self
.db
.execute("INSERT INTO logfiles(job_id, path, filesize, hash_sha512) \
609 VALUES(%s, %s, %s, %s)", self
.id, os
.path
.relpath(target_filename
, PACKAGES_DIR
),
610 os
.path
.getsize(target_filename
), h
.hexdigest())
612 def _add_file_package(self
, filename
):
613 # Open package (creates entry in the database)
614 pkg
= self
.backend
.packages
.create(filename
)
616 # Move package to the build directory.
617 pkg
.move(os
.path
.join(self
.build
.path
, self
.arch
))
619 # Attach the package to this job.
620 self
.db
.execute("INSERT INTO jobs_packages(job_id, pkg_id) VALUES(%s, %s)",
623 def get_aborted_state(self
):
624 return self
.data
.aborted_state
626 def set_aborted_state(self
, state
):
627 self
._set
_attribute
("aborted_state", state
)
629 aborted_state
= property(get_aborted_state
, set_aborted_state
)
632 def message_recipients(self
):
635 # Add all people watching the build.
636 l
+= self
.build
.message_recipients
638 # Add the package maintainer on release builds.
639 if self
.build
.type == "release":
640 maint
= self
.pkg
.maintainer
642 if isinstance(maint
, users
.User
):
643 l
.append("%s <%s>" % (maint
.realname
, maint
.email
))
647 # XXX add committer and commit author.
649 # Add the owner of the scratch build on scratch builds.
650 elif self
.build
.type == "scratch" and self
.build
.user
:
651 l
.append("%s <%s>" % \
652 (self
.build
.user
.realname
, self
.build
.user
.email
))
656 def save_buildroot(self
, pkgs
):
657 # Cleanup old stuff first (for rebuilding packages)
658 self
.db
.execute("DELETE FROM jobs_buildroots WHERE job_id = %s", self
.id)
660 for pkg_name
, pkg_uuid
in pkgs
:
661 self
.db
.execute("INSERT INTO jobs_buildroots(job_id, pkg_uuid, pkg_name) \
662 VALUES(%s, %s, %s)", self
.id, pkg_name
, pkg_uuid
)
666 rows
= self
.db
.query("SELECT * FROM jobs_buildroots \
667 WHERE jobs_buildroots.job_id = %s ORDER BY pkg_name", self
.id)
671 # Search for this package in the packages table.
672 pkg
= self
.backend
.packages
.get_by_uuid(row
.pkg_uuid
)
673 pkgs
.append((row
.pkg_name
, row
.pkg_uuid
, pkg
))
677 def send_finished_message(self
):
678 # Send no finished mails for test jobs.
682 logging
.debug("Sending finished message for job %s to %s" % \
683 (self
.name
, ", ".join(self
.message_recipients
)))
686 "build_name" : self
.name
,
687 "build_host" : self
.builder
.name
,
688 "build_uuid" : self
.uuid
,
691 self
.backend
.messages
.send_to_all(self
.message_recipients
,
692 MSG_BUILD_FINISHED_SUBJECT
, MSG_BUILD_FINISHED
, info
)
694 def send_failed_message(self
):
695 logging
.debug("Sending failed message for job %s to %s" % \
696 (self
.name
, ", ".join(self
.message_recipients
)))
700 build_host
= self
.builder
.name
703 "build_name" : self
.name
,
704 "build_host" : build_host
,
705 "build_uuid" : self
.uuid
,
708 self
.backend
.messages
.send_to_all(self
.message_recipients
,
709 MSG_BUILD_FAILED_SUBJECT
, MSG_BUILD_FAILED
, info
)
711 def set_start_time(self
, start_not_before
):
712 self
._set
_attribute
("start_not_before", start_not_before
)
714 def schedule(self
, type, start_time
=None, user
=None):
715 assert type in ("rebuild", "test")
717 if type == "rebuild":
718 if self
.state
== "finished":
721 self
.set_state("new", user
=user
, log
=False)
722 self
.set_start_time(start_time
)
725 self
.log("schedule_rebuild", user
=user
)
728 if not self
.state
== "finished":
731 # Create a new job with same build and arch.
732 job
= self
.create(self
.backend
, self
.build
, self
.arch
, type="test")
733 job
.set_start_time(start_time
)
736 self
.log("schedule_test_job", test_job
=job
, user
=user
)
740 def schedule_test(self
, start_not_before
=None, user
=None):
742 return self
.schedule("test", start_time
=start_not_before
, user
=user
)
744 def schedule_rebuild(self
, start_not_before
=None, user
=None):
746 return self
.schedule("rebuild", start_time
=start_not_before
, user
=user
)
748 def get_build_repos(self
):
750 Returns a list of all repositories that should be used when
753 repo_ids
= self
.db
.query("SELECT repo_id FROM jobs_repos WHERE job_id = %s",
757 return self
.distro
.get_build_repos()
760 for repo
in self
.distro
.repositories
:
761 if repo
.id in [r
.id for r
in repo_ids
]:
764 return repos
or self
.distro
.get_build_repos()
766 def get_repo_config(self
):
768 Get repository configuration file that is sent to the builder.
772 for repo
in self
.get_build_repos():
773 confs
.append(repo
.get_conf())
775 return "\n\n".join(confs
)
777 def get_config(self
):
779 Get configuration file that is sent to the builder.
783 # Add the distribution configuration.
784 confs
.append(self
.distro
.get_config())
786 # Then add all repositories for this build.
787 confs
.append(self
.get_repo_config())
789 return "\n\n".join(confs
)
792 config
= pakfire
.config
.Config(files
=["general.conf"])
793 config
.parse(self
.get_config())
795 # The filename of the source file.
796 filename
= os
.path
.join(PACKAGES_DIR
, self
.build
.pkg
.path
)
797 assert os
.path
.exists(filename
), filename
799 # Create a new pakfire instance with the configuration for
801 p
= pakfire
.PakfireServer(config
=config
, arch
=self
.arch
)
803 # Try to solve the build dependencies.
805 solver
= p
.resolvdep(filename
)
807 # Catch dependency errors and log the problem string.
808 except DependencyError
, e
:
809 self
.state
= "dependency_error"
810 self
.update_message(e
)
813 # If the build dependencies can be resolved, we set the build in
815 if solver
.status
is True:
816 if self
.state
in ("failed",):
819 self
.state
= "pending"