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