Exemple #1
0
 def abort(self):
     self._aborted = True
     for future, task in self.futures.items():
         future.cancel()
     if len(self.futures):
         log.info("Waiting for tasks to finish, please be patient")
     self.strategy.executors.shutdown()
Exemple #2
0
    def on_queue_declareok(self, _unused_frame, userdata):
        """Method invoked by pika when the Queue.Declare RPC call made in
        setup_queue has completed. In this method we will bind the queue
        and exchange together with the routing key by issuing the Queue.Bind
        RPC command. When this command is complete, the on_bindok method will
        be invoked by pika.

        :param pika.frame.Method _unused_frame: The Queue.DeclareOk frame
        :param str|unicode userdata: Extra user data (queue name)

        """
        queue_name = userdata
        log.info('Binding {} to {} with {}',
                 self.EXCHANGE, queue_name, self._routing_key)
        cb = functools.partial(self.on_bindok, userdata=queue_name)
        self._channel.queue_bind(
            queue_name,
            self.EXCHANGE,
            routing_key=self._routing_key,
            callback=cb)
        log.info('Binding {} to {} with jolt_{}',
                 self.EXCHANGE, queue_name, self._routing_key)
        self._channel.queue_bind(
            queue_name,
            self.EXCHANGE,
            routing_key="jolt_" + self._routing_key)
Exemple #3
0
    def add_on_channel_close_callback(self):
        """This method tells pika to call the on_channel_closed method if
        RabbitMQ unexpectedly closes the channel.

        """
        log.info('Adding channel close callback')
        self._channel.add_on_close_callback(self.on_channel_closed)
Exemple #4
0
    def close_channel(self):
        """Call to close the channel with RabbitMQ cleanly by issuing the
        Channel.Close RPC command.

        """
        log.info('Closing the channel')
        self._channel.close()
Exemple #5
0
 def close_connection(self):
     self._consuming = False
     if self._connection.is_closing or self._connection.is_closed:
         log.info('Connection is closing or already closed')
     else:
         log.info('Closing connection')
         self._connection.close()
Exemple #6
0
 def _maybe_reconnect(self):
     if self._consumer.should_reconnect:
         self._consumer.stop()
         reconnect_delay = self._get_reconnect_delay()
         log.info('Reconnecting after {} seconds', reconnect_delay)
         time.sleep(reconnect_delay)
         self._consumer = WorkerTaskConsumer(self._amqp_url)
Exemple #7
0
def display(ctx, task, reverse=None, show_cache=False):
    """
    Display a task and its dependencies visually.

    """
    registry = TaskRegistry.get()
    gb = graph.GraphBuilder(registry, ctx.obj["manifest"])
    dag = gb.build(task, influence=show_cache)

    options = JoltOptions()
    acache = cache.ArtifactCache.get(options)

    if reverse:

        def iterator(task):
            return list(dag.predecessors(task))

        reverse = utils.as_list(reverse)
        tasklist = dag.select(lambda graph, node: node.short_qualified_name in
                              reverse or node.qualified_name in reverse)
    else:

        def iterator(task):
            return task.children

        tasklist = dag.requested_goals

    if dag.has_tasks():

        def _display(task, indent=0, last=None):
            header = ""
            if indent > 0:
                for pipe in last[:-1]:
                    if pipe:
                        header += "\u2502 "
                    else:
                        header += "  "
                if last[-1]:
                    header += "\u251c\u2574"
                else:
                    header += "\u2514\u2574"

            if not show_cache:
                colorize = str
            elif task.is_cacheable() and not acache.is_available(task):
                colorize = colors.red
            else:
                colorize = colors.green

            print(header + colorize(task.short_qualified_name))
            children = iterator(task)
            for i in range(0, len(children)):
                _display(children[i],
                         indent + 1,
                         last=(last or []) + [i + 1 != len(children)])

        for task in tasklist:
            _display(task)
    else:
        log.info("no tasks to display")
