Revert previous commit. Our sbuild is not new enough
[invirt/packages/invirt-dev.git] / invirtibuilder
index d2a571c..b6d4eb8 100755 (executable)
@@ -48,7 +48,20 @@ from invirt.config import structs as config
 
 
 DISTRIBUTION = 'hardy'
-
+logfile = None
+
+def logAndRun(cmd, *args, **kwargs):
+    # Always grab stdout, even if the caller doesn't need it.
+    # TODO: don't slurp it all into memory in that case.
+    if 'stdout' in kwargs and kwargs['stdout'] is None:
+        del kwargs['stdout']
+    kwargs['stderr'] = logfile
+    logfile.write('---> Ran %s\n' % (cmd, ))
+    logfile.write('STDERR:\n')
+    output = c.captureOutput(cmd, *args, **kwargs)
+    logfile.write('STDOUT:\n')
+    logfile.write(output)
+    return output
 
 def getControl(package, ref):
     """Get the parsed debian/control file for a given package.
@@ -93,31 +106,31 @@ def sanitizeVersion(version):
     """Sanitize a Debian package version for use as a git tag.
 
     This function strips the epoch from the version number and
-    replaces any tildes with periods."""
-    if v.debian_version:
+    replaces any tildes with underscores."""
+    if version.debian_version:
         v = '%s-%s' % (version.upstream_version,
                        version.debian_version)
     else:
         v = version.upstream_version
-    return v.replace('~', '.')
+    return v.replace('~', '_')
 
 
 def aptCopy(package, commit, dst_pocket, src_pocket):
     """Copy a package from one pocket to another."""
     binaries = getBinaries(package, commit)
-    c.captureOutput(['reprepro-env', 'copy',
-                     b.pocketToApt(dst_pocket),
-                     b.pocketToApt(src_pocket),
-                     package] + binaries)
+    logAndRun(['reprepro-env', 'copy',
+               b.pocketToApt(dst_pocket),
+               b.pocketToApt(src_pocket),
+               package] + binaries)
 
 
 def sbuild(package, ref, arch, workdir, arch_all=False):
     """Build a package for a particular architecture."""
-    args = ['sbuild', '-d', DISTRIBUTION, '--arch', arch]
+    args = ['sbuild', '-v', '-d', DISTRIBUTION, '--arch', arch]
     if arch_all:
         args.append('-A')
     args.append(getDscName(package, ref))
-    c.captureOutput(args, cwd=workdir, stdout=None)
+    logAndRun(args, cwd=workdir)
 
 
 def sbuildAll(package, ref, workdir):
@@ -129,7 +142,7 @@ def sbuildAll(package, ref, workdir):
         sbuild(package, ref, 'i386', workdir)
 
 
-def tagSubmodule(pocket, package, principal, version, env):
+def tagSubmodule(pocket, package, commit, principal, version, env):
     """Tag a new version of a submodule.
 
     If this pocket does not allow_backtracking, then this will create
@@ -151,28 +164,35 @@ def tagSubmodule(pocket, package, principal, version, env):
                                         package,
                                         principal))
 
-        c.captureOutput(
-            ['git', 'tag', '-m', tag_msg, commit],
-            stdout=None,
-            env=env)
+        logAndRun(
+            ['git', 'tag', '-m', tag_msg, '--', sanitizeVersion(version),
+             commit],
+            env=env,
+            cwd=b.getRepo(package))
 
 
-def updateSubmoduleBranch(pocket, package, ref):
+def updateSubmoduleBranch(pocket, package, commit):
     """Update the appropriately named branch in the submodule."""
     branch = b.pocketToGit(pocket)
-    c.captureOutput(
-        ['git', 'update-ref', 'refs/heads/%s' % branch, ref], cwd=b.getRepo(package))
+    logAndRun(
+        ['git', 'update-ref', 'refs/heads/%s' % branch, commit], cwd=b.getRepo(package))
 
 
 def uploadBuild(pocket, workdir):
     """Upload all build products in the work directory."""
+    force = config.build.pockets[pocket].get('allow_backtracking', False)
     apt = b.pocketToApt(pocket)
     for changes in glob.glob(os.path.join(workdir, '*.changes')):
-        c.captureOutput(['reprepro-env',
-                       '--ignore=wrongdistribution',
-                       'include',
-                       apt,
-                       changes])
+        upload = ['reprepro-env', '--ignore=wrongdistribution',
+                  'include', apt, changes]
+        try:
+            logAndRun(upload)
+        except subprocess.CalledProcessError, e:
+            if not force:
+                raise
+            package = deb822.Changes(open(changes).read())['Binary']
+            logAndRun(['reprepro-env', 'remove', apt, package])
+            logAndRun(upload)
 
 
 def updateSuperproject(pocket, package, commit, principal, version, env):
@@ -186,29 +206,29 @@ def updateSuperproject(pocket, package, commit, principal, version, env):
     """
     superproject = os.path.join(b._REPO_DIR, 'invirt/packages.git')
     branch = b.pocketToGit(pocket)
-    tree = c.captureOutput(['git', 'ls-tree', branch],
-                           cwd=superproject).strip()
+    tree = logAndRun(['git', 'ls-tree', branch],
+                     cwd=superproject).strip()
 
     new_tree = re.compile(
         r'^(160000 commit )[0-9a-f]*(\t%s)$' % package, re.M).sub(
         r'\g<1>%s\g<2>' % commit,
         tree)
 
-    new_tree_id = c.captureOutput(['git', 'mktree', '--missing'],
-                                  cwd=superproject,
-                                  stdin_str=new_tree).strip()
+    new_tree_id = logAndRun(['git', 'mktree', '--missing'],
+                            cwd=superproject,
+                            stdin_str=new_tree).strip()
 
     commit_msg = ('Update %s to version %s\n\n'
                   'Requested by %s' % (package,
                                        version.full_version,
                                        principal))
