nuclearpinguin commented on a change in pull request #7191: [AIRFLOW-4030] 
second attempt to add singularity to airflow
URL: https://github.com/apache/airflow/pull/7191#discussion_r367827554
 
 

 ##########
 File path: airflow/contrib/operators/singularity_operator.py
 ##########
 @@ -0,0 +1,176 @@
+# -*- coding: utf-8 -*-
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from airflow.exceptions import AirflowException
+from airflow.models import BaseOperator
+from airflow.utils.decorators import apply_defaults
+from spython.main import Client
+import shutil
+import ast
+import os
+
+
+class SingularityOperator(BaseOperator):
+    """
+    Execute a command inside a Singularity container
+
+    Singularity has more seamless connection to the host than Docker, so
+    no special binds are needed to ensure binding content in the user $HOME
+    and temporary directories. If the user needs custom binds, this can
+    be done with --volumes
+
+    :param image: Singularity image or URI from which to create the container.
+    :type image: str
+    :param auto_remove: Delete the container when the process exits
+                        The default is False.
+    :type auto_remove: bool
+    :param command: Command to be run in the container. (templated)
+    :type command: str or list
+    :param start_command: start command to pass to the container instance
+    :type start_command: string or list
+    :param environment: Environment variables to set in the container. 
(templated)
+    :type environment: dict
+    :param force_pull: Pull the image on every run. Default is False.
+    :type force_pull: bool
+    :param volumes: List of volumes to mount into the container, e.g.
+        ``['/host/path:/container/path', '/host/path2:/container/path2']``.
+    :param options: other flags (list) to provide to the instance start
+    :type options: list
+    :param working_dir: Working directory to
+        set on the container (equivalent to the -w switch the docker client)
+    :type working_dir: str
+    """
+    template_fields = ('command', 'environment',)
+    template_ext = ('.sh', '.bash',)
+
+    @apply_defaults
+    def __init__(
+            self,
+            image,
+            api_version=None,
+            command=None,
+            start_command=None,
+            environment=None,
+            pull_folder=None,
+            force_pull=False,
+            volumes=None,
+            options=None,
+            working_dir=None,
+            auto_remove=False,
+            *args,
+            **kwargs):
+
+        super(SingularityOperator, self).__init__(*args, **kwargs)
+        self.api_version = api_version
+        self.auto_remove = auto_remove
+        self.command = command
+        self.start_command = start_command
+        self.environment = environment or {}
+        self.force_pull = force_pull
+        self.image = image
+        self.instance = None
+        self.options = options or []
+        self.pull_folder = pull_folder
+        self.volumes = volumes or []
+        self.working_dir = working_dir
+        self.cli = None
+        self.container = None
+
+    def execute(self, context):
+        self.log.info('Preparing Singularity container %s', self.image)
+        self.cli = Client
+
+        if not self.command:
+            raise AirflowException('You must define a command.')
+
+        # Pull the container if asked, and ensure not a binary file
+        if self.force_pull and not os.path.exists(self.image):
+            self.log.info('Pulling container %s', self.image)
+            image, lines = self.cli.pull(self.image, stream=True)
+            for line in lines:
+                self.log.info(line)
+
+            # Move the container to where it's desired
+            if self.pull_folder is not None:
+                self.image = os.path.join(self.pull_folder, 
os.path.basename(image))
+                shutil.move(image, self.image)
+
+        # Prepare list of binds
+        for bind in self.volumes:
+            self.options = self.options + ['--bind', bind]
+
+        # Does the user want a custom working directory?
+        if self.working_dir is not None:
+            self.options = self.options + ['--workdir', self.working_dir]
+
+        # Export environment before instance is run
+        for enkey, envar in self.environment.items():
+            self.log.debug('Exporting %s=%s', envar, enkey)
+            os.putenv(enkey, envar)
+            os.environ[enkey] = envar
+
+        # Create a container instance
+        self.log.debug('Options include: %s', self.options)
+        self.instance = self.cli.instance(self.image,
+                                          options=self.options,
+                                          args=self.start_command,
+                                          start=False)
+
+        self.instance.start()
+        self.log.info(self.instance.cmd)
+        self.log.info('Created instance %s from %s', self.instance, self.image)
+
+        self.log.info('Running command %s', self.get_command())
+        self.cli.quiet = True
+        result = self.cli.execute(self.instance,
+                                  self.get_command(),
+                                  return_result=True)
+
+        # Stop the instance
+        self.log.info('Stopping instance %s', self.instance)
+        self.instance.stop()
+
+        if self.auto_remove is True:
+            if os.path.exists(self.image):
+                shutil.rmtree(self.image)
+
+        # If the container failed, raise the exception
+        if result['return_code'] != 0:
+            message = result['message']
+            raise AirflowException('Singularity failed: %s' % message)
+
+        self.log.info('Output from command %s', result['message'])
+
+    def get_command(self):
 
 Review comment:
   Pylint will be sad due to no docstring. Please add docstring or make it a 
protected method (`_get_command`).

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to