Exemple #8
0
    def send_report(self, report):
        self.annotate_report(report)
        self.shorten_task_names(report)

        if self._artifact:
            dirname = fs.path.dirname(self._artifact)
            if dirname:
                fs.makedirs(dirname)
            with open(self._artifact, "w") as f:
                f.write(report.transform(self._stylesheet))

        if report.has_failure():
            if not self._failure:
                return
        else:
            if not self._success:
                return

        msg = EmailMessage()
        msg['Subject'] = self._subject
        msg['From'] = self._from
        msg['To'] = ", ".join(utils.unique_list(self._to.split()))
        msg.set_content(
            "Your e-mail client cannot display HTML formatted e-mails.")
        msg.add_alternative(report.transform(self._stylesheet), subtype='html')

        with smtplib.SMTP(self._server) as server:
            log.info("Sending email report to {}", self._to)
            server.send_message(msg)
Exemple #9
0
 def fetch(self):
     refspec = " ".join(self.default_refspecs + self.refspecs)
     with self.tools.cwd(self.path):
         log.info("Fetching {0} from {1}", refspec or 'commits', self.url)
         self.tools.run("git fetch {url} {refspec}",
                        url=self.url,
                        refspec=refspec or '',
                        output_on_error=True)
Exemple #10
0
    def open_channel(self):
        """Open a new channel with RabbitMQ by issuing the Channel.Open RPC
        command. When RabbitMQ responds that the channel is open, the
        on_channel_open callback will be invoked by pika.

        """
        log.info('Creating a new channel')
        self._connection.channel(on_open_callback=self.on_channel_open)
Exemple #11
0
    def add_on_cancel_callback(self):
        """Add a callback that will be invoked if RabbitMQ cancels the consumer
        for some reason. If RabbitMQ does cancel the consumer,
        on_consumer_cancelled will be invoked by pika.

        """
        log.info('Adding consumer cancellation callback')
        self._channel.add_on_cancel_callback(self.on_consumer_cancelled)
Exemple #12
0
    def acknowledge_message(self, delivery_tag):
        """Acknowledge the message delivery from RabbitMQ by sending a
        Basic.Ack RPC method for the delivery tag.

        :param int delivery_tag: The delivery tag from the Basic.Deliver frame

        """
        log.info('Acknowledging message {}', delivery_tag)
        self._channel.basic_ack(delivery_tag)
Exemple #13
0
    def on_exchange_declareok(self, _unused_frame, userdata):
        """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
        command.

        :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame
        :param str|unicode userdata: Extra user data (exchange name)

        """
        log.info('Exchange declared: {}', userdata)
        self.setup_queue(self._queue)
Exemple #14
0
    def on_connection_open(self, _unused_connection):
        """This method is called by pika once the connection to RabbitMQ has
        been established. It passes the handle to the connection object in
        case we need it, but in this case, we'll just mark it unused.

        :param pika.SelectConnection _unused_connection: The connection

        """
        log.info('Connection opened')
        self.open_channel()
Exemple #15
0
 def patch(self, patch):
     if not patch:
         return
     with self.tools.cwd(self.path), self.tools.tmpdir("git") as t:
         patchfile = fs.path.join(t.path, "jolt.diff")
         with open(patchfile, "wb") as f:
             f.write(patch.encode())
         log.info("Applying patch to {0}", self.path)
         self.tools.run("git apply --whitespace=nowarn {patchfile}",
                        patchfile=patchfile)
Exemple #16
0
    def on_basic_qos_ok(self, _unused_frame):
        """Invoked by pika when the Basic.QoS method has completed. At this
        point we will start consuming messages by calling start_consuming
        which will invoke the needed RPC commands to start the process.

        :param pika.frame.Method _unused_frame: The Basic.QosOk response frame

        """
        log.info('QOS set to: {}', self._prefetch_count)
        self.start_consuming()
