- merge from PlanetLab Europe
[plcapi.git] / plctest / TestSite.py
1 import os
2 import sys
3 import datetime
4 import time
5 import TestConfig
6 import xmlrpclib
7
8 class TestSite:
9
10     def __init__ (self,test_plc,site_spec):
11         self.test_plc=test_plc
12         self.site_spec=site_spec
13         self.timset=time.strftime("%H:%M:%S", time.localtime())
14         
15     def create_site (self):
16         try:
17             print self.test_plc.auth_root()
18             self.site_id = self.test_plc.server.AddSite(self.test_plc.auth_root(),
19                                                         self.site_spec['site_fields'])
20             self.test_plc.server.AddSiteAddress(self.test_plc.auth_root(),self.site_id,
21                                        self.site_spec['site_address'])
22             
23             return self.site_id
24         except Exception, e:
25             print str(e)
26             
27     def site_id(self):
28         return self.site_id()
29
30     def create_user (self, user_spec):
31         
32         try:
33             i=0
34             print '========>Adding user at '+self.timset+ ': ',user_spec
35             self.person_id=self.test_plc.server.AddPerson(self.test_plc.auth_root(),
36                                                           user_spec)
37             self.test_plc.server.UpdatePerson(self.test_plc.auth_root(),
38                                               self.person_id,{'enabled': True})
39             
40             for i in range(0, len(user_spec['roles']) ):
41                 self.test_plc.server.AddRoleToPerson(self.test_plc.auth_root(),
42                                                      user_spec['roles'][i],
43                                                      user_spec['email'])
44                 i=i+1
45                 
46             self.test_plc.server.AddPersonToSite(self.test_plc.auth_root(),
47                                                  user_spec['email'],
48                                                  self.site_spec['site_fields']['login_base'])
49             
50         except Exception,e:
51             print str(e)
52             
53        
54     def enable_user (self, user_spec):
55         try:
56             persones=self.test_plc.server.GetPersons(self.test_plc.auth_root())
57             for person in persones:
58                 if (person['enabled']!="True"):
59                     self.test_plc.server.UpdatePerson(self.test_plc.auth_root(),
60                                                       person['person_id'],
61                                                       {'enabled': True})
62         except Exception,e:
63             print str(e)
64
65
66     def add_key_user(self,user_spec):
67         try:
68             if(user_spec ==self.site_spec['pi_spec']):
69                 self.test_plc.server.AddPersonKey(self.pi_auth(), user_spec['email'], TestConfig.key)
70             elif(user_spec ==self.site_spec['tech_spec']):
71                 self.test_plc.server.AddPersonKey(self.tech_auth(), user_spec['email'], TestConfig.key)
72             elif (user_spec ==self.site_spec['user_spec']):
73                 self.test_plc.server.AddPersonKey(self.user_auth(), user_spec['email'], TestConfig.key)
74             elif (user_spec ==self.site_spec['tech_user_spec']):
75                 self.test_plc.server.AddPersonKey(self.tech_user_auth(), user_spec['email'], TestConfig.key)
76             elif (user_spec ==self.site_spec['pi_tech_spec']):
77                 self.test_plc.server.AddPersonKey(self.pi_tech_auth(), user_spec['email'], TestConfig.key)
78                 
79         except Exception, e:
80             print str(e)
81
82             
83     def anyuser_auth (self,key):
84         return {'Username':self.site_spec[key]['email'],
85                 'AuthMethod':'password',
86                 'AuthString':self.site_spec[key]['password'],
87                 'Role':self.site_spec[key]['roles'][0],
88                 }
89
90     def pi_auth (self):
91         return self.anyuser_auth('pi_spec')
92     def tech_auth (self):
93         return self.anyuser_auth('tech_spec')
94     def user_auth (self):
95         return self.anyuser_auth('user_spec')
96     def tech_user_auth (self):
97         return self.anyuser_auth('tech_user_spec')
98     def pi_tech_auth (self):
99         return self.anyuser_auth('pi_tech_spec')
100     
101     def node_check_status(self,liste_nodes,bool):
102         try:
103             ret_value=True    
104             filter=['boot_state']
105             bt={'boot_state':'boot'}
106             secondes=15
107
108             start_time = datetime.datetime.now() ##geting the current time
109             dead_time=datetime.datetime.now()+ datetime.timedelta(minutes=10)##adding 10minutes
110             
111             start=time.strftime("%H:%M:%S", time.localtime())
112             print "time in the begining  is :",start
113            
114             
115             for l in liste_nodes :
116                 while (bool):
117                     node_status=self.test_plc.server.GetNodes(self.test_plc.auth_root(),
118                                                               l['hostname'], filter)
119                     timset=time.strftime("%H:%M:%S", time.localtime())
120                     print 'the actual status for the node '+l['hostname']+' at '+str(timset)+' is :',node_status
121                     try:
122                         if (node_status[0] == bt):
123                             test_name='\nTest Installation Node hosted: '+l['hostname']
124                             self.test_plc.affiche_results(test_name, 'Successful', '')##printing out the result
125                             break ##for exsiting and renaming virtual file to just installed
126                         
127                         elif ( start_time  <= dead_time ) :
128                             start_time=datetime.datetime.now()+ datetime.timedelta(minutes=2)
129                             time.sleep(secondes)
130                             
131                         else: bool=False
132                     except OSError ,e :
133                         bool=False
134                         str(e)
135                               
136                 if (bool):
137                     print "Node correctly instaled and booted "
138                 else :
139                     print "Node not fully booted "##cheek if configuration file already exist
140                     ret_value=False
141                     test_name='\nTest Installation Node Hosted: ',l['hostname']
142                     self.test_plc.affiche_results(test_name, 'Failure', '')##printing out the result
143                 
144                 
145             
146             end=time.strftime("%H:%M:%S", time.localtime())
147             print "time at the end is :",end  ##converting time to secondes
148             return ret_value
149         except Exception, e:
150             print str(e)
151             print "vmware killed if problems occur  "
152             time.sleep(10)
153             self.kill_all_vmwares()
154             sys.exit(1)
155             
156     def kill_all_vmwares(self):
157         os.system('pgrep vmware | xargs -r kill')
158         os.system('pgrep vmplayer | xargs -r kill ')
159         os.system('pgrep vmware | xargs -r kill -9')
160         os.system('pgrep vmplayer | xargs -r kill -9')
161
162         
163     def run_vmware(self,liste_nodes,display):
164         path=os.path.dirname(sys.argv[0])
165         print path
166         print " kill last vmware before any new  installation  "
167         self.kill_all_vmwares()
168         print 'i will be displayed here========>', display
169         arg='< /dev/null &>/dev/null &'
170         for l in liste_nodes :
171             #os.system('set -x; vmplayer  VirtualFile-%s/My_Virtual_Machine.vmx  %s '%(l['hostname'],arg))
172             os.system('set -x; DISPLAY=%s vmplayer %s/VirtualFile-%s/My_Virtual_Machine.vmx %s '%(display,path,l['hostname'],arg))
173
174     def delete_known_hosts(self):
175         try:
176             file1=open('/root/.ssh/known_hosts','r')
177             file2=open('/root/.ssh/known_hosts_temp','w')
178             while 1:
179                 txt = file1.readline()
180                 if txt=='':
181                     file1.close()
182                     file2.close()
183                     break
184                 if txt[0:4]!='test' :
185                     file2.write(txt)
186             
187                 
188             os.system('mv -f /root/.ssh/known_hosts_temp  /root/.ssh/known_hosts')
189         except Exception, e:
190             print str(e)
191
192
193     def slice_access(self,liste_nodes):
194         try:
195             bool=True
196             bool1=True
197             secondes=15
198             self.delete_known_hosts()
199             start_time = datetime.datetime.now()
200             dead_time=start_time + datetime.timedelta(minutes=3)##adding 3minutes
201             for l in liste_nodes:
202                 timset=time.strftime("%H:%M:%S", time.localtime())
203                 while(bool):
204                     print '=========>Try to Restart the Node Manager on %s at %s:'%(l['hostname'],str(timset))
205                     access=os.system('set -x; ssh -i /etc/planetlab/root_ssh_key.rsa  root@%s service nm restart'%l['hostname'])
206                     if (access==0):
207                         print '=========>Node Manager Restarted on %s at %s:'%(l['hostname'],str(timset))
208                         while(bool1):
209                             print '=========>Try to connect to the %s@%s at %s '%(TestConfig.slice_spec['name'],l['hostname'],str(time.strftime("%H:%M:%S", time.localtime())))
210                             Date=os.system('set -x; ssh -i ~/.ssh/slices.rsa %s@%s echo "The Actual Time here is;" date'%(TestConfig.slice_spec['name'],l['hostname']))
211                             if (Date==0):
212                                 break
213                             elif ( start_time  <= dead_time ) :
214                                 start_time=datetime.datetime.now()+ datetime.timedelta(seconds=30)
215                                 time.sleep(secondes)
216                             else:
217                                 bool1=False
218                         if(bool1):
219                             print '=========>connected to the '+TestConfig.slice_spec['name']+'@'+l['hostname']+'--->'
220                         else:
221                             print '=========>access to one slice is denied but last chance'
222                             print '=========>Retry to Restart the Node Manager on %s at %s:'%(l['hostname'],str(timset))
223                             access=os.system('set -x; ssh -i /etc/planetlab/root_ssh_key.rsa  root@%s service nm restart'%l['hostname'])
224                             if (access==0):
225                                 print '=========>Retry to connect to the %s@%s at %s '%(TestConfig.slice_spec['name'],l['hostname'],str(time.strftime("%H:%M:%S", time.localtime())))
226                                 Date=os.system('set -x; ssh -i ~/.ssh/slices.rsa %s@%s echo "The Actual Time here is;" date'%(TestConfig.slice_spec['name'],l['hostname']))
227                                 if (Date==0):
228                                     print '=========>connected to the '+TestConfig.slice_spec['name']+'@'+l['hostname']+'--->'
229                                 else:
230                                     print '=========>the Access is finaly denied'
231                                     sys.exit(1)
232                             else :"=========>Last try failed"
233                         break
234                     elif ( start_time  <= dead_time ) :
235                         start_time=datetime.datetime.now()+ datetime.timedelta(minutes=1)
236                         time.sleep(secondes)
237                     else:
238                         bool=False
239                                 
240                 if (not bool):
241                     print 'Node manager problems'
242                     sys.exit(1)
243                         
244                     
245         except Exception, e:
246             print str(e)
247             sys.exit(1)
248