Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/backup.py
blob: 2dee6a427bac1ee7f452790d21bae1fbaad5adc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# Copyright (C) 2007 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import gobject
import gtk
import sugar.env
import sugar.profile

import os
import popen2
import re
import signal
import sys
from threading import Thread

def start_backup(verbose):
    backup_info = sugar.profile.get_trial2_backup()
    if not backup_info:
        raise RuntimeError("Backup key not defined in Sugar profile")

    match = re.match(r'^([^@]*)@([^:]*):(.*)$', backup_info)
    if not match:
        raise RuntimeError("Backup key '%s' is not user@host:path" % backup_info)

    remote_user = match.group(1)
    server = match.group(2)
    remote_path = match.group(3)

    if sugar.env.is_emulator():
        local_path = sugar.env.get_profile_path()
    else:
        local_path = os.path.expanduser('~')

    privkey = sugar.env.get_profile_path('owner.key')

    ssh_cmd = '/usr/bin/ssh -F /dev/null -o "PasswordAuthentication no" -i "%s" -l "%s"' % (privkey, remote_user)
    rsync_cmd = '/usr/bin/rsync -az%s -e \'%s\' %s "%s:%s"' % (verbose and 'P' or '', ssh_cmd, local_path, server, remote_path)

    pipe = popen2.Popen3(rsync_cmd, True)
    if pipe.poll() != -1:
        raise RuntimeError('rsync failed: %s' % pipe.childerr.read())

    return pipe


class BackupThread(Thread):
    def __init__(self, progress_cb, done_cb):
        self._progress_cb = progress_cb
        self._done_cb = done_cb
        self._errmsg = None
        self._pipe = start_backup(True)

        Thread.__init__(self, target=self._backup_thread)

    def _backup_thread(self):
        for line in self._pipe.fromchild:
            # After each file, rsync prints a line something like:
            #    9350 100%    4.46MB/s    0:00:00 (xfer#9, to-check=7719/7769)
            match = re.match(r'.*to-check=(\d+)/(\d+)', line)
            if match:
                try:
                    remaining = int(match.group(1))
                    total = int(match.group(2))
                    progress = (total - remaining) * 100 / total
                    gobject.idle_add(self._progress_cb, progress)
                except:
                    pass

        if self._pipe.poll() != 0:
            self._errmsg = self._pipe.childerr.read()
        gobject.idle_add(self._done_cb)

    def errmsg(self):
        return self._errmsg

    def kill(self):
        if self._pipe.poll() == -1:
            os.kill(self._pipe.pid, signal.SIGINT)

class BackupDialog(gtk.Dialog):
    def __init__(self):
        gtk.Dialog.__init__(self, flags=gtk.DIALOG_MODAL)
        self.set_title('Backup')
        self.set_has_separator(False)

        label = gtk.Label('Backing up data to school server...')
        self.vbox.pack_start(label)

        self._progress_bar = gtk.ProgressBar()
        self.vbox.pack_start(self._progress_bar)

        self.vbox.show_all()

        self.add_button(gtk.STOCK_STOP, gtk.RESPONSE_CLOSE)

        self._thread = BackupThread(self._progress_cb, self._done_cb)
        self._thread.start()
        self._timeout = gobject.timeout_add(100, self._timeout_cb)

        self.connect('response', self._response_cb)

    def _timeout_cb(self):
        self._progress_bar.pulse()
        return True

    def _progress_cb(self, percent):
        self._progress_bar.set_fraction(percent / 100.0)
        if self._timeout:
            gobject.source_remove(self._timeout)
            self._timeout = None
        return False

    def _done_cb(self):
        self.response(gtk.RESPONSE_CLOSE)

    def _response_cb(self, widget, response):
        if self._timeout:
            gobject.source_remove(self._timeout)

        if self._thread.errmsg():
            dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
                                    gtk.BUTTONS_OK,
                                    "Backup failed:\n%s" % self._thread.errmsg())
            dlg.run()
        elif self._thread.isAlive():
            self._thread.kill()

        self.destroy()

def backup_gui():
    try:
        BackupDialog().run()
    except RuntimeError, e:
        dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, \
                                gtk.BUTTONS_OK, 'Backup failed: %s' % str(e))
        dlg.run()

def backup_cron():
    try:
        pipe = start_backup(False)
        sys.exit(pipe.wait())
    except RuntimeError, e:
        sys.stderr.write("Backup failed: %s\n" % str(e))
        sys.exit(1)

if __name__ == "__main__":
    if os.environ.has_key('DISPLAY'):
        gobject.threads_init()
        backup_gui()
    else:
        backup_cron()