- change all occurrences of slices.deleted to slices.is_deleted
[plcapi.git] / TestPeers.py
1 #!/usr/bin/env python
2 ###
3 ##############################
4 ###
5 ### preparation / requirements
6 ###
7 ### two separate instances of myplc
8 ### for now they are located on the same box on lurch
9 ###
10 ### expectations :
11 ### your myplcs should more or less come out of the box, 
12 ### I prefer not to alter the default PLC_ROOT_USER value,
13 ### instead we create a PI account on the site_id=1
14 ###
15 ##############################
16
17 # support reloading without wiping everything off
18 # dunno how to do (defvar plc)
19
20 ## we use indexes 1 and 2 
21 try:
22     dir(plc)
23 except:
24     plc=[None,None,None]
25 ## the server objects
26 try:
27     dir(s)
28 except:
29     s=[None,None,None]
30 ## the authentication objects
31 ## our user
32 try:
33     dir(a)
34 except:
35     a=[None,None,None]
36 ## the builtin root user for bootstrapping
37 try:
38     dir(aa)
39 except:
40     aa=[None,None,None]
41
42 ####################
43 import xmlrpclib
44 import os
45
46 ####################
47 plc1={ 'plcname':'plc1 in federation',
48        'hostname':'lurch.cs.princeton.edu',
49        'url-format':'https://%s:443/PLCAPI/',
50        'builtin_admin_id':'root@localhost.localdomain',
51        'builtin_admin_password':'root',
52        'peer_admin_name':'plc1@planet-lab.org',
53        'peer_admin_password':'peer',
54        'node-format':'n1%02d.plc1.org',
55        'plainname' : 'one',
56        'slice-format' : 's1%02d',
57        }
58 plc2={ 'plcname':'plc2 in federation',
59        'hostname':'planetlab-devbox.inria.fr',
60        'url-format':'https://%s:443/PLCAPI/',
61        'builtin_admin_id':'root@localhost.localdomain',
62        'builtin_admin_password':'root',
63        'peer_admin_name':'plc2@planet-lab.org',
64        'peer_admin_password':'peer',
65        'node-format':'n2%02d.plc2.org',
66        'plainname' : 'two',
67        'slice-format' : 's2%02d',
68        }
69
70 ####################
71 # set initial conditions
72 def define_test (nodes,slices):
73     global number_nodes, number_slices
74     number_nodes=nodes
75     number_slices=slices
76     
77 define_test (nodes=5,slices=3)
78
79 # predefined stuff
80 system_slices_ids = (1,2)
81 def system_slices ():
82     return len(system_slices_ids)
83 # temporary - the myplc I use doesnt know about 'system' yet
84 def system_slivers ():
85 #    return len(system_slices_ids)
86     return 0
87
88 def total_slices ():
89     return number_slices+system_slices()
90 def total_slivers ():
91     return number_slices+system_slivers()
92
93 ####################
94 def peer_index(i):
95     return 3-i
96
97 def plc_name (i):
98     return plc[i]['plcname']
99
100 def site_name (i):
101     return 'site'+str(i)
102
103 def node_name (i,n):
104     return plc[i]['node-format']%n
105
106 def slice_name (i,n):
107     return plc[i]['plainname']+'_'+plc[i]['slice-format']%n
108
109 # to have indexes start at 1
110 def myrange (n):
111     return range (1,n+1,1)
112
113 def message (*args):
114     print "XXXXXXXXXXXXXXXXXXXX",
115     print args
116     
117 ####################
118 def test00_init (args=[1,2]):
119     global plc,s,a,aa
120     ## have you loaded this file already (support for reload)
121     if plc[1]:
122         pass
123     else:
124         plc=[None,plc1,plc2]
125         for i in args:
126             url=plc[i]['url-format']%plc[i]['hostname']
127             plc[i]['url']=url
128             s[i]=xmlrpclib.Server(url)
129             print 'initializing s[%d]'%i,url
130             aa[i]={'Username':plc[i]['builtin_admin_id'],
131                    'AuthMethod':'password',
132                    'AuthString':plc[i]['builtin_admin_password'],
133                    'Role':'admin'}
134             print 'initialized aa[%d]'%i, aa[i]
135             a[i]={'Username':plc[i]['peer_admin_name'],
136                   'AuthMethod':'password',
137                   'AuthString':plc[i]['peer_admin_password'],
138                   'Role':'admin'}
139             print 'initialized a[%d]'%i, a[i]
140
141 def test00_print (args=[1,2]):
142     global plc,s,a,aa
143     for i in args:
144         print 's[%d]'%i,s[i]
145         print 'aa[%d]'%i, aa[i]
146         print 'a[%d]'%i, a[i]
147
148 def check_nodes (en,ef,args=[1,2]):
149     global plc,s,a
150     for i in args:
151         n=len(s[i].GetNodes(a[i]))
152         f=len(s[i].GetForeignNodes(a[i]))
153         print '%02d: Checking nodes: got %d local (e=%d) & %d foreign (e=%d)'%(i,n,en,f,ef)
154         assert n==en
155         assert f==ef
156
157 # expected : local slices, foreign slices
158 def check_slices (els,efs,args=[1,2]):
159     global plc,s,a
160     for i in args:
161         ls=len(s[i].GetSlices(a[i]))
162         fs=len(s[i].GetForeignSlices(a[i]))
163         print '%02d: Checking slices: got %d local (e=%d) & %d foreign (e=%d)'%(i,ls,els,fs,efs)
164         assert els==ls
165         assert efs==fs
166
167 def show_nodes (i,node_ids):
168     for message,nodes in [ ['LOC',s[i].GetNodes(a[i],node_ids)],
169                            ['FOR',s[i].GetForeignNodes(a[i],node_ids)] ]:
170         if nodes:
171             print '[%s:%d] : '%(message,len(nodes)),
172             for node in nodes:
173                 print node['hostname']+' ',
174             print ''
175
176 def check_slice_nodes (expected_nodes, is_local_slice, args=[1,2]):
177     for ns in myrange(number_slices):
178         check_slice_nodes_n (ns,expected_nodes, is_local_slice, args)
179
180 def check_slice_nodes_n (ns,expected_nodes, is_local_slice, args=[1,2]):
181     global plc,s,a
182     for i in args:
183         peer=peer_index(i)
184         if is_local_slice:
185             sname=slice_name(i,ns)
186             slice=s[i].GetSlices(a[i],[sname])[0]
187             message='local'
188         else:
189             sname=slice_name(peer,ns)
190             slice=s[i].GetForeignSlices(a[i],[sname])[0]
191             message='foreign'
192         print '%02d: %s slice %s (e=%d) '%(i,message,sname,expected_nodes),
193         slice_node_ids=slice['node_ids']
194         print 'on nodes ',slice_node_ids
195         show_nodes (i,slice_node_ids)
196         assert len(slice_node_ids)==expected_nodes
197
198 # expected : nodes on local slice
199 def check_local_slice_nodes (expected, args=[1,2]):
200     check_slice_nodes(expected,True,args)
201
202 # expected : nodes on foreign slice
203 def check_foreign_slice_nodes (expected, args=[1,2]):
204     check_slice_nodes(expected,False,args)
205
206 def check_conf_files (args=[1,2]):
207     for nn in myrange(number_nodes):
208         check_conf_files_n (nn,args)
209
210 def check_conf_files_n (nn,args=[1,2]):
211     global plc,s,a
212     for i in args:
213         nodename=node_name(i,nn)
214         ndict= s[i].GetSlivers(a[i],[nodename])[0]
215         assert ndict['hostname'] == nodename
216         conf_files = ndict['conf_files']
217         print '%02d: %d conf_files in GetSlivers for node %s'%(i,len(conf_files),nodename)
218         for conf_file in conf_files:
219             print 'source=',conf_file['source'],'|',
220             print 'dest=',conf_file['dest'],'|',
221             print 'enabled=',conf_file['enabled'],'|',
222             print ''
223
224 import pprint
225 pp = pprint.PrettyPrinter(indent=3)
226
227 def check_slivers (esn,args=[1,2]):
228     for nn in myrange(number_nodes):
229         check_slivers_n (nn,esn,args)
230
231 # too verbose to check all nodes, let's check only the first one
232 def check_slivers_1 (esn,args=[1,2]):
233     check_slivers_n (1,esn,args)
234
235 def check_slivers_n (nn,esn,args=[1,2]):
236     global plc,s,a
237     for i in args:
238         nodename=node_name(i,i)
239         ndict= s[i].GetSlivers(a[i],[nodename])[0]
240         assert ndict['hostname'] == nodename
241         slivers = ndict['slivers']
242         print '%02d: %d slivers (exp. %d) in GetSlivers for node %s'\
243               %(i,len(slivers),esn,nodename)
244         for sliver in slivers:
245             print '>>slivername = ',sliver['name']
246             pp.pprint(sliver)
247         assert len(slivers) == esn
248                 
249
250 ####################
251 def test00_admin_person (args=[1,2]):
252     global plc,s,a
253     for i in args:
254         email = plc[i]['peer_admin_name']
255         try:
256             p=s[i].GetPersons(a[i],[email])[0]
257             plc[i]['peer_admin_id']=p['person_id']
258         except:
259             person_id=s[i].AddPerson(aa[i],{'first_name':'Local', 'last_name':'PeerPoint', 'role_ids':[10],
260                                             'email':email,'password':plc[i]['peer_admin_password']})
261             print '%02d: created peer admin account %d, %s - %s'%(i,person_id,plc[i]['peer_admin_name'],plc[i]['peer_admin_password'])
262             plc[i]['peer_admin_id']=person_id
263
264 def test00_admin_enable (args=[1,2]):
265     global plc,s,a
266     for i in args:
267         s[i].AdmSetPersonEnabled(aa[i],plc[i]['peer_admin_id'],True)
268         s[i].AddRoleToPerson(aa[i],'admin',plc[i]['peer_admin_id'])
269         print '%02d: enabled+admin on account %d:%s'%(i,plc[i]['peer_admin_id'],plc[i]['peer_admin_name'])
270
271 ####################
272 def test01_site (args=[1,2]):
273     global plc,s,a
274     for i in args:
275         peer=peer_index(i)
276         ### create a site (required for creating a slice)
277         sitename=site_name(i)
278         abbrev_name="abbr"+str(i)
279         login_base=plc[i]['plainname']
280         ### should be enough - needs to check we can add/del slices
281         max_slices = number_slices 
282         try:
283             s[i].GetSites(a[i],{'login_base':login_base})[0]
284         except:
285             site_id=s[i].AddSite (a[i], {'name':plc_name(i),
286                                          'abbreviated_name': abbrev_name,
287                                          'login_base': login_base,
288                                          'is_public': True,
289                                          'url': 'http://%s.com/'%abbrev_name,
290                                          'max_slices':max_slices})
291         ### max_slices does not seem taken into account at that stage
292             s[i].UpdateSite(a[i],site_id,{'max_slices':max_slices})
293             print '%02d: Created site %d with max_slices=%d'%(i,site_id,max_slices)
294             plc[i]['site_id']=site_id
295
296 def test01_peer_person (args=[1,2]):
297     global plc,s,a
298     for i in args:
299         peer=peer_index(i)
300         email=plc[peer]['peer_admin_name']
301         try:
302             p=s[i].GetPersons(a[i],[email])[0]
303             plc[i]['peer_person_id']=p['person_id']
304         except:
305             person_id = s[i].AddPerson (a[i], {'first_name':'Peering(plain passwd)', 'last_name':plc_name(peer), 'role_ids':[3000],
306                                                'email':email,'password':plc[peer]['peer_admin_password']})
307             print '%02d:Created person %d as the peer person'%(i,person_id)
308             plc[i]['peer_person_id']=person_id
309
310 def test01_peer (args=[1,2]):
311     global plc,s,a
312     for i in args:
313         peer=peer_index(i)
314         peername = plc_name(peer)
315         try:
316             p=s[i].GetPeers (a[i], [peername])[0]
317             plc[i]['peer_id']=p['peer_id']
318         except:
319             peer_id=s[i].AddPeer (a[i], {'peername':peername,'peer_url':plc[peer]['url'],'person_id':plc[i]['peer_person_id']})
320             # NOTE : need to manually reset the encrypted password through SQL at this point
321             print '%02d:Created peer %d'%(i,peer_id)
322             plc[i]['peer_id']=peer_id
323             print "PLEASE manually set password for person_id=%d in DB%d"%(plc[i]['peer_person_id'],i)
324
325 def test01_peer_passwd (args=[1,2]):
326     global plc,s,a
327     for i in args:
328         # using an ad-hoc local command for now - never could get quotes to reach sql....
329         print "Attempting to set passwd for person_id=%d in DB%d"%(plc[i]['peer_person_id'],i),
330         retcod=os.system("ssh root@%s new_plc_api/person-password.sh %d"%(plc[i]['hostname'],plc[i]['peer_person_id']))
331         print '-> system returns',retcod
332     
333 ##############################
334 # this one gets cached 
335 def get_peer_id (i):
336     try:
337         return plc[i]['peer_id']
338     except:
339         peername = plc_name (peer_index(i))
340         peer_id = s[i].GetPeers(a[i],[peername])[0]['peer_id']
341         plc[i]['peer_id'] = peer_id
342         return peer_id
343
344 def test01_refresh (args=[1,2]):
345     global plc,s,a
346     for i in args:
347         print '%02d: Refreshing peer'%(i),
348         retcod=s[i].RefreshPeer(a[i],get_peer_id(i))
349         print 'got ',retcod
350
351 ####################
352 def get_node_id(i,nodename):
353     return s[i].GetNodes(a[i],[nodename])[0]['node_id']
354
355 def clean_all_nodes (args=[1,2]):
356     global plc,s,a
357     for i in args:
358         print '%02d: Cleaning all nodes'%i
359         for node in s[i].GetNodes(a[i]):
360             print '%02d: > Cleaning node %d'%(i,node['node_id'])
361             s[i].DeleteNode(a[i],node['node_id'])
362
363 def test02_node (args=[1,2]):
364     for nn in myrange(number_nodes):
365         test02_node_n (nn,args)
366
367 def test02_node_n (nn,args=[1,2]):
368     global plc,s,a
369     for i in args:
370         nodename = node_name(i,nn)
371         try:
372             get_node_id(i,nodename)
373         except:
374             n=s[i].AddNode(a[i],1,{'hostname': nodename})
375             print '%02d: Added node %d %s'%(i,n,node_name(i,i))
376
377 def test02_delnode (args=[1,2]):
378     for nn in myrange(number_nodes):
379         test02_delnode_n (nn,args)
380
381 def test02_delnode_n (nn,args=[1,2]):
382     global plc,s,a
383     for i in args:
384         nodename = node_name(i,nn)
385         node_id = get_node_id (i,nodename)
386         retcod=s[i].DeleteNode(a[i],nodename)
387         print '%02d: Deleted node %d, returns %s'%(i,node_id,retcod)
388
389 ####################
390 def clean_all_slices (args=[1,2]):
391     global plc,s,a
392     for i in args:
393         print '%02d: Cleaning all slices'%i
394         for slice in s[i].GetSlices(a[i]):
395             slice_id = slice['slice_id']
396             if slice_id not in system_slices_ids:
397                 print '%02d: > Cleaning slice %d'%(i,slice_id)
398                 s[i].DeleteSlice(a[i],slice_id)
399
400 def get_slice_id (i,name):
401     return s[i].GetSlices(a[i],[name])[0]['slice_id']
402
403 def test03_slice (args=[1,2]):
404     for n in myrange(number_slices):
405         test03_slice_n (n,args)
406
407 def test03_slice_n (ns,args=[1,2]):
408     global plc,s,a
409     for i in args:
410         peer=peer_index(i)
411         plcname=plc_name(i)
412         slicename=slice_name(i,ns)
413         max_nodes=number_nodes
414         try:
415             s[i].GetSlices(a[i],[slicename])[0]
416         except:
417             slice_id=s[i].AddSlice (a[i],{'name':slicename,
418                                           'description':'slice %s on %s'%(slicename,plcname),
419                                           'url':'http://planet-lab.org/%s'%slicename,
420                                           'max_nodes':max_nodes,
421                                           'instanciation':'plc-instantiated',
422                                           })
423             print '%02d: created slice %d - max nodes=%d'%(i,slice_id,max_nodes)
424         
425
426 def test04_node_slice (is_local, add_if_true, args=[1,2]):
427     for ns in myrange(number_slices):
428         test04_node_slice_ns (ns,is_local, add_if_true, args)
429
430 def test04_node_slice_ns (ns,is_local, add_if_true, args=[1,2]):
431     test04_node_slice_nl_n (myrange(number_nodes),ns,is_local, add_if_true, args)
432
433 def test04_node_slice_nl_n (nnl,ns,is_local, add_if_true, args=[1,2]):
434     global plc,s,a
435     for i in args:
436         peer=peer_index(i)
437         slice_id = get_slice_id (i,slice_name (i,ns))
438         
439         if is_local:
440             hostnames=[node_name(i,nn) for nn in nnl]
441             nodetype='local'
442         else:
443             hostnames=[node_name(peer,nn) for nn in nnl]
444             nodetype='foreign'
445         if add_if_true:
446             s[i].AddSliceToNodes (a[i], slice_id,hostnames)
447             message="added"
448         else:
449             s[i].DeleteSliceFromNodes (a[i], slice_id,hostnames)
450             message="deleted"
451         print '%02d: %s in slice %d %s '%(i,message,slice_id,nodetype),
452         print hostnames
453
454 def test04_slice_add_lnode (args=[1,2]):
455     test04_node_slice (True,True,args)
456
457 def test04_slice_add_fnode (args=[1,2]):
458     test04_node_slice (False,True,args)
459
460 def test04_slice_del_lnode (args=[1,2]):
461     test04_node_slice (True,False,args)
462
463 def test04_slice_del_fnode (args=[1,2]):
464     test04_node_slice (False,False,args)
465
466 ####################
467 def test_all_init ():
468     message ("INIT")
469     test00_init ()
470     test00_print ()
471     test00_admin_person ()
472     test00_admin_enable ()
473     test01_peer_person ()
474     test01_peer ()
475     test01_peer_passwd ()
476
477     test01_site ()
478
479 def test_all_nodes ():
480
481     message ("RESETTING NODES")
482     clean_all_nodes ()
483     test01_refresh ()
484     check_nodes(0,0)
485     # create one node on each site
486     message ("CREATING NODES")
487     test02_node ()
488     check_nodes (number_nodes,0,)
489     test01_refresh ()
490     check_nodes (number_nodes,number_nodes,)
491
492     # check deletions
493     message ("DELETING NODES")
494     test02_delnode ([2])
495     check_nodes (number_nodes,number_nodes,[1])
496     check_nodes (0,number_nodes,[2])
497     test01_refresh ()
498     check_nodes (number_nodes,0,[1])
499     check_nodes (0,number_nodes,[2])
500
501     # recreate 
502     message ("RECREATING NODES")
503     test02_node ([2])
504     check_nodes (number_nodes,0,[1])
505     check_nodes (number_nodes,number_nodes,[2])
506     test01_refresh ()
507     check_nodes (number_nodes,number_nodes,)
508
509     # make sure node indexes differ
510     message ("DUMMY DEL/ADD for different indexes")
511     test02_delnode([2])
512     test02_node ([2])
513     check_nodes (number_nodes,number_nodes,)
514     test01_refresh ()
515     check_nodes (number_nodes,number_nodes,)
516
517 def test_all_addslices ():
518
519     # reset
520     message ("RESETTING SLICES TEST")
521     clean_all_nodes ()
522     test02_node ()
523     clean_all_slices ()
524     test01_refresh ()
525
526     # create slices on plc1
527     message ("CREATING SLICES on plc1")
528     test03_slice ([1])
529     # each site has 3 local slices and 0 foreign slice
530     check_slices (total_slices(),0,[1])
531     check_slices (system_slices(),0,[2])
532     test01_refresh ()
533     check_slices (total_slices(),0,[1])
534     check_slices (system_slices(),number_slices,[2])
535     # no slice has any node yet
536     check_local_slice_nodes(0,[1])
537     check_foreign_slice_nodes(0,[2])
538
539     # insert local nodes in local slice on plc1
540     message ("ADDING LOCAL NODES IN SLICES")
541     test04_slice_add_lnode ([1])
542     # of course the change is only local
543     check_local_slice_nodes (number_nodes,[1])
544     check_foreign_slice_nodes(0,[2])
545
546     # refreshing
547     test01_refresh ()
548     # remember that foreign slices only know about LOCAL nodes
549     # so refreshing does not do anything
550     check_local_slice_nodes (number_nodes,[1])
551     check_foreign_slice_nodes (0,[2])
552
553     # now we add foreign nodes into local slice
554     message ("ADDING FOREIGN NODES IN SLICES")
555     test04_slice_add_fnode ([1])
556     check_local_slice_nodes (2*number_nodes,[1])
557     check_foreign_slice_nodes (0,[2])
558
559     # refreshing
560     test01_refresh ()
561     # remember that foreign slices only know about LOCAL nodes
562     # so this does not do anything
563     check_local_slice_nodes (2*number_nodes,[1])
564     check_foreign_slice_nodes (number_nodes,[2])
565
566     check_slivers_1(total_slivers())
567
568 def test_all_delslices ():
569
570     message ("DELETING FOREIGN NODES FROM SLICES")
571     test04_slice_del_fnode([1])
572     check_local_slice_nodes (number_nodes,[1])
573     check_foreign_slice_nodes (number_nodes,[2])
574     # mmh?
575     check_slivers_1(total_slivers(),[1])
576
577     test01_refresh ()
578     check_local_slice_nodes (number_nodes,[1])
579     check_foreign_slice_nodes (0,[2])
580     
581     message ("DELETING LOCAL NODES FROM SLICES")
582     test04_slice_del_lnode([1])
583     check_local_slice_nodes (0,[1])
584     check_foreign_slice_nodes (0,[2])
585     test01_refresh ()
586     check_local_slice_nodes (0,[1])
587     check_foreign_slice_nodes (0,[2])
588
589     message ("CHECKING SLICES CLEAN UP")
590     clean_all_slices([1])
591     check_slices (system_slices(),0,[1])
592     check_slices (system_slices(),number_slices,[2])
593     test01_refresh ()
594     check_slices(system_slices(),0)
595
596 def test_all_slices ():
597     test_all_addslices ()
598     test_all_delslices ()
599     
600 def test_all ():
601     test_all_init ()
602     test_all_nodes ()
603     test_all_slices ()
604
605 if __name__ == '__main__':
606     test_all()
607