← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] ~cjwatson/launchpad:charm-upload into launchpad:master

 

Colin Watson has proposed merging ~cjwatson/launchpad:charm-upload into launchpad:master.

Commit message:
Add build upload processing for charm recipes

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

For more details, see:
https://code.launchpad.net/~cjwatson/launchpad/+git/launchpad/+merge/405451
-- 
Your team Launchpad code reviewers is requested to review the proposed merge of ~cjwatson/launchpad:charm-upload into launchpad:master.
diff --git a/lib/lp/archiveuploader/charmrecipeupload.py b/lib/lp/archiveuploader/charmrecipeupload.py
new file mode 100644
index 0000000..a8d7dcf
--- /dev/null
+++ b/lib/lp/archiveuploader/charmrecipeupload.py
@@ -0,0 +1,68 @@
+# Copyright 2021 Canonical Ltd.  This software is licensed under the
+# GNU Affero General Public License version 3 (see the file LICENSE).
+
+"""Process a charm recipe upload."""
+
+from __future__ import absolute_import, print_function, unicode_literals
+
+__metaclass__ = type
+__all__ = [
+    "CharmRecipeUpload",
+    ]
+
+import os
+
+import scandir
+from zope.component import getUtility
+
+from lp.archiveuploader.utils import UploadError
+from lp.buildmaster.enums import BuildStatus
+from lp.services.helpers import filenameToContentType
+from lp.services.librarian.interfaces import ILibraryFileAliasSet
+
+
+class CharmRecipeUpload:
+    """A charm recipe upload."""
+
+    def __init__(self, upload_path, logger):
+        """Create a `CharmRecipeUpload`.
+
+        :param upload_path: A directory containing files to upload.
+        :param logger: The logger to be used.
+        """
+        self.upload_path = upload_path
+        self.logger = logger
+
+        self.librarian = getUtility(ILibraryFileAliasSet)
+
+    def process(self, build):
+        """Process this upload, loading it into the database."""
+        self.logger.debug("Beginning processing.")
+
+        found_charm = False
+        charm_paths = []
+        for dirpath, _, filenames in scandir.walk(self.upload_path):
+            if dirpath == self.upload_path:
+                # All relevant files will be in a subdirectory.
+                continue
+            for charm_file in sorted(filenames):
+                if charm_file.endswith(".charm"):
+                    found_charm = True
+                charm_paths.append(os.path.join(dirpath, charm_file))
+
+        if not found_charm:
+            raise UploadError("Build did not produce any charms.")
+
+        for charm_path in charm_paths:
+            libraryfile = self.librarian.create(
+                os.path.basename(charm_path), os.stat(charm_path).st_size,
+                open(charm_path, "rb"),
+                filenameToContentType(charm_path),
+                restricted=build.is_private)
+            build.addFile(libraryfile)
+
+        # The master verifies the status to confirm successful upload.
+        self.logger.debug("Updating %s" % build.title)
+        build.updateStatus(BuildStatus.FULLYBUILT)
+
+        self.logger.debug("Finished upload.")
diff --git a/lib/lp/archiveuploader/tests/test_charmrecipeupload.py b/lib/lp/archiveuploader/tests/test_charmrecipeupload.py
new file mode 100644
index 0000000..72c14be
--- /dev/null
+++ b/lib/lp/archiveuploader/tests/test_charmrecipeupload.py
@@ -0,0 +1,78 @@
+# Copyright 2021 Canonical Ltd.  This software is licensed under the
+# GNU Affero General Public License version 3 (see the file LICENSE).
+
+"""Tests for `CharmRecipeUpload`."""
+
+from __future__ import absolute_import, print_function, unicode_literals
+
+__metaclass__ = type
+
+import os
+
+from storm.store import Store
+
+from lp.archiveuploader.tests.test_uploadprocessor import (
+    TestUploadProcessorBase,
+    )
+from lp.archiveuploader.uploadprocessor import (
+    UploadHandler,
+    UploadStatusEnum,
+    )
+from lp.buildmaster.enums import BuildStatus
+from lp.charms.interfaces.charmrecipe import CHARM_RECIPE_ALLOW_CREATE
+from lp.services.features.testing import FeatureFixture
+from lp.services.osutils import write_file
+
+
+class TestCharmRecipeUploads(TestUploadProcessorBase):
+    """End-to-end tests of charm recipe uploads."""
+
+    def setUp(self):
+        super(TestCharmRecipeUploads, self).setUp()
+        self.useFixture(FeatureFixture({CHARM_RECIPE_ALLOW_CREATE: "on"}))
+
+        self.setupBreezy()
+
+        self.switchToAdmin()
+        self.build = self.factory.makeCharmRecipeBuild(
+            distro_arch_series=self.breezy["i386"])
+        self.build.updateStatus(BuildStatus.UPLOADING)
+        Store.of(self.build).flush()
+        self.switchToUploader()
+        self.options.context = "buildd"
+
+        self.uploadprocessor = self.getUploadProcessor(
+            self.layer.txn, builds=True)
+
+    def test_sets_build_and_state(self):
+        # The upload processor uploads files and sets the correct status.
+        self.assertFalse(self.build.verifySuccessfulUpload())
+        upload_dir = os.path.join(
+            self.incoming_folder, "test", str(self.build.id), "ubuntu")
+        write_file(os.path.join(upload_dir, "foo_0_all.charm"), b"charm")
+        write_file(
+            os.path.join(upload_dir, "foo_0_all.manifest"), b"manifest")
+        handler = UploadHandler.forProcessor(
+            self.uploadprocessor, self.incoming_folder, "test", self.build)
+        result = handler.processCharmRecipe(self.log)
+        self.assertEqual(
+            UploadStatusEnum.ACCEPTED, result,
+            "Charm upload failed\nGot: %s" % self.log.getLogBuffer())
+        self.assertEqual(BuildStatus.FULLYBUILT, self.build.status)
+        self.assertTrue(self.build.verifySuccessfulUpload())
+
+    def test_requires_charm(self):
+        # The upload processor fails if the upload does not contain any
+        # .charm files.
+        self.assertFalse(self.build.verifySuccessfulUpload())
+        upload_dir = os.path.join(
+            self.incoming_folder, "test", str(self.build.id), "ubuntu")
+        write_file(
+            os.path.join(upload_dir, "foo_0_all.manifest"), b"manifest")
+        handler = UploadHandler.forProcessor(
+            self.uploadprocessor, self.incoming_folder, "test", self.build)
+        result = handler.processCharmRecipe(self.log)
+        self.assertEqual(UploadStatusEnum.REJECTED, result)
+        self.assertIn(
+            "ERROR Build did not produce any charms.", self.log.getLogBuffer())
+        self.assertFalse(self.build.verifySuccessfulUpload())
diff --git a/lib/lp/archiveuploader/uploadprocessor.py b/lib/lp/archiveuploader/uploadprocessor.py
index 2593673..b8d1148 100644
--- a/lib/lp/archiveuploader/uploadprocessor.py
+++ b/lib/lp/archiveuploader/uploadprocessor.py
@@ -1,4 +1,4 @@
-# Copyright 2009-2018 Canonical Ltd.  This software is licensed under the
+# Copyright 2009-2021 Canonical Ltd.  This software is licensed under the
 # GNU Affero General Public License version 3 (see the file LICENSE).
 
 """Code for 'processing' 'uploads'. Also see nascentupload.py.
@@ -56,6 +56,7 @@ from sqlobject import SQLObjectNotFound
 from zope.component import getUtility
 
 from lp.app.errors import NotFoundError
+from lp.archiveuploader.charmrecipeupload import CharmRecipeUpload
 from lp.archiveuploader.livefsupload import LiveFSUpload
 from lp.archiveuploader.nascentupload import (
     EarlyReturnUploadError,
@@ -70,6 +71,7 @@ from lp.archiveuploader.uploadpolicy import (
 from lp.archiveuploader.utils import UploadError
 from lp.buildmaster.enums import BuildStatus
 from lp.buildmaster.interfaces.buildfarmjob import ISpecificBuildFarmJobSource
+from lp.charms.interfaces.charmrecipebuild import ICharmRecipeBuild
 from lp.code.interfaces.sourcepackagerecipebuild import (
     ISourcePackageRecipeBuild,
     )
@@ -658,6 +660,31 @@ class BuildUploadHandler(UploadHandler):
             self.processor.ztm.abort()
             raise
 
+    def processCharmRecipe(self, logger=None):
+        """Process a charm recipe upload."""
+        assert ICharmRecipeBuild.providedBy(self.build)
+        if logger is None:
+            logger = self.processor.log
+        try:
+            logger.info("Processing charm upload %s" % self.upload_path)
+            CharmRecipeUpload(self.upload_path, logger).process(self.build)
+
+            if self.processor.dry_run:
+                logger.info("Dry run, aborting transaction.")
+                self.processor.ztm.abort()
+            else:
+                logger.info(
+                    "Committing the transaction and any mails associated "
+                    "with this upload.")
+                self.processor.ztm.commit()
+            return UploadStatusEnum.ACCEPTED
+        except UploadError as e:
+            logger.error(str(e))
+            return UploadStatusEnum.REJECTED
+        except:
+            self.processor.ztm.abort()
+            raise
+
     def process(self):
         """Process an upload that is the result of a build.
 
@@ -701,6 +728,8 @@ class BuildUploadHandler(UploadHandler):
                 result = self.processSnap(logger)
             elif IOCIRecipeBuild.providedBy(self.build):
                 result = self.processOCIRecipe(logger)
+            elif ICharmRecipeBuild.providedBy(self.build):
+                result = self.processCharmRecipe(logger)
             else:
                 self.processor.log.debug("Build %s found" % self.build.id)
                 [changes_file] = self.locateChangesFiles()