source: opsi/server/dass-opsi-tools/usr/bin/opsiclient @ 1114

Last change on this file since 1114 was 1114, checked in by joergs, 11 years ago

fix: for python 2.6 (sles11)

  • Property svn:executable set to *
File size: 14.4 KB
Line 
1#!/usr/bin/env python
2
3# -*- coding: utf-8 -*-
4
5"""ospi-client: performs operation for opsi clients on opsi server via JSON-RPC."""
6
7__author__ = "Joerg Steffens"
8__copyright__ = "Copyright 2012, dass IT GmbH"
9__license__ = "GPL"
10__version__ = "1.1"
11__email__ = "joerg.steffens@dass-it.de"
12
13#self.command("opsi-admin -d method host_createOpsiClient "+ \
14        #computername + " null " + "\\'"+description+"\\'" + \
15        #" \\'created by dassadmin\\' " + mac_address + " " + \
16        #ip_address)
17#self.command("opsi-admin -d method configState_create clientconfig.depot.id " + \
18        #computername + " " + depotName)                       
19                       
20import argparse
21import jsonrpc
22import logging
23import os
24from pprint import pprint
25import time
26
27UrlJsonRpc="https://<username>:<password>@opsi:4447/rpc"
28
29HelpEpilog="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."
30
31class OpsiRpc:
32
33    UrlJsonRpcDefault="https://opsi:4447/rpc"
34   
35    ProductAttributesCopy = ['actionRequest','actionResult','installationStatus','packageVersion','productVersion']
36   
37    def __init__(self, urlJsonRpc = UrlJsonRpcDefault, debug=False ):
38        self.logger=logging.getLogger(__name__)       
39        self.debug=debug
40        self.urlJsonRpc=urlJsonRpc
41        self.rpc=jsonrpc.ServiceProxy(self.urlJsonRpc)
42        self.logger.debug( "initialized: " + self.urlJsonRpc )
43
44       
45    def list(self):
46        print( "\n".join( self.rpc.getClientIds_list() ) )
47        return True
48
49       
50    def getClientsWithProduct( self, product ):
51        return self.rpc.productOnClient_getObjects( [], { "productId": product, "installationStatus": "installed" } )
52
53
54    def listClients( self, product ):
55        if product:
56            for client in self.getClientsWithProduct( product ):
57                print client['clientId']
58        else:
59            return self.list()
60        return True
61       
62       
63    def exists(self, src):
64        return len( self.rpc.host_getObjects( [], {"id":src} ) ) == 1
65       
66    def info(self, src):
67        if not self.exists( src ):
68            print "failed: opsi client", src, "does not exist"
69            return False
70        print src + ":"
71        host = self.rpc.host_getHashes( [], {"id":src} )[0]
72        print "  IP:", host["ipAddress"]
73        print "  MAC:", host["hardwareAddress"]
74        print "  inventory:", host["inventoryNumber"]
75        print "  last seen:", host["lastSeen"]
76        print "  notes:", host["notes"]
77       
78        print "  products:"
79        products = self.getProductOnClient( src, [] )
80        for i in products:
81            print "    " + i['productId'] + ":"
82            print "      " + i['installationStatus'], "(",
83            if i['actionRequest']:
84                print i['actionRequest'],
85                if i['actionProgress']:
86                    print i['actionProgress'],
87            print ")"
88            print "      ",
89            pprint( i, indent=8 )
90        return True
91
92    def clean(self, src):
93        if not self.exists( src ):
94            return False
95        products = self.rpc.productOnClient_getObjects( [], { 'clientId': src } )
96        self.rpc.productOnClient_deleteObjects( products )
97
98        products = self.rpc.productPropertyState_getObjects( [], { 'objectId': src } )
99        self.rpc.productPropertyState_deleteObjects( products )
100       
101        if self.debug:
102            pprint( self.getProductOnClient( src ) )
103        return True
104       
105    def createClient(self, name, opsiHostKey, description, notes, hardwareAddress, ipAddress):
106        self.rpc.host_createOpsiClient( name, opsiHostKey, description, notes, hardwareAddress, ipAddress )
107
108    def clientSetDepot(self, name, depot):
109        self.rpc.configState_create( "clientconfig.depot.id", name, depot )       
110
111    def copyClient( self, src, dst, ipAddress = None, hardwareAddress = None, depot = None, description = "", copyProperties = True ):
112   
113        print "create/update", dst, "from template", src + ":",
114        obj = {
115          "id" : dst,
116          "type" : "OpsiClient",
117          "notes" : "copy of " + src,
118          "description" : description,
119          #"inventoryNumber" : "",
120        }
121        if hardwareAddress:
122            obj['hardwareAddress'] = hardwareAddress
123        if ipAddress:
124            obj['ipAddress'] = ipAddress
125
126        if self.exists( dst ):
127            self.rpc.host_updateObject(obj)
128        else:
129            self.rpc.host_insertObject(obj)
130           
131        if depot:
132            self.clientSetDepot(dst,depot)
133           
134        if self.debug:
135            pprint( self.getProductOnClient( src ) )
136        self.copyProductOnClient( src, dst )
137        # TODO:
138        #  copy product properties:
139        #  opsiCallClientBaculaProperties=[ "method", "getProductProperties_hash", "bacula" ]
140        if copyProperties:
141            if self.debug:
142                print "copy product properties"
143            self.copyProductPropertyState( src, dst )
144        print "done"
145        return True
146
147
148
149    def getProductOnClient( self, client, attributes = ProductAttributesCopy ):
150        return self.rpc.productOnClient_getHashes( [], { 'clientId': client } )
151
152
153
154    def copyProductOnClient( self, src, dst, attributes = ProductAttributesCopy ):
155        products_src = self.rpc.productOnClient_getHashes( attributes, { 'clientId': src } )
156        products_dst = []
157        for i in products_src:
158            if self.debug:
159                print i['productId']
160                pprint( i )
161            i['clientId'] = dst
162            products_dst.append(i)
163        self.rpc.productOnClient_createObjects( products_dst )
164        if self.debug:
165            pprint( self.getProductOnClient( dst ) )
166
167    def getProductPropertyState( self, client, attributes = [] ):
168        return self.rpc.productPropertyState_getHashes( [], { 'objectId': client } )
169                       
170    def copyProductPropertyState( self, src, dst, attributes = [] ):
171        productProperties_src = self.getProductPropertyState( src, attributes )
172        productProperties_dst = []
173        for i in productProperties_src:
174            if self.debug:
175                print i['productId'], "-", i["propertyId"] + ": ",
176                pprint(i["values"])
177                #pprint( i )
178            i['objectId'] = dst
179            productProperties_dst.append(i)
180        self.rpc.productPropertyState_createObjects( productProperties_dst )
181        if self.debug:
182            pprint( self.getProductPropertyState( dst ) )
183
184
185    def getClientProductProperty( self, client, product ):
186        return self.rpc.getProductProperties_hash( product, [ client ] )
187
188    def write_client_conf( self, fd, client, properties ):
189        #Client {
190        #Name = ting-fd
191        #Address = ting.dass-it
192        #FDPort = 9102
193        #Catalog = MyCatalog
194        #Password = "D5w2V5w6B8a9H5Z"
195        #File Retention = 6 months
196        #Job Retention = 6 months
197        #AutoPrune = yes
198        #}
199        params = [ "FDPort", "FileRetention", "JobRetention", "AutoPrune" ]
200        fd.write( "Client {\n" )
201        fd.write( '  Name     = "' + properties['filedaemon_full_name'] + '"' + "\n" )
202        fd.write( '  Address  = "' + client['clientId'] + '"' + "\n" )
203        # ipAddress: method host_getObjects [] '{"id":client['clientId']}'
204        #print "  # Address =", ipAddress
205        fd.write( '  Password = "' + properties['filedaemon_full_password'] + '"' + "\n" )
206        try:
207            catalog = properties['catalog']
208        except KeyError:
209            catalog = "MyCatalog"
210        fd.write( '  Catalog  = "' + catalog + '"' + "\n" )
211        for i in params:
212            try:
213                fd.write( '  ' + i + ' = "' + properties[i.lower()] + '"' + "\n" )
214            except KeyError:
215                fd.write( '  # ' + i + " = \n" )
216        fd.write( "}\n")
217        fd.write( "\n" )
218       
219       
220
221
222    def write_job_conf( self, fd, client, properties ):
223        #Job {
224        #FileSet = "tingfileset"
225        #Name = "ting"
226        #Client = ting-fd
227        #JobDefs = "LaptopJob"
228        ## Write Bootstrap = "/var/lib/bacula/ting.bsr"
229        #}
230        params = [ "Fileset", "JobDefs" ]
231        fd.write( "Job {" + "\n" )
232        fd.write( '  Name    = "' + client['clientId'] + '-job"' + "\n" )
233        fd.write( '  Client  = "' + properties['filedaemon_full_name'] + '"' + "\n" )
234        for i in params:
235            fd.write( "  " )
236            try:
237                if not properties[i.lower()]:
238                    fd.write( "# " )
239                fd.write( i + ' = "' + properties[i.lower()] + '"' + "\n" )
240            except KeyError:
241                fd.write( "# " + i + " = " + "\n" )
242        fd.write( "}" + "\n" )
243        fd.write( "\n" )
244
245
246    def write_config_file_header( self, fd ):
247        try:       
248            fd.write( "#\n" )
249            fd.write( "# automatically generated at {0}\n".format( time.asctime() ) )
250            fd.write( "#\n\n" )
251        except BaseException as e:       
252            self.logger.exception( "failed to create files" )
253            return False
254        return True
255           
256
257    def createBaculaConfigFiles( self ):
258        clientsWithBacula=self.getClientsWithProduct( "bacula" )
259        if clientsWithBacula:
260            try:
261                file_opsi_clients = open('opsi-clients-generated.conf', 'w')
262                self.write_config_file_header( file_opsi_clients )
263               
264                file_opsi_jobs = open('opsi-jobs-generated.conf', 'w')
265                self.write_config_file_header( file_opsi_jobs )
266            except BaseException as e:       
267                self.logger.exception( "failed to create files" )
268                return False
269            for client in clientsWithBacula:
270                clientId = client['clientId']               
271                try:
272                    clientBaculaProperties=self.getClientProductProperty( clientId, "bacula" )
273                except ValueError as e:
274                    self.logger.warn( "%s: no valid information found: %s" %(clientId, e) )
275                else:
276                    if clientBaculaProperties:
277                        #pprint( clientBaculaProperties )
278                        self.write_client_conf( file_opsi_clients, client, clientBaculaProperties )
279                        self.write_job_conf( file_opsi_jobs, client, clientBaculaProperties )
280                        self.logger.info( "%s: OK" % clientId )
281                    else:
282                        self.logger.warn( "%s: failed: no product properties defined" %(clientId) )
283            return True
284
285
286
287if __name__ == '__main__':
288    logging.basicConfig(format='%(message)s')
289    logger = logging.getLogger(__name__)
290    logger.setLevel(logging.INFO)
291   
292    parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.', epilog=HelpEpilog )
293
294    parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
295
296    parser_url = parser.add_mutually_exclusive_group(required=True)
297    parser_url.add_argument( '--url', help="OPSI Server JSON-RPC url, in following format: " + UrlJsonRpc )
298   
299    parser_url.add_argument( '--server', help="OPSI Server (instead of URL)" )
300    username_default=os.getlogin()
301   
302    parser.add_argument( '--username', help="username (instead of URL), default: " + username_default, default=username_default )
303    parser.add_argument( '--password', help="password (instead of URL)" )
304   
305    subparsers = parser.add_subparsers(title='subcommands',
306        description='valid subcommands',
307        help='additional help',
308        dest='subcommand' )
309
310    parser_clean = subparsers.add_parser('clean', help='remove all product states from a opsi client' )
311    parser_clean.add_argument( 'src', help="source opsi client to clean" )
312               
313    parser_copy = subparsers.add_parser('copy', help='copy/create a opsi client from a template opsi client')   
314    parser_copy.add_argument( 'src', help="source/template opsi client" )
315    parser_copy.add_argument( 'dst', help="opsi client to be created" )
316    parser_copy.add_argument( '--ip', help="IP address of the new opsi client" )
317    parser_copy.add_argument( '--mac', help="MAC address of the new opsi client" )
318    parser_copy.add_argument( '--depot', help="depot server the new opsi client should be located" )
319    #parser_copy.add_argument( '--no-properties', action='store_false', help="don't copy product properties" )
320       
321    parser_createBaculaConfigFiles = subparsers.add_parser('createBaculaConfigFiles', help='create Bacula config files for all clients that have bacula installed')
322
323    parser_exists = subparsers.add_parser('exists', help='check, if a opsi clients exists' )
324    parser_exists.add_argument( 'src', help="source opsi client" )
325   
326    #parser_list = subparsers.add_parser('list', help='list all opsi clients' )
327   
328    parser_listClients = subparsers.add_parser('listClients', help='list opsi clients')
329    parser_listClients.add_argument( '--product', help="only list clients, that have product installed" )
330   
331    parser_info = subparsers.add_parser('info', help='print information about a opsi client' )
332    parser_info.add_argument( 'src', help="opsi client" )
333   
334    args = parser.parse_args()
335   
336    if args.debug:
337        logger.setLevel(logging.DEBUG)
338
339    url=args.url
340    if (not url):
341        if args.server:
342            account=""
343            if args.username and args.password:
344                account=args.username + ":" + args.password + "@"
345            elif args.username:
346                account=args.username + "@"
347            url="https://" + account + args.server + ":4447/rpc"
348        else:
349            parser.error( "argument --url is required" )
350       
351    opsi=OpsiRpc( url, args.debug )
352   
353    result = True
354
355    if args.subcommand == "clean":
356        result = opsi.clean( args.src )
357    elif args.subcommand == "copy":
358        result = opsi.copyClient( args.src, args.dst, args.ip, args.mac, args.depot )
359    elif args.subcommand == "createBaculaConfigFiles":
360        result = opsi.createBaculaConfigFiles()
361    elif args.subcommand == "exists":
362        result = opsi.exists( args.src )       
363    elif args.subcommand == "list":
364        result = opsi.list()
365    elif args.subcommand == "listClients":         
366        result = opsi.listClients( args.product )       
367    elif args.subcommand == "info":
368        result = opsi.info( args.src )       
369    else:
370        print "not yet implemented"
371
372    if args.debug: print result   
373       
374    if result:
375        exit(0)
376    else:
377        exit(1)
Note: See TracBrowser for help on using the repository browser.