-    new_commit = c.captureOutput(
+    new_commit = logAndRun(
         ['git', 'commit-tree', new_tree_id, '-p', branch],
         cwd=superproject,
         env=env,
         stdin_str=commit_msg).strip()
 
-    c.captureOutput(
+    logAndRun(
         ['git', 'update-ref', 'refs/heads/%s' % branch, new_commit],
         cwd=superproject)
 
@@ -249,22 +269,14 @@ def packageWorkdir(package, commit):
     finally:
         shutil.rmtree(workdir)
 
-
-def reportBuild(build):
-    """Run hooks to report the results of a build attempt."""
-
-    c.captureOutput(['run-parts',
-                   '--arg=%s' % build.build_id,
-                   '--',
-                   b._HOOKS_DIR])
-
-
 def build():
     """Deal with items in the build queue.
 
     When triggered, iterate over build queue items one at a time,
     until there are no more pending build jobs.
     """
+    global logfile
+
     while True:
         stage = 'processing incoming job'
         queue = os.listdir(b._QUEUE_DIR)
@@ -286,15 +298,27 @@ def build():
 
         database.session.begin()
 
+        logdir = os.path.join(b._LOG_DIR, str(db.build_id))
+        if not os.path.exists(logdir):
+            os.makedirs(logdir)
+
         try:
             db.failed_stage = 'validating job'
-            src = b.validateBuild(pocket, package, commit)
             # Don't expand the commit in the DB until we're sure the user
             # isn't trying to be tricky.
-            db.commit = commit = c.captureOutput(['git', 'rev-parse', commit],
-                                                 cwd=b.getRepo(package)).strip()
+            b.ensureValidPackage(package)
+
+            logfile = open(os.path.join(logdir, '%s.log' % db.package), 'w')
+
+            db.commit = commit = b.canonicalize_commit(package, commit)
+            src = b.validateBuild(pocket, package, commit)
+            version = b.getVersion(package, commit)
+            db.version = str(version)
+            b.runHook('pre-build', [str(db.build_id)])
 
-            db.version = str(b.getVersion(package, commit))
+            env = dict(os.environ)
+            env['GIT_COMMITTER_NAME'] = config.build.tagger.name
+            env['GIT_COMMITTER_EMAIL'] = config.build.tagger.email
 
             # If validateBuild returns something other than True, then
             # it means we should copy from that pocket to our pocket.
@@ -302,8 +326,16 @@ def build():
             # (If the validation failed, validateBuild would have
             # raised an exception)
             if src != True:
+                # TODO: cut out this code duplication
+                db.failed_stage = 'tagging submodule before copying package'
+                tagSubmodule(pocket, package, commit, principal, version, env)
+                db.failed_stage = 'updating submodule branches before copying package'
+                updateSubmoduleBranch(pocket, package, commit)
+                db.failed_stage = 'updating superproject before copying package'
+                updateSuperproject(pocket, package, commit, principal, version, env)
                 db.failed_stage = 'copying package from another pocket'
                 aptCopy(package, commit, pocket, src)
+                
             # If we can't copy the package from somewhere, but
             # validateBuild didn't raise an exception, then we need to
             # do the build ourselves
@@ -320,29 +352,13 @@ def build():
                     # If we were, we could use debuild and get nice
                     # environment scrubbing. Since we're not, debuild
                     # complains about not having an orig.tar.gz
-                    c.captureOutput(['dpkg-buildpackage', '-us', '-uc', '-S'],
-                                  cwd=packagedir,
-                                  stdout=None)
-
-                    try:
-                        db.failed_stage = 'building binary packages'
-                        sbuildAll(package, commit, workdir)
-                    finally:
-                        logdir = os.path.join(b._LOG_DIR, str(db.build_id))
-                        if not os.path.exists(logdir):
-                            os.makedirs(logdir)
-
-                        for log in glob.glob(os.path.join(workdir, '*.build')):
-                            os.copy2(log, logdir)
-
-                    db.failed_stage = 'processing metadata'
-                    env = dict(os.environ)
-                    env['GIT_COMMITTER_NAME'] = config.build.tagger.name
-                    env['GIT_COMMITTER_EMAIL'] = config.build.tagger.email
-                    version = b.getVersion(package, commit)
+                    logAndRun(['dpkg-buildpackage', '-us', '-uc', '-S'],
+                              cwd=packagedir)
 
+                    db.failed_stage = 'building binary packages'
+                    sbuildAll(package, commit, workdir)
                     db.failed_stage = 'tagging submodule'
-                    tagSubmodule(pocket, package, principal, version, env)
+                    tagSubmodule(pocket, package, commit, principal, version, env)
                     db.failed_stage = 'updating submodule branches'
                     updateSubmoduleBranch(pocket, package, commit)
                     db.failed_stage = 'updating superproject'
@@ -359,6 +375,9 @@ def build():
             db.succeeded = True
             db.failed_stage = None
         finally:
+            if logfile is not None:
+                logfile.close()
+
             database.session.save_or_update(db)
             database.session.commit()
 
@@ -366,8 +385,10 @@ def build():
             # build queue item
             os.unlink(os.path.join(b._QUEUE_DIR, build))
 
-            reportBuild(db)
-
+            if db.succeeded:
+                b.runHook('post-build', [str(db.build_id)])
+            else:
+                b.runHook('failed-build', [str(db.build_id)])
 
 class Invirtibuilder(pyinotify.ProcessEvent):
     """Process inotify triggers to build new packages."""