Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/sugar_network/node/slave.py
blob: 074ae79a0e75fb8e22dacf5ae64d63bb1de2e62a (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
# Copyright (C) 2012-2014 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import shutil
import logging
from urlparse import urlsplit
from os.path import join, dirname, exists, isabs
from gettext import gettext as _

from sugar_network import toolkit
from sugar_network.model.context import Context
from sugar_network.model.post import Post
from sugar_network.model.report import Report
from sugar_network.node.model import User
from sugar_network.node import master_api
from sugar_network.node.routes import NodeRoutes
from sugar_network.toolkit.router import route, ACL
from sugar_network.toolkit.coroutine import this
from sugar_network.toolkit import http, parcel, ranges, enforce


RESOURCES = (User, Context, Post, Report)

_logger = logging.getLogger('node.slave')


class SlaveRoutes(NodeRoutes):

    def __init__(self, volume, **kwargs):
        guid_path = join(volume.root, 'etc', 'node')
        if exists(guid_path):
            with file(guid_path) as f:
                guid = f.read().strip()
        else:
            guid = toolkit.uuid()
            if not exists(dirname(guid_path)):
                os.makedirs(dirname(guid_path))
            with file(guid_path, 'w') as f:
                f.write(guid)
        NodeRoutes.__init__(self, guid, volume=volume, **kwargs)
        vardir = join(volume.root, 'var')
        self._push_r = toolkit.Bin(join(vardir, 'push.ranges'), [[1, None]])
        self._pull_r = toolkit.Bin(join(vardir, 'pull.ranges'), [[1, None]])
        self._master_guid = urlsplit(master_api.value).netloc

    @route('POST', cmd='online_sync', acl=ACL.LOCAL,
            arguments={'no_pull': bool})
    def online_sync(self, no_pull=False):
        conn = http.Connection(master_api.value)
        response = conn.request('POST',
                data=parcel.encode(self._export(not no_pull), header={
                    'from': self.guid,
                    'to': self._master_guid,
                    }),
                params={'cmd': 'sync'},
                headers={'Transfer-Encoding': 'chunked'})
        self._import(parcel.decode(response.raw))

    @route('POST', cmd='offline_sync', acl=ACL.LOCAL)
    def offline_sync(self, path):
        enforce(isabs(path), "Argument 'path' is not an absolute path")

        _logger.debug('Start offline synchronization in %r', path)
        if not exists(path):
            os.makedirs(path)

        this.broadcast({
            'event': 'sync_progress',
            'progress': _('Reading sneakernet packages'),
            })
        requests = self._import(parcel.decode_dir(path))

        this.broadcast({
            'event': 'sync_progress',
            'progress': _('Generating new sneakernet package'),
            })
        offline_script = join(dirname(sys.argv[0]), 'sugar-network-sync')
        if exists(offline_script):
            shutil.copy(offline_script, path)
        parcel.encode_dir(requests + self._export(True), root=path, header={
            'from': self.guid,
            'to': self._master_guid,
            })

        _logger.debug('Synchronization completed')

    def status(self):
        result = NodeRoutes.status(self)
        result['mode'] = 'slave'
        return result

    def _import(self, package):
        requests = []

        for packet in package:
            sender = packet['from']
            from_master = (sender == self._master_guid)
            if packet.name == 'push':
                seqno, committed = this.volume.patch(packet)
                if seqno is not None:
                    if from_master:
                        with self._pull_r as r:
                            ranges.exclude(r, committed)
                    else:
                        requests.append(('request', {
                            'origin': sender,
                            'ranges': committed,
                            }, []))
                    with self._push_r as r:
                        ranges.exclude(r, seqno, seqno)
            elif packet.name == 'ack' and from_master and \
                    packet['to'] == self.guid:
                with self._pull_r as r:
                    ranges.exclude(r, packet['ack'])
                if packet['ranges']:
                    with self._push_r as r:
                        ranges.exclude(r, packet['ranges'])

        return requests

    def _export(self, pull):
        export = []
        if pull:
            export.append(('pull', {'ranges': self._pull_r.value}, None))
        export.append(('push', None, self.volume.diff(self._push_r.value)))
        return export