(*) full support for database caching, including SliceAttributes
[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 ### xxx todo
18 # check sites
19 # check persons
20
21 # support reloading without wiping everything off
22 # dunno how to do (defvar plc)
23
24 import getopt
25 import sys
26 import time
27
28 ## we use indexes 1 and 2 
29 try:
30     dir(plc)
31 except:
32     plc=[None,None,None]
33 ## the server objects
34 try:
35     dir(s)
36 except:
37     s=[None,None,None]
38 ## the authentication objects
39 ## our user
40 try:
41     dir(a)
42 except:
43     a=[None,None,None]
44 ## the builtin root user for bootstrapping
45 try:
46     dir(aa)
47 except:
48     aa=[None,None,None]
49
50 ####################
51 import xmlrpclib
52 import os
53
54 ####################
55 # predefined stuff
56 # number of 'system' persons
57 # builtin maint, local root, 2 persons for the peering
58 system_persons = 4
59 # among that, 1 gets refreshed - other ones have conflicting names
60 system_persons_cross = 1
61
62 system_slices_ids = (1,2)
63 def system_slices ():
64     return len(system_slices_ids)
65 def total_slices ():
66     return number_slices+system_slices()
67
68 # temporary - the myplc I use doesnt know about 'system' yet
69 def system_slivers ():
70 #    return len(system_slices_ids)
71     return 0
72 def total_slivers ():
73     return number_slices+system_slivers()
74
75 ####################
76 # set initial conditions
77 def define_test (sites,keys,persons,nodes,slices,fast_mode):
78     global number_sites, number_keys, number_persons, number_nodes, number_slices, fast_flag
79     number_sites = sites
80     number_keys=keys
81     number_persons=persons
82     number_nodes=nodes
83     number_slices=slices
84     fast_flag=fast_mode
85
86 def show_test():
87     print '%d sites, %d keys, %d persons, %d nodes & %d slices'%(number_sites, number_keys,number_persons,
88                                                                  number_nodes,number_slices)
89
90 def fast():
91     define_test(1,1,1,1,1,True)
92     
93 def normal():
94     define_test (sites=4,keys=2,persons=4,nodes=5,slices=4,fast_mode=False)
95
96 def big():
97     define_test (sites=16,keys=8,persons=16,nodes=20,slices=16,fast_mode=False)
98
99 fast()
100 #normal()
101
102 ####################
103 # argh, for login_name that doesn't accept digits
104 plain_numbers=['zero','one','two','three','four','five','six','seven','eight','nine','ten',
105                'eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty']
106 ####################
107 plc1={ 'plcname':'plc1 in federation',
108        'hostname':'lurch.cs.princeton.edu',
109        'url-format':'https://%s:443/PLCAPI/',
110        'builtin-admin-id':'root@plc1.org',
111        'builtin-admin-password':'root',
112        'peer-admin-name':'peer1@planet-lab.org',
113        'peer-admin-password':'peer',
114        'node-format':'n1%02d.plc1.org',
115        'plainname' : 'one',
116        'site-format':'one%s',
117        'person-format' : 'user1-%d@plc1.org',
118        'key-format':'ssh-rsa 1111111111111111 user%d-key%d',
119        'person-password' : 'password1',
120        }
121 plc2={ 'plcname':'plc2 in federation',
122        'hostname':'planetlab-devbox.inria.fr',
123        'url-format':'https://%s:443/PLCAPI/',
124        'builtin-admin-id':'root@plc2.org',
125        'builtin-admin-password':'root',
126        'peer-admin-name':'peer2@planet-lab.org',
127        'peer-admin-password':'peer',
128        'node-format':'n2%02d.plc2.org',
129        'plainname' : 'two',
130        'site-format':'two%s',
131        'person-format' : 'user2-%d@plc2.org',
132        'key-format':'ssh-rsa 2222222222222222 user%d-key%d',
133        'person-password' : 'password2',
134        }
135
136 ####################
137 def peer_index(i):
138     return 3-i
139
140 def plc_name (i):
141     return plc[i]['plcname']
142
143 def site_name (i,n):
144     x=site_login_base(i,n)
145     return 'Site fullname '+x
146
147 def site_login_base (i,n):
148     return plc[i]['site-format']%plain_numbers[n]
149
150 def person_name (i,n):
151     return plc[i]['person-format']%n
152
153 def key_name (i,n,k):
154     return plc[i]['key-format']%(n,k)
155
156 def node_name (i,n):
157     return plc[i]['node-format']%n
158
159 def map_on_site (n):
160     result=(n%number_sites)
161     if (result==0):
162         result=number_sites
163     return result
164
165 def slice_name (i,n):
166     site_index=map_on_site(n)
167     return "%s_slice%d"%(site_login_base(i,site_index),n)
168
169 def sat_name (i):
170     return 'sat_%d'%i
171
172 # to have indexes start at 1
173 def myrange (n):
174     return range (1,n+1,1)
175
176 def message (*args):
177     print "====================",
178     print args
179     
180 ##########
181 def timer_start ():
182     global epoch,last_time
183     epoch = time.time()
184     last_time=epoch
185     print '+++ timer start'
186
187 def timer_show ():
188     global last_time
189     now=time.time()
190     print '+++ %.02f seconds ellapsed (%.02f)'%(now-epoch,now-last_time)
191     last_time=now
192
193 ####################
194 def test00_init (args=[1,2]):
195     timer_start()
196     global plc,s,a,aa
197     ## have you loaded this file already (support for reload)
198     if plc[1]:
199         pass
200     else:
201         plc=[None,plc1,plc2]
202         for i in args:
203             url=plc[i]['url-format']%plc[i]['hostname']
204             plc[i]['url']=url
205             s[i]=xmlrpclib.ServerProxy(url,allow_none=True)
206             print 'initializing s[%d]'%i,url
207             aa[i]={'Username':plc[i]['builtin-admin-id'],
208                    'AuthMethod':'password',
209                    'AuthString':plc[i]['builtin-admin-password'],
210                    'Role':'admin'}
211             print 'initialized aa[%d]'%i, aa[i]
212             a[i]={'Username':plc[i]['peer-admin-name'],
213                   'AuthMethod':'password',
214                   'AuthString':plc[i]['peer-admin-password'],
215                   'Role':'admin'}
216             print 'initialized a[%d]'%i, a[i]
217
218 def test00_print (args=[1,2]):
219     for i in args:
220         print 's[%d]'%i,s[i]
221         print 'aa[%d]'%i, aa[i]
222         print 'a[%d]'%i, a[i]
223
224 def check_nodes (el,ef,args=[1,2]):
225     for i in args:
226         # use a single request and sort afterwards for efficiency
227         # could have used GetNodes's scope as well
228         all_nodes = s[i].GetNodes(a[i])
229         n = len ([ x for x in all_nodes if x['peer_id'] is None])
230         f = len ([ x for x in all_nodes if x['peer_id'] is not None])
231         print '%02d: Checking nodes: got %d local (e=%d) & %d foreign (e=%d)'%(i,n,el,f,ef)
232         assert n==el
233         assert f==ef
234
235 def check_keys (el,ef,args=[1,2]):
236     for i in args:
237         # use a single request and sort afterwards for efficiency
238         # could have used GetKeys's scope as well
239         all_keys = s[i].GetKeys(a[i])
240         n = len ([ x for x in all_keys if x['peer_id'] is None])
241         f = len ([ x for x in all_keys if x['peer_id'] is not None])
242         print '%02d: Checking keys: got %d local (e=%d) & %d foreign (e=%d)'%(i,n,el,f,ef)
243         assert n==el
244         assert f==ef
245
246 def check_persons (el,ef,args=[1,2]):
247     for i in args:
248         # use a single request and sort afterwards for efficiency
249         # could have used GetPersons's scope as well
250         all_persons = s[i].GetPersons(a[i])
251         n = len ([ x for x in all_persons if x['peer_id'] is None])
252         f = len ([ x for x in all_persons if x['peer_id'] is not None])
253         print '%02d: Checking persons: got %d local (e=%d) & %d foreign (e=%d)'%(i,n,el,f,ef)
254         assert n==el
255         assert f==ef
256
257 # expected : local slices, foreign slices
258 def check_slices (els,efs,args=[1,2]):
259     for i in args:
260         ls=len(s[i].GetSlices(a[i],{'peer_id':None}))
261         fs=len(s[i].GetSlices(a[i],{'~peer_id':None}))
262         print '%02d: Checking slices: got %d local (e=%d) & %d foreign (e=%d)'%(i,ls,els,fs,efs)
263         assert els==ls
264         assert efs==fs
265
266 def show_nodes (i,node_ids):
267     # same as above
268     all_nodes = s[i].GetNodes(a[i],node_ids)
269     loc_nodes = filter (lambda n: n['peer_id'] is None, all_nodes)
270     for_nodes = filter (lambda n: n['peer_id'] is not None, all_nodes)
271
272     for message,nodes in [ ['LOC',loc_nodes], ['FOR',for_nodes] ] :
273         if nodes:
274             print '[%s:%d] : '%(message,len(nodes)),
275             for node in nodes:
276                 print node['hostname']+' ',
277             print ''
278
279 def check_slice_nodes (expected_nodes, is_local_slice, args=[1,2]):
280     for ns in myrange(number_slices):
281         check_slice_nodes_n (ns,expected_nodes, is_local_slice, args)
282
283 def check_slice_nodes_n (ns,expected_nodes, is_local_slice, args=[1,2]):
284     for i in args:
285         peer=peer_index(i)
286         if is_local_slice:
287             sname=slice_name(i,ns)
288             slice=s[i].GetSlices(a[i],{'name':[sname],'peer_id':None})[0]
289             message='local'
290         else:
291             sname=slice_name(peer,ns)
292             slice=s[i].GetSlices(a[i],{'name':[sname],'~peer_id':None})[0]
293             message='foreign'
294         print '%02d: %s slice %s (e=%d) '%(i,message,sname,expected_nodes),
295         slice_node_ids=slice['node_ids']
296         print 'on nodes ',slice_node_ids
297         show_nodes (i,slice_node_ids)
298         assert len(slice_node_ids)>=expected_nodes
299         if len(slice_node_ids) != expected_nodes:
300             print 'TEMPORARY'
301
302 # expected : nodes on local slice
303 def check_local_slice_nodes (expected, args=[1,2]):
304     check_slice_nodes(expected,True,args)
305
306 # expected : nodes on foreign slice
307 def check_foreign_slice_nodes (expected, args=[1,2]):
308     check_slice_nodes(expected,False,args)
309
310 def check_conf_files (args=[1,2]):
311     for nn in myrange(number_nodes):
312         check_conf_files_n (nn,args)
313
314 def check_conf_files_n (nn,args=[1,2]):
315     for i in args:
316         nodename=node_name(i,nn)
317         ndict= s[i].GetSlivers(a[i],[nodename])[0]
318         assert ndict['hostname'] == nodename
319         conf_files = ndict['conf_files']
320         print '%02d: %d conf_files in GetSlivers for node %s'%(i,len(conf_files),nodename)
321         for conf_file in conf_files:
322             print 'source=',conf_file['source'],'|',
323             print 'dest=',conf_file['dest'],'|',
324             print 'enabled=',conf_file['enabled'],'|',
325             print ''
326
327 import pprint
328 pp = pprint.PrettyPrinter(indent=3)
329
330 def check_slivers (esn,args=[1,2]):
331     for nn in myrange(number_nodes):
332         check_slivers_n (nn,esn,args)
333
334 # too verbose to check all nodes, let's check only the first one
335 def check_slivers_1 (esn,args=[1,2]):
336     check_slivers_n (1,esn,args)
337
338 def check_slivers_n (nn,esn,args=[1,2]):
339     for i in args:
340         nodename=node_name(i,nn)
341         ndict= s[i].GetSlivers(a[i],[nodename])[0]
342         assert ndict['hostname'] == nodename
343         slivers = ndict['slivers']
344         print '%02d: %d slivers (exp. %d) in GetSlivers for node %s'\
345               %(i,len(slivers),esn,nodename)
346         for sliver in slivers:
347             print '>>slivername = ',sliver['name']
348             pretty_printer.pprint(sliver)
349         assert len(slivers) == esn
350                 
351
352 ####################
353 def test00_admin_person (args=[1,2]):
354     global plc
355     for i in args:
356         email = plc[i]['peer-admin-name']
357         try:
358             p=s[i].GetPersons(a[i],[email])[0]
359             plc[i]['peer-admin-id']=p['person_id']
360         except:
361             person_id=s[i].AddPerson(aa[i],{'first_name':'Local', 
362                                             'last_name':'PeerPoint', 
363                                             'role_ids':[10],
364                                             'email':email,
365                                             'password':plc[i]['peer-admin-password']})
366             print '%02d:== created peer admin account %d, %s - %s'%(i,
367                                                                   person_id,plc[i]['peer-admin-name'],
368                                                                   plc[i]['peer-admin-password'])
369             plc[i]['peer-admin-id']=person_id
370
371 def test00_admin_enable (args=[1,2]):
372     for i in args:
373         s[i].AdmSetPersonEnabled(aa[i],plc[i]['peer-admin-id'],True)
374         s[i].AddRoleToPerson(aa[i],'admin',plc[i]['peer-admin-id'])
375         print '%02d:== enabled+admin on account %d:%s'%(i,plc[i]['peer-admin-id'],plc[i]['peer-admin-name'])
376
377 def test00_peer_person (args=[1,2]):
378     global plc
379     for i in args:
380         peer=peer_index(i)
381         email=plc[peer]['peer-admin-name']
382         try:
383             p=s[i].GetPersons(a[i],[email])[0]
384             plc[i]['peer_person_id']=p['person_id']
385         except:
386             person_id = s[i].AddPerson (a[i], {'first_name':'Peering(plain passwd)', 'last_name':plc_name(peer), 'role_ids':[3000],
387                                                'email':email,'password':plc[peer]['peer-admin-password']})
388             print '%02d:Created person %d as the peer person'%(i,person_id)
389             plc[i]['peer_person_id']=person_id
390
391 ####################
392 def test00_peer (args=[1,2]):
393     global plc
394     for i in args:
395         peer=peer_index(i)
396         peername = plc_name(peer)
397         try:
398             p=s[i].GetPeers (a[i], [peername])[0]
399             plc[i]['peer_id']=p['peer_id']
400         except:
401             peer_id=s[i].AddPeer (a[i], {'peername':peername,'peer_url':plc[peer]['url'],'person_id':plc[i]['peer_person_id']})
402             # NOTE : need to manually reset the encrypted password through SQL at this point
403             print '%02d:Created peer %d'%(i,peer_id)
404             plc[i]['peer_id']=peer_id
405             print "PLEASE manually set password for person_id=%d in DB%d"%(plc[i]['peer_person_id'],i)
406
407 def test00_peer_passwd (args=[1,2]):
408     for i in args:
409         # using an ad-hoc local command for now - never could get quotes to reach sql....
410         print "Attempting to set passwd for person_id=%d in DB%d"%(plc[i]['peer_person_id'],i),
411         retcod=os.system("ssh root@%s new_plc_api/person-password.sh %d"%(plc[i]['hostname'],plc[i]['peer_person_id']))
412         print '-> system returns',retcod
413     
414 # this one gets cached 
415 def get_peer_id (i):
416     try:
417         return plc[i]['peer_id']
418     except:
419         peername = plc_name (peer_index(i))
420         peer_id = s[i].GetPeers(a[i],[peername])[0]['peer_id']
421         plc[i]['peer_id'] = peer_id
422         return peer_id
423
424 ##############################
425 def test00_refresh (message,args=[1,2]):
426     print '=== refresh',message
427     timer_show()
428     for i in args:
429         print '%02d:== Refreshing peer'%(i),
430         retcod=s[i].RefreshPeer(a[i],get_peer_id(i))
431         print 'got ',retcod
432         timer_show()
433
434 ####################
435 def test01_site (args=[1,2]):
436     for ns in myrange(number_sites):
437         test01_site_n (ns,True,args)
438
439 def test01_del_site (args=[1,2]):
440     for ns in myrange(number_sites):
441         test01_site_n (ns,False,args)
442
443 def test01_site_n (ns,add_if_true,args=[1,2]):
444     for i in args:
445         login_base = site_login_base (i,ns)
446         try:
447             site_id = s[i].GetSites(a[i],[login_base])[0]['site_id']
448             if not add_if_true:
449                 s[i].DeleteSite(a[i],site_id)
450                 print "%02d:== deleted site_id %d"%(i,site_id)
451         except:
452             if add_if_true:
453                 sitename=site_name(i,ns)
454                 abbrev_name="abbr"+str(i)
455                 max_slices = number_slices
456                 site_id=s[i].AddSite (a[i], {'name':plc_name(i),
457                                              'abbreviated_name': abbrev_name,
458                                              'login_base': login_base,
459                                              'is_public': True,
460                                              'url': 'http://%s.com/'%abbrev_name,
461                                              'max_slices':max_slices})
462                 ### max_slices does not seem taken into account at that stage
463                 s[i].UpdateSite(a[i],site_id,{'max_slices':max_slices})
464                 print '%02d:== Created site %d with max_slices=%d'%(i,site_id,max_slices)
465
466 ####################
467 def test02_person (args=[1,2]):
468     for np in myrange(number_persons):
469         test02_person_n (np,True,args)
470
471 def test02_del_person (args=[1,2]):
472     for np in myrange(number_persons):
473         test02_person_n (np,False,args)
474
475 def test02_person_n (np,add_if_true,args=[1,2]):
476     test02_person_n_ks (np, myrange(number_keys),add_if_true,args)
477
478 def test02_person_n_ks (np,nks,add_if_true,args=[1,2]):
479     for i in args:
480         email = person_name(i,np)
481         try:
482             person_id=s[i].GetPersons(a[i],[email])[0]['person_id']
483             if not add_if_true:
484                 s[i].DeletePerson(a[i],person_id)
485                 print "%02d:== deleted person_id %d"%(i,person_id)
486         except:
487             if add_if_true:
488                 password = plc[i]['person-password']
489                 person_id=s[i].AddPerson(a[i],{'first_name':'Your average', 
490                                                'last_name':'User%d'%np, 
491                                                'role_ids':[30],
492                                                'email':email,
493                                                'password': password })
494                 print '%02d:== created user account %d, %s - %s'%(i, person_id,email,password)
495                 for nk in nks:
496                     key=key_name(i,np,nk)
497                     s[i].AddPersonKey(aa[i],email,{'key_type':'ssh', 'key':key})
498                     print '%02d:== added key %s to person %s'%(i,key,email)
499
500 ####################
501 # retrieves node_id from hostname - checks for local nodes only
502 def get_local_node_id(i,nodename):
503     return s[i].GetNodes(a[i],[nodename],None,'local')[0]['node_id']
504
505 # clean all local nodes - foreign nodes are not supposed to be cleaned up manually
506 def clean_all_nodes (args=[1,2]):
507     for i in args:
508         print '%02d:== Cleaning all nodes'%i
509         loc_nodes = s[i].GetNodes(a[i],None,None,'local')
510         for node in loc_nodes:
511             print '%02d:==== Cleaning node %d'%(i,node['node_id'])
512             s[i].DeleteNode(a[i],node['node_id'])
513
514 def test03_node (args=[1,2]):
515     for nn in myrange(number_nodes):
516         test03_node_n (nn,args)
517
518 def test03_node_n (nn,args=[1,2]):
519     for i in args:
520         nodename = node_name(i,nn)
521         try:
522             get_local_node_id(i,nodename)
523         except:
524             login_base=site_login_base(i,map_on_site(nn))
525             n=s[i].AddNode(a[i],login_base,{'hostname': nodename})
526             print '%02d:== Added node %d %s'%(i,n,node_name(i,i))
527
528 def test02_delnode (args=[1,2]):
529     for nn in myrange(number_nodes):
530         test02_delnode_n (nn,args)
531
532 def test02_delnode_n (nn,args=[1,2]):
533     for i in args:
534         nodename = node_name(i,nn)
535         node_id = get_local_node_id (i,nodename)
536         retcod=s[i].DeleteNode(a[i],nodename)
537         print '%02d:== Deleted node %d, returns %s'%(i,node_id,retcod)
538
539 ####################
540 def clean_all_slices (args=[1,2]):
541     for i in args:
542         print '%02d:== Cleaning all slices'%i
543         for slice in s[i].GetSlices(a[i],{'peer_id':None}):
544             slice_id = slice['slice_id']
545             if slice_id not in system_slices_ids:
546                 print '%02d:==== Cleaning slice %d'%(i,slice_id)
547                 s[i].DeleteSlice(a[i],slice_id)
548
549 def test04_slice (args=[1,2]):
550     for n in myrange(number_slices):
551         test04_slice_n (n,args)
552
553 def test04_slice_n (ns,args=[1,2]):
554     for i in args:
555         peer=peer_index(i)
556         plcname=plc_name(i)
557         slicename=slice_name(i,ns)
558         max_nodes=number_nodes
559         try:
560             s[i].GetSlices(a[i],[slicename])[0]
561         except:
562             slice_id=s[i].AddSlice (a[i],{'name':slicename,
563                                           'description':'slice %s on %s'%(slicename,plcname),
564                                           'url':'http://planet-lab.org/%s'%slicename,
565                                           'max_nodes':max_nodes,
566                                           'instanciation':'plc-instantiated',
567                                           })
568             print '%02d:== created slice %d - max nodes=%d'%(i,slice_id,max_nodes)
569             for np in myrange(number_persons):
570                 email = person_name (i,np)
571                 retcod = s[i].AddPersonToSlice (a[i], email, slicename)
572                 print '%02d:== Attached person %s to slice %s'%(i,email,slicename)
573         
574
575 def test04_node_slice (is_local, add_if_true, args=[1,2]):
576     for ns in myrange(number_slices):
577         test04_node_slice_ns (ns,is_local, add_if_true, args)
578
579 def test04_node_slice_ns (ns,is_local, add_if_true, args=[1,2]):
580     test04_node_slice_nl_n (myrange(number_nodes),ns,is_local, add_if_true, args)
581
582 def test04_node_slice_nl_n (nnl,ns,is_local, add_if_true, args=[1,2]):
583     for i in args:
584         peer=peer_index(i)
585         sname = slice_name (i,ns)
586         
587         if is_local:
588             hostnames=[node_name(i,nn) for nn in nnl]
589             nodetype='local'
590         else:
591             hostnames=[node_name(peer,nn) for nn in nnl]
592             nodetype='foreign'
593         if add_if_true:
594             s[i].AddSliceToNodes (a[i], sname,hostnames)
595             message="added"
596         else:
597             s[i].DeleteSliceFromNodes (a[i], sname,hostnames)
598             message="deleted"
599         print '%02d:== %s in slice %s %s '%(i,message,sname,nodetype),
600         print hostnames
601
602 def test04_slice_add_lnode (args=[1,2]):
603     test04_node_slice (True,True,args)
604
605 def test04_slice_add_fnode (args=[1,2]):
606     test04_node_slice (False,True,args)
607
608 def test04_slice_del_lnode (args=[1,2]):
609     test04_node_slice (True,False,args)
610
611 def test04_slice_del_fnode (args=[1,2]):
612     test04_node_slice (False,False,args)
613
614 ####################
615 def test05_sat (args=[1,2]):
616     for i in args:
617         name = sat_name(i)
618         try:
619             sat_id=s[i].GetSliceAttributeTypes (a[i],[name])[0]
620         except:
621             description="custom sat on plc%d"%i
622             min_role_id=10
623             sat_id=s[i].AddSliceAttributeType (a[i],
624                                                { 'name':name,
625                                                  'description': description,
626                                                  'min_role_id' : min_role_id})
627             print '%02d:== created SliceAttributeType = %d'%(i,sat_id)
628
629 # for test, we create 4 slice_attributes
630 # on slice1 - sat=custom_made (see above) - all nodes
631 # on slice1 - sat=custom_made (see above) - node=n1
632 # on slice1 - sat='net_max' - all nodes
633 # on slice1 - sat='net_max' - node=n1
634
635 def test05_sa_atom (slice_name,sat_name,value,node,i):
636     sa_id=s[i].GetSliceAttributes(a[i],{'name':sat_name,
637                                         'value':value})
638     if not sa_id:
639         if node:
640             sa_id=s[i].AddSliceAttribute(a[i],
641                                          slice_name,
642                                          sat_name,
643                                          value,
644                                          node)
645         else:
646             print 'slice_name',slice_name,'sat_name',sat_name
647             sa_id=s[i].AddSliceAttribute(a[i],
648                                          slice_name,
649                                          sat_name,
650                                          value)
651         print '%02d:== created SliceAttribute = %d'%(i,sa_id),
652         print 'On slice',slice_name,'and node',node
653         
654 def test05_sa (args=[1,2]):
655     for i in args:
656         test05_sa_atom (slice_name(i,1),sat_name(i),'custom sat/all nodes',None,i)
657         test05_sa_atom (slice_name(i,1),sat_name(i),'custom sat/node1',node_name(i,1),i)
658         test05_sa_atom (slice_name(i,1),'net_max','predefined sat/all nodes',None,i)
659         test05_sa_atom (slice_name(i,1),'net_max','predefined sat/node1',node_name(i,1),i)
660         
661 ##############################
662 # readable dumps
663 ##############################
664 def p_site (s):
665     print (s['site_id'],s['peer_id'],s['login_base'],s['name'],s['node_ids'])
666
667 def p_key (k):
668     print  (k['key_id'],k['peer_id'],k['key'])
669     
670 def p_person (p):
671     print  (p['person_id'],p['peer_id'],p['email'],'keys:',p['key_ids'],'sites:',p['site_ids']) 
672
673 def p_node(n):
674     print (n['node_id'],n['peer_id'],n['hostname'],'sls=',n['slice_ids'],'site=',n['site_id'])
675
676 def p_slice(s):
677     print (s['slice_id'],s['peer_id'],s['name'],'nodes=',s['node_ids'],'persons=',s['person_ids'])
678     print '---',('sas=',s['slice_attribute_ids'],s['name'],'crp=',s['creator_person_id'])
679
680 def p_sat(sat):
681     print (sat['attribute_type_id'],sat['peer_id'], sat['name'], sat['min_role_id'], sat['description'])
682
683 def p_sa (sa):
684         print (sa['slice_attribute_id'],sa['peer_id'],sa['name'],'AT_id:',sa['attribute_type_id'])
685         print '---',('v=',sa['value'],'sl=',sa['slice_id'],'n=',sa['node_id'])
686
687 def p_sliver (x):
688     print ('SLIVERS for : hostname',x['hostname'])
689     print ('%d config files'%len(x['conf_files']))
690     for sv in x['slivers']:
691         p_sliver_slice(sv,x['hostname'])
692
693 import pprint
694 pretty_printer=pprint.PrettyPrinter(5)
695
696 def p_sliver_slice(sliver,hostname):
697     print 'SLIVER on hostname %s, s='%hostname,sliver['name']
698     print 'KEYS',
699     pretty_printer.pprint(sliver['keys'])
700     print 'ATTRIBUTES',
701     pretty_printer.pprint(sliver['attributes'])
702
703 def dump (args=[1,2]):
704     for i in args:
705         print 'SITES'
706         [p_site(x) for x in s[i].GetSites(a[i])]
707         print 'KEYS'
708         [p_key(x) for x in s[i].GetKeys(a[i])]
709         print 'PERSONS'
710         [p_person(x) for x in s[i].GetPersons(a[i])]
711         print 'NODES'
712         [p_node(x) for x in s[i].GetNodes(a[i])]
713         print 'SLICES'
714         [p_slice(x) for x in s[i].GetSlices(a[i])]
715         print 'Slice Attribute Types'
716         [p_sat(x) for x in s[i].GetSliceAttributeTypes(a[i])]
717         print 'Slice Attributes'
718         [p_sa(x) for x in s[i].GetSliceAttributes(a[i])]
719         print 'SLIVERS'
720         [p_sliver(x) for x in s[i].GetSlivers(a[i])]
721     
722
723 ## for usage under the api
724 def pt ():
725     for x in GetSites():
726         p_site(x)
727         
728 def pk ():
729     for x in GetKeys():
730         print  (x['key_id'],x['peer_id'],x['key']) 
731
732 def pp ():
733     for x in GetPersons():
734         p_person(x)
735
736 def pn ():
737     for x in GetNodes():
738         p_node(x)
739
740 def ps ():
741     for x in GetSlices():
742         p_slice(x)
743
744 def psat():
745     for x in GetSliceAttributeTypes():
746         p_sat(x)
747         
748 def psa():
749     for x in GetSliceAttributes():
750         p_sa(x)
751         
752 def pv ():
753     for s in GetSlivers():
754         p_sliver(s)
755
756 def all():
757     print 'SITES'
758     pt()
759     print 'KEYS'
760     pk()
761     print 'PERSONS'
762     pp()
763     print 'NODES'
764     pn()
765     print 'SLICES'
766     ps()
767     print 'SLICE ATTR TYPES'
768     psat()
769     print 'SLICE ATTRS'
770     psa()
771     print 'SLIVERS'
772     pv()
773
774
775 ####################
776 def test_all_init ():
777     message ("INIT")
778     test00_init ()
779     test00_print ()
780     test00_admin_person ()
781     test00_admin_enable ()
782     test00_peer_person ()
783     test00_peer ()
784     test00_peer_passwd ()
785
786 def test_all_sites ():
787     test01_site ()
788     test00_refresh ('after site creation')
789
790 def test_all_persons ():
791     test02_del_person()
792     test00_refresh ('before persons&keys creation')
793     check_keys(0,0)
794     check_persons(system_persons,system_persons_cross)
795     message ("Creating persons&keys")
796     test02_person ()
797     if not fast_flag:
798         message ("1 extra del/add cycle for unique indexes")
799         test02_del_person([2])
800         test02_person([2])
801     check_keys(number_persons*number_keys,0)
802     check_persons(system_persons+number_persons,system_persons_cross)
803     test00_refresh ('after persons&keys creation')
804     check_keys(number_persons*number_keys,number_persons*number_keys)
805     check_persons(system_persons+number_persons,system_persons_cross+number_persons)
806
807 def test_all_nodes ():
808
809     message ("RESETTING NODES")
810     clean_all_nodes ()
811     test00_refresh ('cleaned nodes')
812     check_nodes(0,0)
813
814     # create one node on each site
815     message ("CREATING NODES")
816     test03_node ()
817     check_nodes(number_nodes,0)
818     test00_refresh ('after node creation')
819     check_nodes(number_nodes,number_nodes)
820     test02_delnode([2])
821     if not fast_flag:
822         message ("2 extra del/add cycles on plc2 for different indexes")
823         test03_node ([2])
824         test02_delnode([2])
825         test03_node ([2])
826         test02_delnode([2])
827     check_nodes(0,number_nodes,[2])
828     test00_refresh('after deletion on plc2')
829     check_nodes(number_nodes,0,[1])
830     check_nodes(0,number_nodes,[2])
831     message ("ADD on plc2 for different indexes")
832     test03_node ([2])
833     check_nodes (number_nodes,0,[1])
834     check_nodes (number_nodes,number_nodes,[2])
835     test00_refresh('after re-creation on plc2')
836     check_nodes (number_nodes,number_nodes,)
837
838 def test_all_addslices ():
839
840     # reset
841     message ("RESETTING SLICES TEST")
842     clean_all_nodes ()
843     test03_node ()
844     clean_all_slices ()
845     test00_refresh ("After slices init")
846
847     # create slices on plc1
848     message ("CREATING SLICES on plc1")
849     test04_slice ([1])
850     # each site has 3 local slices and 0 foreign slice
851     check_slices (total_slices(),0,[1])
852     check_slices (system_slices(),0,[2])
853     test00_refresh ("after slice created on plc1")
854     check_slices (total_slices(),0,[1])
855     check_slices (system_slices(),number_slices,[2])
856     # no slice has any node yet
857     check_local_slice_nodes(0,[1])
858     check_foreign_slice_nodes(0,[2])
859
860     # insert local nodes in local slice on plc1
861     message ("ADDING LOCAL NODES IN SLICES")
862     test04_slice_add_lnode ([1])
863     # of course the change is only local
864     check_local_slice_nodes (number_nodes,[1])
865     check_foreign_slice_nodes(0,[2])
866
867     # refreshing
868     test00_refresh ("After local nodes were added on plc1")
869     check_local_slice_nodes (number_nodes,[1])
870     check_foreign_slice_nodes (number_nodes,[2])
871
872     # now we add foreign nodes into local slice
873     message ("ADDING FOREIGN NODES IN SLICES")
874     test04_slice_add_fnode ([1])
875     check_local_slice_nodes (2*number_nodes,[1])
876     check_foreign_slice_nodes (number_nodes,[2])
877
878     # refreshing
879     test00_refresh ("After foreign nodes were added in plc1")
880     # remember that foreign slices only know about LOCAL nodes
881     # so this does not do anything
882     check_local_slice_nodes (2*number_nodes,[1])
883     check_foreign_slice_nodes (2*number_nodes,[2])
884
885     check_slivers_1(total_slivers())
886
887 def test_all_delslices ():
888
889     message ("DELETING FOREIGN NODES FROM SLICES")
890     test04_slice_del_fnode([1])
891     check_local_slice_nodes (number_nodes,[1])
892     check_foreign_slice_nodes (2*number_nodes,[2])
893     # mmh?
894     check_slivers_1(total_slivers(),[1])
895
896     test00_refresh ("After foreign nodes were removed on plc1")
897     check_local_slice_nodes (number_nodes,[1])
898     check_foreign_slice_nodes (number_nodes,[2])
899     
900     message ("DELETING LOCAL NODES FROM SLICES")
901     test04_slice_del_lnode([1])
902     check_local_slice_nodes (0,[1])
903     check_foreign_slice_nodes (number_nodes,[2])
904
905     test00_refresh ("After local nodes were removed on plc1")
906     check_local_slice_nodes (0,[1])
907     check_foreign_slice_nodes (0,[2])
908
909     message ("CHECKING SLICES CLEAN UP")
910     clean_all_slices([1])
911     check_slices (system_slices(),0,[1])
912     check_slices (system_slices(),number_slices,[2])
913     test00_refresh ("After slices clenaup")
914     check_slices(system_slices(),0)
915
916 def test_all_slices ():
917     test_all_addslices ()
918     test_all_delslices ()
919     
920 def test_all_sats ():
921     test05_sat ()
922     test00_refresh("after SliceAttributeType creation")                   
923
924 def test_all ():
925     test_all_init ()
926     timer_show()
927     test_all_sites ()
928     timer_show()
929     test_all_persons ()
930     timer_show()
931     test_all_nodes ()
932     timer_show()
933     test_all_slices ()
934     timer_show()
935     test_all_sats ()
936     timer_show()
937     dump()
938     timer_show()
939     message("END")
940
941 ### ad hoc test sequences
942 def populate ():
943     test_all_init()
944     test01_site()
945     test02_person()
946     test03_node()
947     test04_slice([1])
948     test04_slice_add_lnode([1])
949     test05_sat()
950     test05_sa([1])
951     test00_refresh ("populate: refreshing peer 1",[1])
952     test04_slice_add_fnode([1])
953     test00_refresh("populate: refresh all")
954     dump()
955
956 def test_now ():
957     test_all_init()
958     test_all_sites ()
959 #    clean_all_nodes()
960 #    clean_all_slices()
961 #    populate()
962
963 #####
964 def usage ():
965     print "Usage: %s [-n] [-f]"%sys.argv[0]
966     print " -f runs faster (1 node - 1 slice)"
967     print " -b performs big run (4 times as large as normal)"
968     print " -n runs test_now instead of test_all"
969     print " -p runs populate instead of test_all"
970     
971     sys.exit(1)
972
973 def main ():
974     try:
975         (o,a) = getopt.getopt(sys.argv[1:], "fnpb")
976     except:
977         usage()
978     func = test_all
979     for (opt,val) in o:
980         if opt=='-f':
981             fast()
982         elif opt=='-b':
983             big()
984         elif opt=='-n':
985             print 'Running test_now'
986             func = test_now
987         elif opt=='-p':
988             print 'Running populate'
989             func = populate
990         else:
991             usage()
992     if a:
993         usage()
994     show_test()
995     func()   
996     timer_show()
997
998 if __name__ == '__main__':
999     normal()
1000     main()
1001