Exemple #17
0
    def on_bindok(self, _unused_frame, userdata):
        """Invoked by pika when the Queue.Bind method has completed. At this
        point we will set the prefetch count for the channel.

        :param pika.frame.Method _unused_frame: The Queue.BindOk response frame
        :param str|unicode userdata: Extra user data (queue name)

        """
        log.info('Queue bound: {}', userdata)
        self.set_qos()
Exemple #18
0
    def stop_consuming(self):
        """Tell RabbitMQ that you would like to stop consuming by sending the
        Basic.Cancel RPC command.

        """
        if self._channel:
            log.info('Sending a Basic.Cancel RPC command to RabbitMQ')
            cb = functools.partial(self.on_cancelok,
                                   userdata=self._consumer_tag)
            self._channel.basic_cancel(self._consumer_tag, cb)
Exemple #19
0
    def on_consumer_cancelled(self, method_frame):
        """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
        receiving messages.

        :param pika.frame.Method method_frame: The Basic.Cancel frame

        """
        log.info('Consumer was cancelled remotely, shutting down: {}',
                 method_frame)
        if self._channel:
            self._channel.close()
Exemple #20
0
 def checkout(self, rev):
     log.info("Checking out {0} in {1}", rev, self.path)
     with self.tools.cwd(self.path):
         try:
             return self.tools.run("git checkout -f {rev}",
                                   rev=rev,
                                   output=False)
         except Exception:
             self.fetch()
             return self.tools.run("git checkout -f {rev}",
                                   rev=rev,
                                   output_on_error=True)
     self._original_head = False
Exemple #21
0
    def on_channel_open(self, channel):
        """This method is invoked by pika when the channel has been opened.
        The channel object is passed in so we can make use of it.

        Since the channel is now open, we'll declare the exchange to use.

        :param pika.channel.Channel channel: The channel object

        """
        log.info('Channel opened')
        self._channel = channel
        self.add_on_channel_close_callback()
        self.setup_exchange(self.EXCHANGE)
Exemple #22
0
    def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        log.info('Connecting to {}', self._url)
        return pika.SelectConnection(
            parameters=pika.URLParameters(self._url),
            on_open_callback=self.on_connection_open,
            on_open_error_callback=self.on_connection_open_error,
            on_close_callback=self.on_connection_closed)
Exemple #23
0
    def on_cancelok(self, _unused_frame, userdata):
        """This method is invoked by pika when RabbitMQ acknowledges the
        cancellation of a consumer. At this point we will close the channel.
        This will invoke the on_channel_closed method once the channel has been
        closed, which will in-turn close the connection.

        :param pika.frame.Method _unused_frame: The Basic.CancelOk frame
        :param str|unicode userdata: Extra user data (consumer tag)

        """
        self._consuming = False
        log.info('RabbitMQ acknowledged the cancellation of the consumer: {}',
                 userdata)
        self.close_channel()
Exemple #24
0
    def setup_exchange(self, exchange_name):
        """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
        command. When it is complete, the on_exchange_declareok method will
        be invoked by pika.

        :param str|unicode exchange_name: The name of the exchange to declare

        """
        log.info('Declaring exchange: {}', exchange_name)
        # Note: using functools.partial is not required, it is demonstrating
        # how arbitrary data can be passed to the callback when it is called
        cb = functools.partial(self.on_exchange_declareok,
                               userdata=exchange_name)
        self._channel.exchange_declare(exchange=exchange_name,
                                       exchange_type=self.EXCHANGE_TYPE,
                                       callback=cb)
Exemple #25
0
    def setup_queue(self, queue_name):
        """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
        command. When it is complete, the on_queue_declareok method will
        be invoked by pika.

        :param str|unicode queue_name: The name of the queue to declare.

        """
        log.info('Declaring queue {}', queue_name)
        cb = functools.partial(self.on_queue_declareok, userdata=queue_name)
        self._channel.queue_declare(queue=queue_name,
                                    callback=cb,
                                    arguments={
                                        "x-message-deduplication": True,
                                        "x-max-priority": self._max_priority
                                    })
