Ignore:
Timestamp:
Feb 28, 2018, 6:41:10 PM (6 years ago)
Author:
joergs
Message:

added createBareosConfigFiles

  • try to allow alternatives to jsonrpc, however tests with jsonrpclib (jsonrpclib_pelix-0.3.1) have not been successful.
  • createBareosConfigFiles
    • replaced createBaculaConfigFiles
    • provide default parameter for JobDefs and FileSet
    • store resulting files to correct location /etc/bareos/bareos-dir.d/*/opsi-*-generated.conf
File:
1 edited

Legend:

Unmodified
Added
Removed
  • opsi/server/dass-opsi-tools/usr/bin/opsiclient

    r1234 r1239  
    88
    99__author__ = "Joerg Steffens"
    10 __copyright__ = "Copyright 2012-2017, dass IT GmbH"
     10__copyright__ = "Copyright 2012-2018, dass IT GmbH"
    1111__license__ = "GPL"
    1212__version__ = "1.2"
     
    2121
    2222import argparse
    23 from datetime import datetime, timedelta
    24 from dateutil import parser as dateparser
    25 import jsonrpc
     23from   datetime import datetime, timedelta
     24from   dateutil import parser as dateparser
    2625import logging
    2726import os
    28 from pprint import pprint, pformat
     27from   pprint import pprint, pformat
    2928import sys
     29import ssl
    3030import time
    3131
     32try:
     33    import jsonrpc
     34except ImportError:
     35    import jsonrpclib
     36
     37
    3238UrlJsonRpc="https://<username>:<password>@opsi:4447/rpc"
    3339
    34 HelpEpilog="WARNING: python-json-rpc is known to have problems with HTTP proxies. In case of problems, make sure, the environment variables http_proxy and/or https_proxy are *not* set."
     40HelpEpilog="WARNING: python-json-rpc is known to have problems with HTTP proxies. In case of problems, make sure, the environment variables http_proxy and/or https_proxy are *not* set. It might also be neccesary to set variable PYTHONHTTPSVERIFY=0"
    3541
    3642class Nrpe:
     
    8389        self.nagios=nagios
    8490        self.urlJsonRpc=urlJsonRpc
    85         self.rpc=jsonrpc.ServiceProxy(self.urlJsonRpc)
     91        if 'jsonrpc' in sys.modules:
     92            self.rpc=jsonrpc.ServiceProxy(self.urlJsonRpc)
     93        else:
     94            self.rpc=jsonrpclib.ServerProxy(self.urlJsonRpc)
    8695        self.logger.debug( "initialized: " + self.urlJsonRpc )
     96        self.logger.debug(dir(self.rpc))
    8797
    8898
    8999    def list(self):
     100        exceptions = []
     101        if 'jsonrpc' in sys.modules:
     102            exceptions = [ jsonrpc.json.JSONDecodeException ]
    90103        try:
    91104            print( "\n".join( self.rpc.getClientIds_list() ) )
    92         except jsonrpc.json.JSONDecodeException as e:
     105        except exceptions as e:
    93106            self.logger.debug( pformat(self.rpc.getClientIds_list()) )
    94107            self.logger.exception( "failed" )
     
    314327
    315328
     329
     330    def write_value_conf(self, fd, key, properties, default=None):
     331        value = None
     332        comment = ''
     333        try:
     334            value = properties[key.lower()]
     335        except KeyError:
     336            pass
     337        if not value and default:
     338            value = default
     339        if not value:
     340            # prevent a None to be written
     341            value = ''
     342            comment = '# '
     343        fd.write('  {}{} = "{}"\n'.format(comment, key, value))
     344
     345
     346
    316347    def write_client_conf( self, fd, client, properties ):
    317348        #Client {
     
    319350        #Address = ting.dass-it
    320351        #FDPort = 9102
     352        #Password = "D5w2V5w6B8a9H5Z"
    321353        #Catalog = MyCatalog
    322         #Password = "D5w2V5w6B8a9H5Z"
    323354        #File Retention = 6 months
    324355        #Job Retention = 6 months
    325356        #AutoPrune = yes
    326357        #}
    327         params = [ "FDPort", "FileRetention", "JobRetention", "AutoPrune" ]
     358        params = [ 'catalog', "FDPort", "FileRetention", "JobRetention", "AutoPrune" ]
    328359        fd.write( "Client {\n" )
    329360        fd.write( '  Name     = "' + properties['filedaemon_full_name'] + '"' + "\n" )
    330         fd.write( '  Address  = "' + client['clientId'] + '"' + "\n" )
     361        fd.write( '  Address  = "' + properties['filedaemon_client_address'] + '"' + "\n" )
    331362        # ipAddress: method host_getObjects [] '{"id":client['clientId']}'
    332363        #print("  # Address =", ipAddress)
    333364        fd.write( '  Password = "' + properties['filedaemon_full_password'] + '"' + "\n" )
    334         try:
    335             catalog = properties['catalog']
    336         except KeyError:
    337             catalog = "MyCatalog"
    338         fd.write( '  Catalog  = "' + catalog + '"' + "\n" )
    339365        for i in params:
    340             try:
    341                 fd.write( '  ' + i + ' = "' + properties[i.lower()] + '"' + "\n" )
    342             except KeyError:
    343                 fd.write( '  # ' + i + " = \n" )
     366            self.write_value_conf(fd, i, properties)
    344367        fd.write( "}\n")
    345368        fd.write( "\n" )
    346369
    347370
    348     def write_job_conf( self, fd, client, properties ):
     371    def write_job_conf(self, fd, client, properties, defaultjobdefs, defaultfileset):
    349372        #Job {
    350373        #FileSet = "tingfileset"
     
    354377        ## Write Bootstrap = "/var/lib/bacula/ting.bsr"
    355378        #}
    356         params = [ "Fileset", "JobDefs" ]
     379        params = [ "JobDefs", "FileSet" ]
    357380        fd.write( "Job {" + "\n" )
    358381        fd.write( '  Name    = "' + client['clientId'] + '-job"' + "\n" )
    359382        fd.write( '  Client  = "' + properties['filedaemon_full_name'] + '"' + "\n" )
    360         for i in params:
    361             fd.write( "  " )
    362             try:
    363                 if not properties[i.lower()]:
    364                     fd.write( "# " )
    365                 fd.write( i + ' = "' + properties[i.lower()] + '"' + "\n" )
    366             except KeyError:
    367                 fd.write( "# " + i + " = " + "\n" )
     383        self.write_value_conf(fd, 'JobDefs', properties, defaultjobdefs)
     384        self.write_value_conf(fd, 'FileSet', properties, defaultfileset)
    368385        fd.write( "}" + "\n" )
    369386        fd.write( "\n" )
     
    381398
    382399
    383     def createBaculaConfigFiles( self ):
    384         clientsWithBacula=self.getClientsWithProduct( "bacula" )
     400
     401    def createBareosConfigFiles(self, defaultjobdefs, defaultfileset):
     402        bareosDirConfigPath = '/etc/bareos/bareos-dir.d/'
     403        clientsWithBacula=self.getClientsWithProduct('winbareos')
    385404        if clientsWithBacula:
    386405            try:
    387                 file_opsi_clients = open('opsi-clients-generated.conf', 'w')
     406                configfile = bareosDirConfigPath + 'client/opsi-clients-generated.conf'
     407                file_opsi_clients = open(configfile, 'w')
    388408                self.write_config_file_header( file_opsi_clients )
    389 
    390                 file_opsi_jobs = open('opsi-jobs-generated.conf', 'w')
     409            except (BaseException, IOError) as e:
     410                self.logger.exception( "failed to create configuration file {}".format(configfile) )
     411                return False
     412
     413            try:
     414                configfile = bareosDirConfigPath + 'job/opsi-jobs-generated.conf'
     415                file_opsi_jobs = open(configfile, 'w')
    391416                self.write_config_file_header( file_opsi_jobs )
    392             except BaseException as e:
    393                 self.logger.exception( "failed to create files" )
     417            except (BaseException, IOError) as e:
     418                self.logger.exception( "failed to create configuration file {}".format(configfile) )
    394419                return False
     420
    395421            for client in clientsWithBacula:
    396422                clientId = client['clientId']
    397423                try:
    398                     clientBaculaProperties=self.getClientProductProperty( clientId, "bacula" )
     424                    clientBaculaProperties=self.getClientProductProperty( clientId, 'winbareos' )
    399425                except ValueError as e:
    400426                    self.logger.warn( "%s: no valid information found: %s" %(clientId, e) )
     
    402428                    if clientBaculaProperties:
    403429                        #pprint( clientBaculaProperties )
    404                         self.write_client_conf( file_opsi_clients, client, clientBaculaProperties )
    405                         self.write_job_conf( file_opsi_jobs, client, clientBaculaProperties )
     430                        self.write_client_conf(file_opsi_clients, client, clientBaculaProperties)
     431                        self.write_job_conf(file_opsi_jobs, client, clientBaculaProperties, defaultjobdefs, defaultfileset)
    406432                        self.logger.info( "%s: OK" % clientId )
    407433                    else:
     
    508534    logger.setLevel(logging.INFO)
    509535   
    510     parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.', epilog=HelpEpilog )
     536    parser = argparse.ArgumentParser(
     537        description='Command line tool for OPSI configuration.',
     538        epilog=HelpEpilog
     539    )
    511540
    512541    parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
     
    538567    #parser_copy.add_argument( '--no-properties', action='store_false', help="don't copy product properties" )
    539568
    540     parser_createBaculaConfigFiles = subparsers.add_parser('createBaculaConfigFiles', help='create Bacula config files for all clients that have bacula installed')
     569    parser_createBareosConfigFiles = subparsers.add_parser(
     570        'createBareosConfigFiles',
     571        help='create Bareos config files for all clients that have winbareos installed',
     572        formatter_class=argparse.ArgumentDefaultsHelpFormatter
     573    )
     574    parser_createBareosConfigFiles.add_argument(
     575        '--defaultjobdefs',
     576        metavar='JobDefs',
     577        default='DefaultJob',
     578        help="use this JobDefs if no other is defined for a client"
     579    )
     580    parser_createBareosConfigFiles.add_argument(
     581        '--defaultfileset',
     582        metavar='FileSet',
     583        help="use this FileSet if no other is defined for a client"
     584    )
    541585
    542586    parser_exists = subparsers.add_parser('exists', help='check, if a opsi clients exists' )
     
    595639        elif args.subcommand == "copy":
    596640            result = opsi.copyClient( args.src, args.dst, args.ip, args.mac, args.depot )
    597         elif args.subcommand == "createBaculaConfigFiles":
    598             result = opsi.createBaculaConfigFiles()
     641        elif args.subcommand == "createBareosConfigFiles":
     642            result = opsi.createBareosConfigFiles(args.defaultjobdefs, args.defaultfileset)
    599643        elif args.subcommand == "exists":
    600644            result = opsi.exists( args.src )
Note: See TracChangeset for help on using the changeset viewer.