summaryrefslogtreecommitdiff
path: root/morphlib/exts/ssh-rsync.write
blob: 211dbe5ee7c2a6582fafeda73ad1847735ef64ec (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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/python
# Copyright (C) 2013  Codethink Limited
#
# 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; version 2 of the License.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


'''A Morph deployment write extension for upgrading systems over ssh.'''


import cliapp
import os
import sys
import time
import tempfile

import morphlib.writeexts

class SshRsyncWriteExtension(morphlib.writeexts.WriteExtension):

    '''Upgrade a running baserock system with ssh and rsync.

    It assumes the system is baserock-based and has a btrfs partition.

    The location command line argument is the 'user@hostname' string
    that will be passed to ssh and rsync

    '''

    def process_args(self, args):
        if len(args) != 2:
            raise cliapp.AppException('Wrong number of command line args')

        temp_root, location = args

        self.check_valid_target(location)
        self.upgrade_remote_system(location, temp_root)

    def upgrade_remote_system(self, location, temp_root):
        root_disk = self.find_root_disk(location)
        version_label = os.environ.get('VERSION_LABEL')

        self.status(msg='Creating remote mount point')
        remote_mnt = cliapp.ssh_runcmd(location, ['mktemp', '-d']).strip()
        try:
            self.status(msg='Mounting root disk')
            cliapp.ssh_runcmd(location, ['mount', root_disk, remote_mnt])
        except Exception as e:
            try:
                cliapp.ssh_runcmd(location, ['rmdir', remote_mnt])
            except:
                pass
            raise e

        try:
            version_root = os.path.join(remote_mnt, 'systems', version_label)
            run_dir = os.path.join(version_root, 'run')
            orig_dir = os.path.join(version_root, 'orig')

            self.status(msg='Creating %s' % version_root)
            cliapp.ssh_runcmd(location, ['mkdir', version_root])

            self.create_remote_orig(location, version_root, remote_mnt,
                                    temp_root)

            self.status(msg='Creating "run" subvolume')
            cliapp.ssh_runcmd(location, ['btrfs', 'subvolume',
                                         'snapshot', orig_dir, run_dir])

            self.status(msg='Updating system configuration')
            bscs_loc = os.path.join(run_dir, 'usr', 'bin',
                                    'baserock-system-config-sync')

            output = cliapp.ssh_runcmd(location,  ['sh', '-c',
                         '"$1" merge "$2" &> /dev/null || echo -n cmdfailed',
                         '-', bscs_loc, version_label])
            if output == "cmdfailed":
                self.status(msg='Updating system configuration failed')

            self.install_remote_kernel(location, version_root, temp_root)
            default_path = os.path.join(remote_mnt, 'systems', 'default')
            if self.bootloader_is_wanted():
                output = cliapp.ssh_runcmd(location, ['sh', '-c',
                                    'test -e "$1" && stat -c %F "$1" '
                                        '|| echo missing file',
                                    '-', default_path])
                if output != "symbolic link":
                    # we are upgrading and old system that does
                    # not have an updated extlinux config file
                    self.update_remote_extlinux(location, remote_mnt,
                                                version_label)
            cliapp.ssh_runcmd(location, ['ln', '-sfn', version_label,
                                         default_path])
        except Exception as e:
            try:
                cliapp.ssh_runcmd(location,
                    ['btrfs', 'subvolume', 'delete', run_dir])
            except:
                pass
            try:
                cliapp.ssh_runcmd(location,
                    ['btrfs', 'subvolume', 'delete', orig_dir])
            except:
                pass
            try:
                cliapp.ssh_runcmd(location, ['rm', '-rf', version_root])
            except:
                pass
            raise e
        finally:
            self.status(msg='Removing temporary mounts')
            cliapp.ssh_runcmd(location, ['umount', remote_mnt])
            cliapp.ssh_runcmd(location, ['rmdir', remote_mnt])

    def update_remote_extlinux(self, location, remote_mnt, version_label):
        '''Install/reconfigure extlinux on location'''

        self.status(msg='Creating extlinux.conf')
        config = os.path.join(remote_mnt, 'extlinux.conf')
        temp_fd, temp_path = tempfile.mkstemp()
        with os.fdopen(temp_fd, 'w') as f:
            f.write('default linux\n')
            f.write('timeout 1\n')
            f.write('label linux\n')
            f.write('kernel /systems/default/kernel\n')
            f.write('append root=/dev/sda '
                    'rootflags=subvol=systems/default/run '
                    'init=/sbin/init rw\n')

        try:
            cliapp.runcmd(['rsync', '-as', temp_path,
                           '%s:%s~' % (location, config)])
            cliapp.ssh_runcmd(location, ['mv', config+'~', config])
        except Exception as e:
            try:
                cliapp.ssh_runcmd(location, ['rm', '-f', config+'~'])
            except:
                pass
            raise e

    def create_remote_orig(self, location, version_root, remote_mnt,
                           temp_root):
        '''Create the subvolume version_root/orig on location'''

        self.status(msg='Creating "orig" subvolume')
        old_orig = self.get_old_orig(location, remote_mnt)
        new_orig = os.path.join(version_root, 'orig')
        cliapp.ssh_runcmd(location, ['btrfs', 'subvolume', 'snapshot',
                                     old_orig, new_orig])

        cliapp.runcmd(['rsync', '-as', '--checksum', '--numeric-ids',
                       '--delete', temp_root + os.path.sep,
                       '%s:%s' % (location, new_orig)])

    def get_old_orig(self, location, remote_mnt):
        '''Identify which subvolume to snapshot from'''

        # rawdisk upgrades use 'factory'
        return os.path.join(remote_mnt, 'systems', 'factory', 'orig')

    def find_root_disk(self, location):
        '''Read /proc/mounts on location to find which device contains "/"'''

        self.status(msg='Finding device that contains "/"')
        contents = cliapp.ssh_runcmd(location, ['cat', '/proc/mounts'])
        for line in contents.splitlines():
            line_words = line.split()
            if (line_words[1] == '/' and line_words[0] != 'rootfs'):
                return line_words[0]

    def install_remote_kernel(self, location, version_root, temp_root):
        '''Install the kernel in temp_root inside version_root on location'''

        self.status(msg='Installing kernel')
        image_names = ('vmlinuz', 'zImage', 'uImage')
        kernel_dest = os.path.join(version_root, 'kernel')
        for name in image_names:
            try_path = os.path.join(temp_root, 'boot', name)
            if os.path.exists(try_path):
                cliapp.runcmd(['rsync', '-as', try_path,
                               '%s:%s' % (location, kernel_dest)])

    def check_valid_target(self, location):
        try:
            cliapp.ssh_runcmd(location, ['true'])
        except Exception as e:
            raise cliapp.AppException('%s does not respond to ssh:\n%s'
                                      % (location, e))

        output = cliapp.ssh_runcmd(location, ['sh', '-c',
                     'test -d /baserock || echo -n dirnotfound'])
        if output == 'dirnotfound':
            raise cliapp.AppException('%s is not a baserock system'
                                      % location)

        output = cliapp.ssh_runcmd(location, ['sh', '-c',
                     'type rsync &> /dev/null || echo -n cmdnotfound'])
        if output == 'cmdnotfound':
            raise cliapp.AppException('%s does not have rsync'
                                      % location)

SshRsyncWriteExtension().run()