aboutsummaryrefslogtreecommitdiff
blob: 092a04ff96ef072c1094eac31445793116f2148e (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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/usr/bin/python
# -*- coding: utf-8 -*-
###############################################################################
# LAYMAN MOUNTING OVERLAY HANDLER
###############################################################################
# File:       mounter.py
#
#             Controls all mountable overlay types
#
# Copyright:
#             (c) 2014 Devan Franchini
#             Distributed under the terms of the GNU General Public License v2
#            
# Author(s):
#             Devan Franchini <twitch153@gentoo.org>
#
'''
Controls all mountable overlay types.
'''
#==============================================================================
#
# Dependencies
#
#------------------------------------------------------------------------------
from __future__ import unicode_literals

import argparse
import copy
import os
import sys

from  layman.constants  import MOUNT_TYPES
from  layman.utils      import path, run_command
from  layman.version    import VERSION


if sys.hexversion >= 0x30200f0:
    STR = str
else:
    STR = basestring

MOUNT_ARGS = {'Squashfs': ['-o', 'loop', '-t', 'squashfs']}
_USAGE = 'layman-mounter [-h] [-l] [-L] [-m MOUNT [MOUNT ...]]\n'\
         '                      [-u UMOUNT [UMOUNT ...]] [-V]'

def is_mounted(mdir):
    '''
    Determines whether or not an overlay is mounted at it's
    installed overlay.

    @rtype bool
    '''
    return os.path.ismount(mdir)


class Mounter(object):
    '''
    Handles all mountable overlays.
    '''
    def __init__(self, database, overlays, config=None):
        self.config = config
        self.database = database
        self.output = self.config['output']
        self.overlays = overlays
        self.storage = self.config['storage']


    @property
    def installed(self):
        '''
        Returns a dictionary of all installed overlays
        and their overlay objects.

        @rtype dict {'ovl1', <layman.overlays.Overlay object>,...}
        '''
        installed_db = {}

        for overlay in self.overlays():
            ovl_db = self.database().select(overlay)
            installed_db[overlay] = ovl_db
        return installed_db


    @property
    def mountables(self):
        '''
        Returns a dictionary of all mountable overlays and their
        types.

        @rtype dict {'ovl1': 'Squashfs',...}
        '''
        mountable_ovls = {}

        for key in sorted(self.installed):
            for ovl_type in self.installed[key].source_types():
                if ovl_type in MOUNT_TYPES:
                    mountable_ovls[key] = ovl_type
        return mountable_ovls


    @property
    def mounted(self):
        '''
        Returns a dictionary of all mountable overlays and a
        boolean reflecting their mounted status.

        @rtype dict {'ovl1': True, 'ovl2': False,...}
        '''
        mounted_ovls = {}

        for ovl in self.mountables:
            mdir = path([self.storage, ovl])
            mounted_ovls[ovl] = is_mounted(mdir)
        return mounted_ovls


    def _check_selection(self, repos):
        '''
        Internal function to validate the repo parameter.

        @rtype tuple
        '''
        if 'ALL' in repos:
            repos = sorted(self.mountables)
        elif isinstance(repos, STR):
            repos = [repos]

        return repos


    def mount(self, repo, dest=None, install=False, ovl_type=None, pkg=None):
        '''
        Mounts an overlay to it's installation directory.

        @params repo: str of overlay name or "ALL".
        @params dest: str of optional destination dir.
        @params install: bool to reflect whether or not the overlay is being
        installed.
        @params ovl_type: str of optional overlay type.
        @params pkg: str of optional location of package to mount.
        @rtype int: reflects whether or not the overlay was mounted.
        '''
        result = 1

        selection = self._check_selection(repo)

        for i in selection:
            name = {'ovl': i}

            if i not in self.mountables and not install:
                self.output.error('Overlay "%(ovl)s" cannot be mounted!'\
                                    % name)
                continue
            if dest:
                mdir = dest
            else:
                mdir = path([self.storage, i])

            if not is_mounted(mdir):
                if install:
                    args = copy.deepcopy(MOUNT_ARGS[ovl_type])
                else:
                    args = copy.deepcopy(MOUNT_ARGS[self.mountables[i]])
                
                if not pkg:
                    source = self.installed[i].sources[0].src

                    if 'file://' in source:
                        pkg = source.replace('file://', '')
                    else:
                        pkg = path([self.storage, i, source.get_extension()])

                args.append(pkg)
                args.append(mdir)
                result = run_command(self.config, 'mount', args, cmd='mount')
            else:
                self.output.warn('Overlay "%(ovl)s" is already mounted!'\
                                    % name)
        return result


    def umount(self, repo, dest=None, sync=False):
        '''
        Unmounts an overlay from it's installation directory.

        @params repo: str of overlay name or "ALL".
        @params dest: str of optional path to unmount.
        @params sync: bool to reflect whether or not the overlay is being
        synced.
        @rtype int: reflects whether or not it was a successful unmount.
        '''
        result = 1

        selection = self._check_selection(repo)
            
        for i in selection:
            name = {'ovl': i}

            if i not in self.mountables and not sync:
                self.output.error('Overlay "%(ovl)s" cannot be mounted!'\
                                    % name)
                continue
            if dest:
                mdir = dest
            else:
                mdir = path([self.storage, i])

            if is_mounted(mdir):
                args = ['-l', mdir]
                result = run_command(self.config, 'umount', args, cmd='umount')
            else:
                self.output.warn('Overlay "%(ovl)s" is already unmounted!'\
                                    % name)

        return result


class Interactive(object):
    '''
    Interactive CLI session for the Mounter class
    '''
    def __init__(self, config=None, mounter=None):
        self.args = None
        self.parser = None
        self.output = config['output']
        self.storage = config['storage']
        self.mount = mounter
        self.mountables = self.mount.mountables


    def args_parser(self):
        '''
        Parses all command line arguments.

        @rtype argparse.NameSpace object.
        '''
        self.parser = argparse.ArgumentParser(prog='layman-mounter',
            description='Layman\'s utility script to handle mountable '\
                        'overlays.')
        self.parser.add_argument('-l',
                                 '--list-mountables',
                                 action='store_true',
                                 help='Lists all available overlays that'
                                 ' support mounting')
        self.parser.add_argument('-L',
                                 '--list-mounted',
                                 action='store_true',
                                 help='Lists all mounted overlays')
        self.parser.add_argument('-m',
                                 '--mount',
                                 nargs='+',
                                 help='Mounts the selected overlay. Specify '\
                                 '"ALL" to mount all possible overlays')
        self.parser.add_argument('-u',
                                 '--umount',
                                 nargs='+',
                                 help='Unmounts the selected overlay. Specify'\
                                 ' "ALL" to unmount all possible overlays')
        self.parser.add_argument('-V',
                                 '--version',
                                 action='version',
                                 version='%(prog)s ' + VERSION)
        self.args = self.parser.parse_args()


    def __call__(self):
        self.args_parser()
        if len(sys.argv) == 1:
            self.output.notice('usage: %(USAGE)s' % {'USAGE':_USAGE})
            sys.exit(0)
        options = {}

        for key in vars(self.args):
            options[key] = vars(self.args)[key]

        for i in ('list_mountables', 'list_mounted'):
            if options[i]:
                getattr(self, i)()
                self.output.notice('')

        for i in ('umount', 'mount'):
            if options[i]:
                getattr(self.mount, '%(action)s' % {'action': i})(options[i])


    def list_mountables(self):
        '''
        Lists all overlays that can be mounted.
        '''
        self.output.info('Mountable overlays:')
        self.output.info('~~~~~~~~~~~~~~~~~~~')
        if self.mountables:
            for ovl in sorted(self.mountables):
                self.output.info(ovl)
        else:
            self.output.warn('N/A')


    def list_mounted(self):
        '''
        Lists all mounted overlays.
        '''
        mounted = self.mount.mounted

        self.output.info('Overlays:')
        self.output.info('~~~~~~~~~')
        for i in mounted:
            if mounted[i]:
                status = 'Mounted'
            else:
                status = 'Unmounted'
            stat_dict = {'ovl': i, 'status': status}
            self.output.info('Name: %(ovl)s, Status: %(status)s' % stat_dict)