summaryrefslogtreecommitdiff
blob: 06d9e048d3279772d46bb9d4c1407c1e2ed7cbf6 (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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
#!/usr/bin/python -O
#
# /usr/sbin/webapp-config
#       Python script for managing the deployment of web-based
#       applications
#
#       Originally written for the Gentoo Linux distribution
#
# Copyright (c) 1999-2007 Authors
#       Released under v2 of the GNU GPL
#
# Author(s)     Stuart Herbert
#               Renat Lumpau   <rl03@gentoo.org>
#               Gunnar Wrobel  <wrobel@gentoo.org>
#
# ========================================================================
''' This module provides handlers for the web application database as
well as the database of virtual installs.  '''

# ========================================================================
# Dependencies
# ------------------------------------------------------------------------

import time, os, os.path, re

import WebappConfig.wrapper as wrapper

from WebappConfig.debug       import OUT
from WebappConfig.permissions import PermissionMap


# ========================================================================
# Reduced base class
# ------------------------------------------------------------------------

class AppHierarchy:
    '''
    This base class provides a few common classes shared between the db
    handler for /var/db/webapps and /usr/share/webapps.

    Doctests can be found in the derived classes.
    '''


    def __init__(self,
                 fs_root,
                 root,
                 category   = '',
                 package    = '',
                 version    = '',
                 dbfile     = 'installs'):

        self.__r        = fs_root
        self.root       = self.__r + root
        self.root       = re.compile('/+').sub('/', self.root)

        if not os.path.isdir(self.root):
            OUT.die('"' + self.root + '" specifies no directory! webapp'
                    '-config needs a valid directory to store/retrieve in'
                    'formation. Please correct your settings.')

        self.category   = category
        self.pn         = package
        self.pvr        = version
        self.dbfile     = dbfile

    def package_name(self):
        ''' Returns the package name in case the database has been initialized
        with a specific name and version.'''
        if self.category:
            return self.category + '/' + self.pn + '-' + self.pvr
        else:
            return self.pn + '-' + self.pvr

    def set_category(self, cat):
        ''' Set category name.'''
        self.category = cat

    def set_package(self, package):
        ''' Set the package name.'''
        self.pn = package

    def set_version(self, version):
        ''' Set the package version.'''
        self.pvr = version

    def approot(self):
        ''' Return the root directory of the package.'''
        if self.pn:
            result = self.root + '/' + self.category + '/' + self.pn
            return re.compile('/+').sub('/', result)

    def appdir(self):
        ''' Return specific package directory (name + version).'''
        if self.pvr and self.approot():
            result = self.approot() + '/' + self.pvr
            return re.compile('/+').sub('/', result)

    def appdb(self):
        ''' Return the complete path to the db file.'''
        if self.appdir():
            result = self.appdir() + '/' + self.dbfile
            return re.compile('/+').sub('/', result)

    def list_locations(self):
        ''' List all available db files.'''

        OUT.debug('Retrieving hierarchy locations', 6)

        dbpath = self.appdb()

        if dbpath and os.path.isfile(dbpath):
            return {dbpath : [ self.category, self.pn, self.pvr]}

        if dbpath and not os.path.isfile(dbpath):
            OUT.debug('Package "' + self.package_name()
                      + '" not listed in the hierarchy (file "'
                      + dbpath + ' is missing)!', 8)
            return {}

        locations = {}
        packages  = []

        if self.pn:
            packages.append(os.path.join(self.root, self.pn))
            if self.category:
                packages.append(os.path.join(self.root, self.category, self.pn))
        else:
            packages.extend(os.path.join(self.root, m) for m in os.listdir(self.root))
            for i in packages:
                if os.path.isdir(i):
                    packages.extend(os.path.join(i,m) for m in os.listdir(i))

        for i in packages:

            OUT.debug('Checking package', 8)

            if os.path.isdir(i):

                OUT.debug('Checking version', 8)

                versions = os.listdir(i)

                for j in versions:
                    appdir = os.path.join(i,j)
                    location = os.path.join( appdir, self.dbfile)
                    if (os.path.isdir(appdir) and
                        os.path.isfile(location)):
                            pn = os.path.basename(i)
                            cat = os.path.basename(os.path.split(i)[0])
                            if cat == "webapps":
                                cat = ""
                            locations[location] = [ cat, pn, j ]

        return locations

# ========================================================================
# Handler for /var/db/webapps
# ------------------------------------------------------------------------

class WebappDB(AppHierarchy):
    '''
    The DataBase class handles a file-oriented data base that stores
    information about virtual installs of web applications.
    '''

    def __init__(self,
                 fs_root    = '/',
                 root       = '/var/db/webapps',
                 category   = '',
                 package    = '',
                 version    = '',
                 installs   = 'installs',
                 dir_perm   = PermissionMap('0755'),
                 file_perm  = PermissionMap('0600'),
                 verbose    = False,
                 pretend    = False):

        AppHierarchy.__init__(self,
                              fs_root,
                              root,
                              category,
                              package,
                              version,
                              dbfile = installs)

        self.__dir_perm   = dir_perm
        self.__file_perm  = file_perm
        self.__v          = verbose
        self.__p          = pretend

    def remove(self, installdir):
        '''
        Remove a record from the list of virtual installs.

        installdir - the installation directory
        '''
        if not installdir:
            OUT.die('The installation directory must be specified!')

        dbpath = self.appdb()

        if not dbpath:
            OUT.die('No package specified!')

        if not os.access(dbpath, os.R_OK):
            OUT.warn('Unable to read the install database ' + dbpath)
            return

        # Read db file
        fdb = open(dbpath)
        entries = fdb.readlines()
        fdb.close()

        newentries = []
        found = False

        for i in entries:

            j = i.strip().split(' ')

            if j:

                if len(j) != 4:

                    # Remove invalid entry
                    OUT.warn('Invalid line "' + i.strip() + '" remo'
                             'ved from the database file!')
                elif j[3] != installdir:

                    OUT.debug('Keeping entry', 7)

                    # Keep valid entry
                    newentries.append(i.strip())

                elif j[3] == installdir:

                    # Remove entry, indicate found
                    found = True

        if not found:
            OUT.warn('Installation at "' +  installdir + '" could not be '
                     'found in the database file. Check the entries in "'
                     + dbpath + '"!')

        if not self.__p:
            installs = open(dbpath, 'w')
            installs.write('\n'.join(newentries) + '\n')
            installs.close()
            if not self.has_installs():
                os.unlink(dbpath)
        else:
            OUT.info('Pretended to remove installation ' + installdir)
            OUT.info('Final DB content:\n' + '\n'.join(newentries) + '\n')

    def add(self, installdir, user, group):
        '''
        Add a record to the list of virtual installs.

        installdir - the installation directory
        '''

        if not installdir:
            OUT.die('The installation directory must be specified!')

        if not str(user):
            OUT.die('Please specify a valid user!')

        if not str(group):
            OUT.die('Please specify a valid group!')

        OUT.debug('Adding install record', 6)

        dbpath = self.appdb()

        if not dbpath:
            OUT.die('No package specified!')

        if not self.__p and not os.path.isdir(os.path.dirname(dbpath)):
            os.makedirs(os.path.dirname(dbpath), self.__dir_perm(0o755))

        fd = None

        if not self.__p:
            fd = os.open(dbpath,
                         os.O_WRONLY | os.O_APPEND | os.O_CREAT,
                         self.__file_perm(0o600))

        entry = str(int(time.time())) + ' ' + str(user) + ' ' + str(group)\
            + ' ' + installdir + '\n'

        OUT.debug('New record', 7)

        if not self.__p:
            os.write(fd, (entry).encode('utf-8'))
            os.close(fd)
        else:
            OUT.info('Pretended to append installation ' + installdir)
            OUT.info('Entry:\n' + entry)


    def read_db(self):
        '''
        Returns the db content.
        '''

        files = self.list_locations()

        if not files:
            return {}

        result = {}

        for j in list(files.keys()):

            if files[j][0]:
                p = files[j][0] + '/' + files[j][1] + '-' + files[j][2]
            else:
                p = files[j][1] + '-' + files[j][2]

            add = []

            installs = open(j).readlines()

            for i in installs:
                if len(i.split(' ')) == 4:
                    add.append(i.split(' '))

            if add:
                result[p] = add

        return result

    def prune_database(self, action):
        '''
        Prunes the installs files to ensure no webapp
        is incorrectly listed as installed.
        '''

        loc = self.read_db()
        
        if not loc and self.__v:
            OUT.die('No virtual installs found!')

        files = self.list_locations()
        keys = sorted(loc)

        if action != 'clean':
            OUT.warn('This is a list of all outdated entries that would be removed: ')
        for j in keys:
            for i in loc[j]:
                appdir = i[3].strip()
                # We check to see if the webapp is installed.
                if not os.path.exists(appdir+'/.webapp-'+j):
                    if self.__v:
                       OUT.warn('No .webapp file found in dir: ')
                       OUT.warn(appdir)
                       OUT.warn('Assuming webapp is no longer installed.')
                       OUT.warn('Pruning entry from database.')
                    if action == 'clean':
                        for installs in list(files.keys()):
                            contents = open(installs).readlines()
                            new_entries = ''
                            for entry in contents:
                                # Grab all the other entries but the one that
                                # isn't installed.
                                if not re.search('.* ' + appdir +'\\n', entry):
                                    new_entries += entry
                            f = open(installs, 'w')
                            f.write(new_entries)
                            f.close()
                    else:
                        OUT.warn(appdir)

    def has_installs(self):
        ''' Return True in case there are any virtual install locations 
        listed in the db file '''
        if self.read_db():
            return True
        return False

    def listinstalls(self):
        '''
        Outputs a list of what has been installed so far.
        '''

        loc = self.read_db()

        if not loc and self.__v:
            OUT.die('No virtual installs found!')

        keys = sorted(loc)

        for j in keys:
            # The verbose output is meant to be readable for the user
            if self.__v:
                OUT.info('Installs for ' + '-'.join(j.split('/')), 4)

            for i in loc[j]:
                if self.__v:
                    # The verbose output is meant to be readable for
                    # the user
                    OUT.info('  ' + i[3].strip(), 1)
                else:
                    # This is a simplified form for the webapp.eclass
                    OUT.info(i[3].strip(), 1)

# ========================================================================
# Handler for /usr/share/webapps
# ------------------------------------------------------------------------

class WebappSource(AppHierarchy):
    '''
    The WebappSource class handles a web application hierarchy under
    /usr/share/webapps.
    '''

    def __init__(self,
                 fs_root    = '/',
                 root       = '/usr/share/webapps',
                 category   = '',
                 package    = '',
                 version    = '',
                 installed  = 'installed_by_webapp_eclass',
                 pm         = ''):

        AppHierarchy.__init__(self,
                              fs_root,
                              root,
                              category,
                              package,
                              version,
                              dbfile = installed)

        self.__types = None
        self.pm = pm

        # Ignore specific files from the install location
        self.ignore = []

    def read(self,
             config_owned  = 'config-files',
             server_owned  = 'server-owned-files',
             virtual_files = 'virtual',
             default_dirs  = 'default-owned'):
        '''
        Initialize the type cache.
        '''
        import WebappConfig.filetype

        server_files = []
        config_files = []

        if os.access(self.appdir() + '/' + config_owned, os.R_OK):
            flist = open(self.appdir() + '/' + config_owned)
            config_files = flist.readlines()

            OUT.debug('Identified config-protected files.', 7)

            flist.close()

        if os.access(self.appdir() + '/' + server_owned, os.R_OK):
            flist = open(self.appdir() + '/' + server_owned)
            server_files = flist.readlines()

            OUT.debug('Identified server-owned files.', 7)

            flist.close()

        self.__types = WebappConfig.filetype.FileType(config_files,
                                                      server_files,
                                                      virtual_files,
                                                      default_dirs)

    def filetype(self, filename):
        ''' Determine filetype for the given file.'''
        if self.__types:

            OUT.debug('Returning file type', 7)

            return self.__types.filetype(filename)

    def dirtype(self, directory):
        ''' Determine filetype for the given directory.'''
        if self.__types:

            OUT.debug('Returning directory type', 7)

            return self.__types.dirtype(directory)

    def source_exists(self, directory):
        '''
        Checks if the specified source directory exists within the
        application directory.
        '''
        if self.appdir() and os.path.isdir(self.appdir()
                                            + '/' + directory):
            return True
        return False

    def get_source_directories(self, directory):
        '''
        Lists the directories provided by the source directory
        'directory'
        '''
        dirs = []

        if self.source_exists(directory):
            source_dir = self.appdir() + '/' + directory
            dir_entries = os.listdir(source_dir)
            for i in dir_entries:
                if (not os.path.islink(source_dir + '/' + i)
                    and os.path.isdir(source_dir + '/' + i)):
                    dirs.append(i)

        # Support for ignoring entries. Currently only needed
        # to enable doctests in the subversion repository
        if self.ignore:
            dirs = [i for i in  dirs
                    if not i in self.ignore]

        dirs.sort()

        return dirs

    def get_source_files(self, directory):
        '''
        Lists the files provided by the source directory
        'directory'
        '''

        files = []

        if self.source_exists(directory):
            source_dir = self.appdir() + '/' + directory
            dir_entries = os.listdir(source_dir)
            for i in dir_entries:
                if (os.path.isfile(source_dir + '/' + i)
                    or os.path.islink(source_dir + '/' + i)):
                    files.append(i)

        # Support for ignoring files. Currently only needed
        # to enable doctests in the subversion repository
        if self.ignore:
            files = [i for i in  files
                    if not i in self.ignore]

        files.sort()

        return files

    def listunused(self, db):
        '''
        Outputs a list of what has not been installed so far
        '''

        packages = self.list_locations()

        if not packages:
            OUT.die('No packages found!')

        keys = sorted(packages)

        OUT.debug('Check for unused web applications', 7)

        for i in keys:

            db.set_category(packages[i][0])
            db.set_package (packages[i][1])
            db.set_version (packages[i][2])

            if not db.has_installs():
                if packages[i][0]:
                    OUT.notice(packages[i][0] + '/' + packages[i][1] + '-' + packages[i][2])
                else:
                    OUT.notice(packages[i][1] + '-' + packages[i][2])


    def packageavail(self):
        '''
        Check to see whether the given package has been installed or not.

        These checks are carried out by using wrapper.py to facilitate
        distribution independant handling of the task.

        Outputs:
            0       - on success
            1       - package not found
            2       - no package to find
            3       - package isn't webapp-config compatible          '
        '''

        OUT.debug('Verifying package ' + self.package_name(), 6)

        # package_installed() does not handle "/PN" correctly
        package = self.pn

        if self.category:
            package = self.category + '/' + self.pn

        # not using self.package_name() here as we don't need pvr
            return 1

        # unfortunately, just because a package has been installed, it
        # doesn't mean that the package itself is webapp-compatible
        #
        # we need to check that the package has an entry in the
        # application repository

        if not self.appdb():
            return 3
        else:
            return 0

    def reportpackageavail(self):
        '''
        This is a simple wrapper around packageavail() that outputs
        user-friendly error messages if an error occurs

        Cannot test the rest, do not want to die.
        '''

        OUT.info('Do we have ' + self.package_name() + ' available?')

        available = self.packageavail()

        if available == 0:
            OUT.info('  Yes, we do')
        if available == 1:
            OUT.die('  Please emerge ' + self.package_name() + ' first.')
        if available == 3:
            OUT.die('  ' + self.package_name() + ' is not compatible with '
                    'webapp-config.\nIf it should be, report this at '
                    + wrapper.bugs_link)