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