minor updates
[tests.git] / qaapi / qa / Config.py
1 import xmlrpclib
2 import os
3 import sys
4 import re
5 import socket
6 import utils
7 import copy
8 from logger import logfile, Logfile
9 from Table import Table
10 from PLCs import PLC, PLCs
11 from Sites import Site, Sites   
12 from Nodes import Node, Nodes
13 from Slices import Slice, Slices
14 from Persons import Person, Persons     
15 from TestScripts import TestScript
16
17 path = os.path.dirname(os.path.abspath(__file__))
18
19 class Config:
20
21     path = os.path.dirname(os.path.abspath(__file__))
22     tests_path = path + os.sep + 'tests' + os.sep
23     node_tests_path = tests_path + os.sep + 'node' + os.sep
24     slice_tests_path = tests_path + os.sep + 'slice' + os.sep   
25     vserver_scripts_path = path + os.sep + 'vserver' + os.sep
26     
27     def update_api(self, plc = None):
28         # Set up API acccess
29         # If plc is specified, find its configuration
30         # and use its API
31         if plc is not None:
32             protocol, host, path, port  = 'http', plc['host'], plc['api_path'], plc['port']
33             if port in ['443']:
34                 protocol = 'https'
35             api_server = "%(protocol)s://%(host)s:%(port)s/%(path)s" % locals()
36             self.api = xmlrpclib.Server(api_server, allow_none = 1)
37             self.api_type = 'xmlrpc'    
38         else:
39
40             # Try importing the API shell for direct api access.
41             # If that fails fall back to using xmlrpm
42             try:
43                 sys.path.append('/usr/share/plc_api')
44                 from PLC.Shell import Shell
45                 shell = Shell(globals = globals())
46             
47                 # test it
48                 shell.GetRoles()
49                 self.api = shell
50                 self.api_type = 'direct'
51             except:
52                 self.api = xmlrpclib.Server('https://%s/PLCAPI/' % self.PLC_API_HOST, allow_none = 1)
53                 self.api_type = 'xmlrpc'
54
55     def __init__(self, config_file = path+os.sep+'qa_config', logdir = "/var/log"):
56         # Load config file
57         try:
58             execfile(config_file, self.__dict__)
59         except:
60             raise "Could not find system config in %s" % config_file
61         
62         self.logdir = logdir    
63         log_filename = logdir + os.sep + "qaapi.log"
64         self.update_logfile(log_filename)
65         self.auth = {}
66         self.auth['Username'] = self.PLC_ROOT_USER
67         self.auth['AuthString'] = self.PLC_ROOT_PASSWORD
68         self.auth['AuthMethod'] = 'password'
69         self.verbose = self.VERBOSE
70
71         attributes = ['plcs', 'sites', 'slices', 'nodes', 'persons', 'nodegroups']
72         for attribute in attributes:
73             setattr(self, attribute, [])        
74         
75         # try setting hostname and ip
76         self.hostname = socket.gethostname()
77         try:
78             command = "/sbin/ifconfig eth0 | grep -v inet6 | grep inet | awk '{print$2;}'"
79             (status, output) = utils.commands(command, logfile = self.logfile)            
80             self.ip = re.findall(r'[0-9\.]+', output)[0]
81         except:
82             self.ip = '127.0.0.1'
83         
84         api_host = self.__dict__.get("PLC_API_HOST",self.ip)
85         self.PLC_API_HOST=api_host
86
87         self.update_api()
88
89         # Load list of node tests
90         valid_node_test_files = lambda name: not name.startswith('__init__') \
91                                              and not name.endswith('pyc')
92         node_test_files = os.listdir(self.node_tests_path)
93         self.node_test_files = filter(valid_node_test_files, node_test_files) 
94
95     def update_logfile(self, filename):
96         self.logfile = Logfile(filename)
97         filename_parts = self.logfile.filename.split(os.sep)
98         self.logdir = os.sep + os.sep.join(filename_parts[:-1]) + os.sep
99
100     def get_plc(self, plc_name):
101         plc = PLC(self)
102         if hasattr(self, 'plcs')  and plc_name in self.plcs.keys():
103             plc.update(self.plcs[plc_name])
104             plc.update_api()
105         return plc
106
107     def get_node(self, hostname):
108         node = Node(self)
109         if hasattr(self, 'nodes') and hostname in self.nodes.keys():
110             node.update(self.nodes[hostname])
111             node.__init_logfile__()
112         return node                     
113
114     def get_node_test(self, testscript):
115         script = TestScript({'name': testscript})
116         if hasattr(self, 'node_tests') and testscript in self.node_tests.keys():
117             script.update(self.node_tests[testscript])
118         return script
119
120     def get_slice_test(self, testscript):
121         script = TestScript()
122         if hasattr(self, 'slice_tests') and testscript in self.slice_tests.keys():
123             script.update(self.slice_tests[testscript])
124         return script  
125          
126     
127     def load(self, conffile):
128         
129         confdata = {}
130         try: execfile(conffile, confdata)
131         except: raise 
132
133         from Nodes import Nodes
134         from PLCs import PLCs   
135         loadables = ['plcs', 'sites', 'nodes', 'nodegroups', 'slices', 'persons']
136         config = Config(logdir = self.logdir)
137         for element in confdata.keys():
138             if element in ['plcs']:
139                 setattr(self, element, PLCs(config, confdata[element]).dict('name'))
140             elif element in ['nodes']:
141                 setattr(self, element, Nodes(config, confdata[element]).dict('hostname'))
142             elif element in ['nodegroups']:
143                         setattr(self, element, Table(confdata[element]).dict('name'))   
144             elif element in ['sites']:
145                 setattr(self, element, Sites(confdata[element]).dict('login_base'))
146             elif element in ['slices']:
147                 setattr(self, element, Slices(confdata[element]).dict('name'))
148             elif element in ['persons']:
149                 setattr(self, element, Persons(confdata[element]).dict('email'))
150             elif element in ['node_tests']:
151                 setattr(self, element, TestScripts(confdata[element]).dict('name')) 
152             elif element in ['slice_tests']:
153                 setattr(self, element, TestScript(confdata[element]).dict('name'))
154
155     def archive_scripts(self, prefix):
156         valid_prefix = ['slice', 'node'] 
157         if prefix not in valid_prefix:
158             raise "Error. Invalid prefix %s. Must be in %s" %  (prefix, valid_prefix)
159
160         scripts_dir = self.path + os.sep + 'tests' +os.sep + prefix + os.sep
161         workdir = '/tmp' + os.sep       
162         archive_path = workdir + os.sep + prefix + os.sep
163         archive_filename = prefix + ".tar.gz"
164   
165         if self.verbose:
166             utils.header("Creating/Updating %s archive %s" % (prefix, archive_path + archive_filename), logfile = self.logfile)
167         utils.commands("mkdir -p %(archive_path)s" % locals(), logfile = self.logfile)  
168         utils.commands("cp -Rf %(scripts_dir)s* %(archive_path)s" % locals(), logfile = self.logfile)
169         tar_cmd = "cd %(workdir)s && tar -czf %(workdir)s/%(archive_filename)s %(prefix)s" % locals() 
170         utils.commands(tar_cmd, logfile = self.logfile)
171         return (archive_filename, workdir+archive_filename) 
172
173     def archive_slice_tests(self): 
174         return self.archive_scripts('slice')
175     
176     def archive_node_tests(self):
177         return self.archive_scripts('node')