instance.py

Fri, 19 Jan 2018 15:41:45 +0000

author
Tuomo Valkonen <tuomov@iki.fi>
date
Fri, 19 Jan 2018 15:41:45 +0000
changeset 4
d72c4844e791
parent 3
4cad934aa9ce
child 6
46c89e5a219f
permissions
-rw-r--r--

Better borg output processing and some logging

#
# Borgend borg launcher / processor
#

import json
import logging
from subprocess import Popen, PIPE
from config import settings, arglistify

necessary_opts=['--log-json', '--progress']

class BorgInstance:
    def __init__(self, operation, archive_or_repository, args, argsl):
        self.operation=operation;
        self.args=args;
        self.archive_or_repository=archive_or_repository;
        self.argsl=argsl;

    def construct_cmdline(self):
        cmd=([settings['borg']['executable']]+necessary_opts+
             arglistify(settings['borg']['common_parameters'])+
             [self.operation])
        tmp1=self.operation+'_parameters'
        if tmp1 in settings['borg']:
            cmd=cmd+arglistify(settings['borg'][tmp1])

        return cmd+arglistify(self.args)+[self.archive_or_repository]+self.argsl

    def launch(self):
        # Borg prints json to stderr, so pipe it
        cmd=self.construct_cmdline()

        logging.info('Launching ' + str(cmd))

        self.proc=Popen(cmd, stderr=PIPE)

    def read(self):
        try:
            line=self.proc.stderr.readline()
        except err:
            logging.info('Pipe read failed: %s' % str(err))

            return {'type': 'exception', 'exception': err}

        if line==b'':

            logging.info('Pipe EOF?')

            return None

        try:
            return json.loads(line)
        except:
            logging.warning('JSON parse failed on: "%s"' % line)

            errmsg=line
            for line in iter(self.proc.stderr.readline, b''):
                errmsg=errmsg+line

            return {'type': 'unparsed_error', 'message': str(errmsg)}

    def terminate(self):
        self.proc.terminate()

    def wait(self):
        return self.proc.wait() is not None

    def has_terminated(self):
        return self.proc.poll() is not None

mercurial