Exemplo n.º 1
0
    def stop_command(self, index, command, returncode):
        """
        Indicate that a command stopped.

        :param index: The index of the command.
        :param command: The command that was executed, as an unicode string.
        :param returncode: The exit status.
        """
        self.stream.write(
            self.format_output(
                "{}\t[{}]\n",
                " " * (self.longest_len - len(command)),
                success("success") if returncode == 0 else error("failed"),
            ))

        if returncode != 0:
            self.binary_stream.write(self.output_map[index].getvalue())
            self.stream.write(
                self.format_output(
                    "{}) {} {}\n",
                    warning(important(index + 1)),
                    error("Command exited with"),
                    important(error(returncode)),
                ))

        del self.output_map[index]
Exemplo n.º 2
0
    def run(self):
        '''Run an infinite loop that wait for requests to run a process.'''

        self.adapter.debug('Run cmd launch pad')
        while True:

            if self.end_event and self.end_event.is_set():
                self.adapter.debug('Terminate thread as requested')
                self.terminate_process()
                break
            elif self.timed_out_event.is_set():
                self.adapter.info('### END PROCESS - %s ###',
                                  error('timed out'))
                self.on_process_timed_out()

            readers = [self.queue_process._reader, self.queue_in._reader]

            r, w, x = select.select(readers, [], [], 1)
            for ready in r:
                if ready == self.queue_process._reader:
                    self.on_process_queue_item_received(
                        self.queue_process.get(block=True))
                elif ready == self.queue_in._reader:
                    self.on_parameter_received(self.queue_in.get(block=True))
                else:
                    raise Error('Unexpected input')
Exemplo n.º 3
0
    def close():
        logger.debug("Closing database at %s.", important(database_path))

        try:
            database.close()
        except OSError as ex:
            logger.warning(
                "Could not close database to %s ! Error was: %s",
                important(database_path),
                error(str(ex)),
            )
Exemplo n.º 4
0
    def on_process_queue_item_received(self, item):
        exit_status, output = item

        if exit_status is None:
            # process produced output and is still running
            self.adapter.info('%s', output.strip())
        else:
            if exit_status == 0:
                self.adapter.info('### END PROCESS - exit status %s ###',
                                  success(exit_status))
            else:
                self.adapter.info('### END PROCESS - exit status %s ###',
                                  error(exit_status))

            self.p = None
Exemplo n.º 5
0
    def on_parameter_received(self, parameter):
        self.adapter.debug('Got parameter %s', parameter)

        if self.is_process_alive(
        ) and self.options['discard_if_already_running']:
            self.adapter.debug('Process already running, discard request')
            return

        if self.is_process_alive() and self.options['stop_previous_process']:
            self.adapter.info('### END PROCESS - %s ###', error('interrupted'))
            self.terminate_process()

        if not self.is_process_alive():
            self.adapter.info('### START PROCESS ###')
            self.run_process(self.cmd_template, parameter)
Exemplo n.º 6
0
import logging
import chromalog

from chromalog.mark.helpers.simple import success, error, important

chromalog.basicConfig(format="%(message)s", level=logging.INFO)
logger = logging.getLogger()

filename = r'/var/lib/status'

logger.info("Booting up system: %s", success("OK"))
logger.info("Booting up network: %s", error("FAIL"))
logger.info("Reading file at %s: %s", important(filename), success("OK"))
Exemplo n.º 7
0
formatter = ColorizingFormatter('[%(levelname)s] %(message)s')

handler = ColorizingStreamHandler()
handler.setFormatter(formatter)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.info("This is a regular info log message.")
logger.info(
    "Trying to read user information from %s using a json parser.",
    important(r'/usr/local/mylib/user-info.json'),
)
logger.warning(
    "Unable to read the file at %s ! Something is wrong.",
    important(r'/usr/local/mylib/user-info.json'),
)
logger.error("Something went really wrong !")
logger.info(
    "This is a %s and this is an %s.",
    success("success"),
    error("error"),
)
logger.info(
    "You can combine %s and %s to get an %s !",
    success("success"),
    important("important"),
    important(success("important-success")),
)
Exemplo n.º 8
0
def info(ctx, fetch):
    debug = ctx.obj['debug']
    loop = ctx.obj['loop']
    plm = ctx.obj['plm']
    database = ctx.obj['database']

    try:
        logger.info(
            "Device information for PowerLine Modem on serial port: %s",
            important(plm.serial_port_url),
        )
        logger.info(
            "Device category: %s (%s)",
            important(plm.device_category.title),
            plm.device_category.examples,
        )
        logger.info(
            "Device subcategory: %s",
            important(plm.device_subcategory.title),
        )
        logger.info("Identity: %s", important(plm.identity))
        logger.info("Firmware version: %s", important(plm.firmware_version))

        controllers, responders = loop.run_until_complete(
            plm.get_all_link_records(),
        )

        devices = database.get_devices()

        if fetch:
            missing_device_identities = {
                record.identity for record in chain(controllers, responders)
                if devices.get(record.identity) is None
            }

            if missing_device_identities:
                logger.info(
                    "Fetching missing device information for %d device(s)...",
                    len(missing_device_identities),
                )

                for index, identity in enumerate(
                    missing_device_identities,
                    start=1,
                ):
                    logger.info(
                        "[%d/%d] %s...",
                        index,
                        len(missing_device_identities),
                        identity,
                    )

                    try:
                        device_info = loop.run_until_complete(
                            asyncio.wait_for(
                                plm.id_request(identity),
                                2,
                            ),
                        )
                    except asyncio.TimeoutError:
                        logger.info(
                            "[%d/%d] %s: %s",
                            index,
                            len(missing_device_identities),
                            identity,
                            error("timed out"),
                        )
                    else:
                        devices[identity] = database.set_device(
                            identity=device_info['identity'],
                            alias=None,
                            description=None,
                            category=device_info['category'],
                            subcategory=device_info['subcategory'],
                            firmware_version=device_info['firmware_version'],
                        )
                        logger.info(
                            "[%d/%d] %s: %s",
                            index,
                            len(missing_device_identities),
                            identity,
                            success("success"),
                        )

                logger.info("Done fetching missing device information.")

        if controllers:
            logger.info("Controllers:")

            for controller in controllers:
                device = devices.get(controller.identity)

                if device:
                    logger.info("%s - %s", controller, success(device))
                else:
                    logger.info("%s", controller)

        if responders:
            logger.info("Responders:")

            for responder in responders:
                device = devices.get(responder.identity)

                if device:
                    logger.info("%s - %s", responder, success(device))
                else:
                    logger.info("%s", responder)

    except Exception as ex:
        if debug:
            logger.exception("Unexpected error.")
        else:
            logger.error("Unexpected error: %s.", ex)