Exemple #26
0
    def on_job_completed(self, job):
        job.join()
        if job.channel is self._channel:
            self._channel.basic_publish(
                exchange=self.RESULT_EXCHANGE,
                routing_key=job.properties.correlation_id,
                properties=pika.BasicProperties(
                    correlation_id=job.properties.correlation_id,
                    expiration="600000"),
                body=str(job.response))

            self.acknowledge_message(job.basic_deliver.delivery_tag)
            log.info("Result published")
        else:
            log.info("Result not published as connection was lost")
        self._job = None
Exemple #27
0
 def clone(self):
     log.info("Cloning into {0}", self.path)
     if fs.path.exists(self.path):
         with self.tools.cwd(self.path):
             self.tools.run(
                 "git init && git remote add origin {} && git fetch",
                 self.url,
                 output_on_error=True)
     else:
         self.tools.run("git clone {0} {1}",
                        self.url,
                        self.path,
                        output_on_error=True)
     raise_error_if(not fs.path.exists(self._git_folder()),
                    "git: failed to clone repository '{0}'", self.relpath)
     self._init_repo()
Exemple #28
0
    def start_consuming(self):
        """This method sets up the consumer by first calling
        add_on_cancel_callback so that the object is notified if RabbitMQ
        cancels the consumer. It then issues the Basic.Consume RPC command
        which returns the consumer tag that is used to uniquely identify the
        consumer with RabbitMQ. We keep the value to use it when we want to
        cancel consuming. The on_message method is passed in as a callback pika
        will invoke when a message is fully received.

        """
        log.info('Issuing consumer related RPC commands')
        self.add_on_cancel_callback()
        self._consumer_tag = self._channel.basic_consume(
            self._queue, self.on_message)
        self.was_consuming = True
        self._consuming = True
Exemple #29
0
            def selfdeploy(self):
                """ Installs the correct version of Jolt as specified in execution request. """

                tools = Tools()
                manifest = JoltManifest()
                try:
                    manifest.parse()
                    ident = manifest.get_parameter("jolt_identity")
                    url = manifest.get_parameter("jolt_url")
                    if not ident or not url:
                        return "jolt"

                    requires = manifest.get_parameter("jolt_requires")

                    log.info("Jolt version: {}", ident)

                    src = "build/selfdeploy/{}/src".format(ident)
                    env = "build/selfdeploy/{}/env".format(ident)

                    if not fs.path.exists(env):
                        try:
                            fs.makedirs(src)
                            tools.run("curl {} | tar zx -C {}", url, src)
                            tools.run("virtualenv {}", env)
                            tools.run(". {}/bin/activate && pip install -e {}",
                                      env, src)
                            if requires:
                                tools.run(
                                    ". {}/bin/activate && pip install {}", env,
                                    requires)
                        except Exception as e:
                            tools.rmtree("build/selfdeploy/{}",
                                         ident,
                                         ignore_errors=True)
                            raise e

                    return ". {}/bin/activate && jolt".format(env)
                except Exception as e:
                    log.exception()
                    raise e
Exemple #30
0
    def stop(self):
        """Cleanly shutdown the connection to RabbitMQ by stopping the consumer
        with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok
        will be invoked by pika, which will then closing the channel and
        connection. The IOLoop is started again because this method is invoked
        when CTRL-C is pressed raising a KeyboardInterrupt exception. This
        exception stops the IOLoop which needs to be running for pika to
        communicate with RabbitMQ. All of the commands issued prior to starting
        the IOLoop will be buffered but not processed.

        """
        if not self._closing:
            self._closing = True
            log.info('Stopping')
            if self._consuming:
                self.stop_consuming()
                self._connection.ioloop.start()
            else:
                self._connection.ioloop.stop()
            log.info('Stopped')
            if self._job:
                self.on_job_completed(self._job)