-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp4.py
More file actions
764 lines (672 loc) · 30.9 KB
/
app4.py
File metadata and controls
764 lines (672 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
#!/usr/bin/env python
"""
PRE-REQUISITES:
1. Python 2.x
2. Install python-requests:
a. sudo easy_install requests
3. Go to dev.elbrys.com and follow the directions there
BUG/SUGGESTIONS:
Mail bug reports and suggestion to : support@elbrys.com
Bug reports may also be logged in github here: https://github.com/Elbrys/ODL-S-Sample-Apps/issues
DESCRIPTION:
This is an intermediate complexity application that utilizes multi-threading.
The application is the same as app3.py except that it does not have a fixed set
of policies like app3.py. Instead it reads an external file that has a list of
policy definitions. You can update this file while app4.py is running and
then use the menu option to restart the application and the new policy
definitions will be made available the next time you select 'change policy'
The application is associated with the switch you configured on the command line.
You must have configured that switch to use controller of your SDN Developer Lab as its openflow controller per
the instructions on dev.elbrys.com. Any endpoint that does not yet have an associated
policy (one you gave it using this application - see below) will be detected
and will cause an 'unmanaged endpoint' event to be sent to this application.
This application has created a subscription to events. It will receive events
from your switch. IF Event logging is ENABLED (see below): it will print a message to the screen
when it receives events. When a new 'unmanaged endpoint' event occurs it will print a message to
the screen as well as add that endpoint to its list of known endpoints. Event logging is disabled by default.
All traffic for unmanaged endpoints will be blocked until you associate a policy to the endpoint.
This application will allow you to view a list of all unmanaged endpoints and select
a target endpoint and then do any number of actions to that endpoint, including
associating a policy to it.
While this application is running, you can go to sdn-developer.elbrys.com
and refresh the screen and you will see this application listed in the applications table. In addition
the switch you configured on the command line should indicate it is active on the SDN Developer Lab screen
by being displayed in green.
Enable event logging, connect one or more user devices (laptop, tablet, phone) to ports on your network device.
After you connect the device, cause it to send network traffic (ping, web browse, etc)
You should see an event indicating an 'unmanaged endpoint' with a MAC address
that matches the device you have connected to the switch (if event logging is enabled).
"""
import sys, os, errno, signal
import requests
import json
import time
import argparse
from requests.auth import HTTPBasicAuth
import threading
import Queue
import traceback
def interuppt_handler(signum, frame):
sys.exit(-2) #Terminate process here as catching the signal removes the close process behaviour of Ctrl-C
signal.signal(signal.SIGINT, interuppt_handler)
def GetAuthToken(user, password):
# This calls the api to create an authorization token to make other calls
# RETURNS: authorization token
global odlsBaseUrl
url = odlsBaseUrl + '/auth/token'
print "GetAuthToken: " + odlsBaseUrl
headers = {'content-type': 'application/json'}
user = "name="+user
appId = requests.get(url, headers=headers, auth=HTTPBasicAuth(user,password))
result = appId.text
status = appId.status_code
if ((status >= 200) & (status <=299)):
authToken = appId.json()
authToken = authToken['token']
else:
print " "
print "!! Error !!"
print " Unable to create authorization token. Double check that the username and password you entered."
print " See usage below:"
parser.print_help()
sys.exit()
return authToken;
def CreateApp(authToken, switches, parser):
global odlsBaseUrl
# This removes any zombie apps and then calls the api to create an application
# RETURNS: app identifier
RemoveZombieApps(authToken, switches)
print switches
switchesStr = ', '.join(switches)
url = odlsBaseUrl + '/applications'
payload = {'name': 'Demo App4 - Connected to switch: ' + switchesStr,
'scope': {'vnets':switches}}
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
appId = requests.post(url, data=json.dumps(payload), headers=headers)
result = appId.text
status = appId.status_code
if ((status >= 200) & (status <=299)):
appId = appId.json()
appId = appId['id']
else:
print " "
print "!! Error !!"
print " Unable to create application. Double check your switch identifier."
print " See usage below:"
parser.print_help()
sys.exit()
return appId;
def CreatePolicy(authToken, appId, payload):
global odlsBaseUrl
# This calls the api to create a
# policy for the application.
# The policy is defined by payload which is the JSON body defining the
# policy to be created
# RETURNS: policy identifier
# NOTE: For this application, in the payload parameter,
# the default policy must always be False. If you want to see 'unmanaged endpoint'
# events in subscription stream then you cannot have a default policy
# defined.
# This application depends on seeing the 'unmanaged endpoint' event.
url = odlsBaseUrl + '/applications/' + appId + '/policies'
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.post(url, data=json.dumps(payload), headers=headers)
status = r.status_code
if ((status >= 200) & (status <=299)):
policyId = r.json()
policyId = policyId['id']
else:
print " "
print "!! Error !!"
print " Unable to create policy."
print r.text
sys.exit()
return policyId;
def CreateSubscription(authToken, appId):
global odlsBaseUrl
# This calls the OpenNAC api to create a subscription
# RETURNS: subscription identifier
url = odlsBaseUrl + '/applications/' + appId + '/subscriptions'
payload = {'type': 'httpSSE'}
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
subId = requests.post(url, data=json.dumps(payload), headers=headers)
result = subId.text
status = subId.status_code
if ((status >= 200) & (status <=299)):
subId = subId.json()
subId = subId['id']
else:
print " "
print "!! Error !!"
print " Unable to create subscription."
print r.text
sys.exit()
return subId;
def GetApps(authToken):
global odlsBaseUrl
url = odlsBaseUrl + '/applications'
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.get(url, headers=headers)
if ((r.status_code < 200) | (r.status_code > 299)):
print "Error getting applications list: " + r.text
sys.exit()
else:
return r
def GetAppInfo(authToken, appId):
global odlsBaseUrl
url = odlsBaseUrl + '/applications/' + appId
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.get(url, headers=headers)
if ((r.status_code < 200) | (r.status_code > 299)):
print "Error getting application info: " + r.text
sys.exit()
else:
return r
def GetEndpointInfo(authToken, appId, endpointId):
global odlsBaseUrl
url = odlsBaseUrl + '/applications/' + appId + '/endpoints/' + endpointId
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.get(url, headers=headers)
if ((r.status_code < 200) | (r.status_code > 299)):
print "Error getting endpoint info: " + r.text
sys.exit()
else:
return r
def DeleteEndpoint(authToken, appId, endpointId):
global odlsBaseUrl
url = odlsBaseUrl + '/applications/' + appId + '/endpoints/' + endpointId
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.delete(url, headers=headers)
if ((r.status_code < 200) | (r.status_code > 299)):
print "Error deleting endpoint: " + r.text
sys.exit()
else:
return r
def ChangeEndpointPolicy(authToken, endpointId, policyId):
global odlsBaseUrl
url = odlsBaseUrl + '/endpoints/' + endpointId + '/policy'
payload = {'policy': policyId}
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.put(url, data=json.dumps(payload), headers=headers)
if ((r.status_code < 200) | (r.status_code > 299)):
print "Error changing policy for endpoint: " + r.text
sys.exit()
else:
return r
def GetPolicyInfo(authToken, policyId):
global odlsBaseUrl
url = odlsBaseUrl + '/policies/' + policyId
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.get(url, headers=headers)
if ((r.status_code < 200) | (r.status_code > 299)):
print "Error getting policy info: " + r.text
sys.exit()
else:
return r
def RemoveZombieApps(authToken, switches):
# Removes any old applications currently connected to the target switch. Only
# one application may be connected to a switch.
apps = GetApps(authToken)
for a in apps.json():
appInfo = GetAppInfo(authToken, a['id'])
appInfo = appInfo.json()
appScope = appInfo['scope']
appVnets = appScope['vnets']
for v in appVnets:
if (v in switches):
print "Deleting a zombie application: " + a['id'] + ", " + a['name']
DeleteApp(authToken,a['id'])
break
def DeleteApp(authToken, appId):
global odlsBaseUrl
# This calls the api to delete an application
# RETURNS: app identifier
url = odlsBaseUrl + '/applications/' + appId
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + authToken}
r = requests.delete(url, headers=headers)
def GetCommandLineParser():
# This method will process the command line parameters
parser = argparse.ArgumentParser(description='Simple SDN Application to block/unblock devices connected to switch.')
parser.add_argument('--id',required=True,
help='your Application id. Go to sdn-developer.elbrys.com, logon, find SDN App ID on the SDN Applications table.')
parser.add_argument('--secret',required=True,
help='your Application secret. Go to sdn-developer.elbrys.com, logon, find SDN App Secret on SDN Applications table, select the "eyeball" icon next to password.')
parser.add_argument('switches', metavar='switchId', nargs='+',
help='Datapath Id (DPID) or vNet ID (Tallac) for the switches/APs connected without : e.g. ccfa00b07b95 Go to sdn-developer.elbrys.com, logon, look in Devices table')
parser.add_argument('--server',required=True,
help='The IP address controller. Go to sdn-developer.elbrys.com, logon, look for IP Address on the "Controller" table.')
parser.add_argument('--port',required=True,
help='The TCP port number for REST API. Go to sdn-developer.elbrys.com, logon, look at "Controller" table, for REST API Port.')
return parser
def UpdateEndpoints(authToken, appId, endpoints):
# Add any new endpoints detected from events
while not odlsQueue.empty():
data = odlsQueue.get()
endpointId = data['id']
endpointMac = data['mac']
try:
del endpoints[endpointId]
except KeyError:
pass
endpoints[endpointId] = data
# Go through all endpoints and update their data - data for endpoints can change over time, roaming may change
# connected switch or IP address, policy for endpoint may habe been changed...
for e in endpoints:
epInfo = GetEndpointInfo(authToken, appId, e)
if (epInfo):
epInfo = epInfo.json()
try:
del endpoints[e]
except KeyError:
pass
endpoints[e] = epInfo
return endpoints
def UserCmdSelectEndpoint(endpoints):
selectedEndpointId=""
if not endpoints:
print "There are currently no endpoints connected to your switch. You may need to "
print " cause it to generate network traffic (ping something, browse in browser, etc)."
else:
print "Known endpoints: "
done = False
while (not done):
epList = []
idx = 0
for e in endpoints:
epList.insert(idx,e) #insert e at idx - insert inserts before idx+1
ep = endpoints.get(e)
print " " + str(idx) + ": " + ep['mac'] + ", " + ep['ip'] + ", " + ep['id']
idx=idx+1
selectedIdx = raw_input("Enter number of endpoint and enter: ")
if ((int(selectedIdx)<0) or (int(selectedIdx)>=idx)):
done = False
print "The number you entered is out of range. Please retry. You entered: " + selectedIdx
else:
done = True
print selectedIdx
print int(selectedIdx)
print epList
selectedEndpointId=epList[int(selectedIdx)]
print selectedEndpointId
return(selectedEndpointId)
def UserCmdShowDetails(authToken, endpoints, selectedEp):
if (len(selectedEp)<=0):
print " No currently selected Endpoint."
else:
ep = None
ep = endpoints.get(selectedEp)
if (not ep):
print " Selected endpoint no longer in endpoint list, select another. " + selectedEp
else:
print " id: " + ep.get('id','No ID.')
print " MAC address: " + ep.get('mac','No MAC')
print " IP address: " + ep.get('ip','No IP address.')
print " Time created: " + str(ep.get('timeCreated', 'No creation time.'))
policyId = ep.get('policy',None)
if (not policyId):
print " Current policy: No Policy: unmanaged"
else:
pInfo = GetPolicyInfo(authToken, policyId)
pInfo = pInfo.json()
print " Current policy: " + pInfo.get('name','No Name') + "(" + str(policyId) + ")"
links = ep['links']
print " Application: " + str(links.get('application', 'No associated application.'))
print " Account: " + str(links.get('account', 'No associated account.'))
print " Connection properties: "
properties = ep.get('properties',None)
if (properties):
for p in properties:
print " Link type: " + p.get('type','No type')
if (p['type'] == 'openflow'):
print " Datapathid: " + str(p.get('datapathId','No Datapathid'))
print " Port: " + str(p.get('port', 'No port'))
elif (p['type'] == 'tallac'):
print " Vnet id: " + str(p.get('vnet', 'No vnet'))
print " Vnet name: " + p.get('vnetName', 'No vnet Name.')
print " NAS ID: " + str(p.get('nasId','No NAS ID defined.'))
print " NAS MAC: " + p.get('nasMac', 'No MAC address')
print " NAS IP: " + p.get('nasIp','No IP address')
else:
print " <property type unknown by this app. This app needs to be updated.>"
def UserCmdForgetEndpoint(authToken, appId, endpoints, selectedEp):
if (len(selectedEp)<=0):
print " No currently selected Endpoint."
else:
ep = None
ep = endpoints.get(selectedEp)
if (not ep):
print " Selected endpoint no longer in endpoint list, select another. " + selectedEp
else:
DeleteEndpoint(authToken, appId, ep['id'])
del endpoints[selectedEp]
return endpoints
def UserCmdChangePolicy(authToken, appId, endpoints, selectedEp, policies):
if (len(selectedEp)<=0):
print " No currently selected Endpoint."
else:
ep = None
ep = endpoints.get(selectedEp)
if (not ep):
print " Selected endpoint no longer in endpoint list, select another. " + selectedEp
else:
print "Available Policies: "
done = False
while (not done):
pList = []
idx = 0
for p in policies:
policy = policies.get(p)
pList.insert(idx,policy['id']) #insert p at idx - insert inserts before idx+1
print " " + str(idx) + ": " + policy['name'] + ", " + policy['id']
idx=idx+1
selectedIdx = raw_input("Enter number of policy and enter: ")
if ((int(selectedIdx)<0) or (int(selectedIdx)>=idx)):
done = False
print "The number you entered is out of range. Please retry. You entered: " + selectedIdx
else:
done = True
selectedPolicyId=pList[int(selectedIdx)]
print "Endpoint ID " + ep['id']
print "Policy ID" + selectedPolicyId
ChangeEndpointPolicy(authToken, ep['id'], selectedPolicyId)
def UserCmdRestartApp(authToken, args, parser, appId, thread):
# This will delete the current application and create a new application.
# It returns the result from StartApplication(), see that function for its return value.
StopApplication(authToken, appId, thread)
appInfo = StartApplication(args, parser)
print "\n Application restarted. All endpoints have been forgotten and will appear "
print " as unmanaged endpoints again when they pass their first packet. You will need "
print " to set their policies again. There are new identifiers for application, subscription and policies.\n\n"
return appInfo
class ReceiveOdlsEvents(threading.Thread):
"""
A thread class that will receive events
"""
def __init__ (self, authToken, subId, q):
self.authToken = authToken
self.subId = subId
self.q = q
threading.Thread.__init__ (self)
self._stop = threading.Event()
self._log = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
def logEnable(self):
self._log.set()
def logDisable(self):
self._log.clear()
def logToggle(self):
if (self.logging()):
self._log.clear()
else:
self._log.set()
def logging(self):
return self._log.isSet()
def run(self):
global odlsBaseUrl
# This calls a subscription url as a streaming http interface.
# It is waiting for an event message .
# the event message is sent one line at a time across the stream.
# each line beginning with a '<linetype>:'.
# <linetype> may be 'event:' which indicates a new event, after the : is the type of event
# <linetype> may be 'data:' which indicates json data, this will be data associated with
# the preceding event
# an empty line is sent at the end of sending an event.
# A typical event may look like (ignore the # at start...that is python comment):
# event: unmanagedEndPoint
# data: <some JSON data>
# data: <some more JSON data>
#
# This function receives each line until an empty line is sent.
# This function collects all lines that begin with 'data:' and puts them in a buffer
# This function parses the buffer as json
# This function then parses the json to validate that the event was for an
# 'unmanaged endpoint', and then gathers the event identifier
# from the event.
# RETURNS: nothing
#Create a policy to allow all traffic
url = odlsBaseUrl + '/httpsse/' + self.subId
headers = {'content-type': 'application/json',
'Authorization': 'bearer ' + self.authToken}
try:
while (True):
r = requests.get(url, headers=headers, stream=True)
if (self.stopped()):
print" -->Terminating thread that listens for events due to stop signal from main app."
break
jsonBuffer=''
for line in r.iter_lines(chunk_size=1):
if (len(line) <= 0):
#empty line indicates end of an event report.
break
if line:
#event lines begin with 'event:'
#json lines the describe event begin with 'data:'
split = line.split(":",1)
if split[0] in ("data"):
jsonBuffer=jsonBuffer+split[1]
elif split[0] in ("event"):
if split[1] in (" keepAlive"):
if (self.logging()):
print " -->event: keep alive signal (connection is good)."
elif split[1] in (" unmanagedEndPoint"):
if (self.logging()):
print " -->event: unmanaged endpoint connected, collecting its data..."
elif split[1] in (" uriTrack"):
if (self.logging()):
print " -->event: URI tracking data being delivered, collecting its data..."
# if we received 'data:' lines
if (len(jsonBuffer) > 0):
r = json.loads(jsonBuffer)
eventId = r['id']
typeInfo = r['type']
if typeInfo in ("unmanagedEndPoint"):
data = r['data']
self.q.put(data)
endpointId = data['id']
endpointMac = data['mac']
if (self.logging()):
print " -->event: unmanaged endpoint collected and added to list of endpoints: " + endpointMac
elif typeInfo in ("uriTrack"):
data = r['data']
endpoint = data['endpoint']
uris = data['uris']
if (self.logging()):
print " -->event: enpoint " + endpointMac + " visited the following URIs: "
for uri in uris:
print " " + uri["uri"]
except Exception as inst:
print " "
print "Exception in Events Thread. Terminating application."
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to be printed directly
print traceback.format_exc()
os._exit(1)
def LoadPolicyFile():
with open("policies.json") as json_file:
json_data = json.load(json_file)
print json.dumps(json_data)
return json_data
def StartApplication(args, parser):
authToken=""
try:
#This starts an application.
#It returns:
# A python dictionary of the format:
# {'authToken':<authorization token>
# 'appId':<application id for the new application created>,
# 'policies':<a dictionary of policies indexed by policy id>,
# 'subId':<subscription id for subscription for events>}
# 'thread':<Thread that is listening to events>}
# 'selectedEp':<The key into 'endpoints' of the currently selected Endpoint...or "">}
# 'endpoints':<The list of endpoints that have been detected>}
print " "
print "Obtaining authorization token..."
authToken = GetAuthToken(args.id,args.secret)
print " ...auth token obtained: " + authToken
print 'Creating application...'
appId = CreateApp(authToken, args.switches ,parser)
print " ...application created with id:" + appId
print " "
print 'Reading policies.json file...'
policiesRead = LoadPolicyFile()
policies = {}
for p in policiesRead:
print "Creating policy " + p['name'] + " ..."
pId=CreatePolicy(authToken, appId, p)
print " ...policy created with id:" + pId
p['id']=pId
policies[p['name']]=p
print " "
print "Creating subscription to network access events..."
subId = CreateSubscription(authToken, appId)
print " ...subscription created with id:" + subId
print " "
print "Starting thread to listen for events on subscription..."
odlsThread = ReceiveOdlsEvents(authToken, subId, odlsQueue)
odlsThread.setName('Event Listener Thread')
odlsThread.start()
print " ...thread started."
return {'authToken':authToken,
'appId':appId,
'policies':policies,
'subId':subId,
'thread':odlsThread,
'selectedEp':"",
'endpoints':{}}
except Exception as inst:
print " Exception detected while creating application..."
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to be printed directly
print traceback.format_exc()
if (thread):
print "Stopping application..."
StopApplication(authToken, appId, thread)
print " ...application stopped."
elif (authToken):
print "Deleting application..."
DeleteApp(authToken, appId)
print "...application deleted."
print ""
print "Now that the application is deleted endpoints connected to the switch will continue to have connectivity."
print "If you go to sdn-developer.elbrys.com and refresh the screen you will "
print " no longer see this application listed."
def StopApplication(authToken, appId, thread):
DeleteApp(authToken, appId)
if (thread):
thread.stop()
thread.join()
def main():
global odlsBaseUrl
# The version of the application
# 1.0 - initial version
version="1.0"
print "App4"
print "Version: " + version
print __doc__
# --------------------------------
# Command Line Processing
parser=GetCommandLineParser()
args = parser.parse_args()
odlsBaseUrl = "http://"+args.server+":"+args.port+"/ape/v1"
print "API is at: " + odlsBaseUrl
# --------------------------------
# Main application
try:
appInfo = StartApplication(args,parser)
authToken = appInfo['authToken']
appId = appInfo['appId']
subId = appInfo['subId']
policies = appInfo['policies']
thread = appInfo['thread']
selectedEp = appInfo['selectedEp']
endpoints = appInfo['endpoints']
thread.logDisable()
print __doc__
while True:
print " "
print " "
print " "
print "========================================================================="
print "Current selected endpoint: "
endpoints = UpdateEndpoints(authToken, appId, endpoints)
UserCmdShowDetails(authToken, endpoints, selectedEp)
print "-------------------------------------------------------------------------"
print " (s)elect an endpoint"
print " (d)etails of selected endpoint"
print " (f)orget selected endpoint"
print " (c)hange policy of selected endpoint"
print " (k)ill and restart this app"
if (thread.logging()):
print " (t)oggle event logging (currently enabled)"
else:
print " (t)oggle event logging (currently disabled)"
print " (h)elp"
print " (q)uit"
ch = raw_input("Enter an action from above list and hit enter: ")
print " "
endpoints = UpdateEndpoints(authToken, appId, endpoints)
if (ch == 's'):
selectedEp = UserCmdSelectEndpoint(endpoints)
elif (ch == 'd'):
UserCmdShowDetails(authToken, endpoints, selectedEp)
elif (ch == 'f'):
endpoints = UserCmdForgetEndpoint(authToken, appId, endpoints, selectedEp)
elif (ch == 'c'):
UserCmdChangePolicy(authToken, appId, endpoints, selectedEp, policies)
elif (ch == 'k'):
appInfo = UserCmdRestartApp(authToken, args, parser, appId, thread)
authToken = appInfo['authToken']
appId = appInfo['appId']
subId = appInfo['subId']
policies = appInfo['policies']
thread = appInfo['thread']
selectedEp = appInfo['selectedEp']
endpoints = appInfo['endpoints']
elif (ch == 't'):
thread.logToggle()
elif (ch == 'h'):
print __doc__
elif (ch == 'q'):
break
else:
print "Did not recognize the action you entered, please try again. You entered: " + ch
except Exception as inst:
print " Exception detected while executing main loop of application..."
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to be printed directly
print traceback.format_exc()
finally:
if (thread):
print "Stopping application..."
StopApplication(authToken, appId, thread)
print " ...application stopped."
elif (authToken):
print "Deleting application..."
DeleteApp(authToken, appId)
print "...application deleted."
print ""
print "Now that the application is deleted endpoints connected to the switch will continue to have connectivity."
print "If you go to sdn-developer.elbrys.com and refresh the screen you will "
print " no longer see this application listed."
if __name__ == "__main__":
# The BASE url where the RESTful api listens
thread = None
odlsBaseUrl = "http://placeholder.for.rest.api.com";
odlsQueue = Queue.Queue()
main()