-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathflexswitch
executable file
·311 lines (269 loc) · 11 KB
/
flexswitch
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
#!/usr/bin/env python
import os
import signal
import sys
import time
import daemon
import datetime
import re
import json
import subprocess
from optparse import OptionParser
ASICD_CONF_FILE='/opt/flexswitch/params/asicd.conf'
SYS_PROFILE ='/opt/flexswitch/sysprofile/systemProfile.json'
def determineMacAddress ():
print 'Getting MAC address and Mgmt Ip address'
process = subprocess.Popen('ifconfig -a' ,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
errcode = process.returncode
macAddrList = []
macAddrCopy = []
portCopy = []
for line in out.split('\n'):
if re.search('HWaddr', line):
addr = line.partition('HWaddr')[-1].strip(' ')
port = line.split()[0]
if addr not in macAddrCopy and not (port.startswith('SVI') or port.startswith('bcm') or port.startswith('fpPort')):
macAddrList.append((port, addr))
macAddrCopy.append(addr)
chosenMac = macAddrList[0][1]
newMac = '%x' %(int(chosenMac.replace(':',''), 16))
returnMac = int(newMac, 16) +1
returnMacStr = '%x' %(returnMac)
returnMacStr = '%s' %(returnMacStr.zfill(12))
resultMacStr = ''.join([c+':' if i%2 and i <len(returnMacStr)-1 else c for i,c in enumerate(returnMacStr)])
for line in out.split('\n'):
if re.search('inet addr', line):
port = line.split()[0]
ip_addr_info = line.partition('inet addr')[-1].strip(':')
if port not in portCopy and not (port.startswith('SVI') or port.startswith('bcm') or port.startswith('fpPort')):
ip_addr = ip_addr_info.split()[0]
portCopy.append(port)
if os.path.isfile(ASICD_CONF_FILE) :
with open(ASICD_CONF_FILE, 'r') as fileHdl:
confData = json.load(fileHdl)
confData['SwitchMac'] = resultMacStr
with open(ASICD_CONF_FILE, 'w') as fileHdl:
json.dump(confData, fileHdl, indent=2)
if os.path.isfile(SYS_PROFILE) :
with open(SYS_PROFILE, 'r') as fileHdl:
confData = json.load(fileHdl)
confData['MgmtIp'] = ip_addr
confData['SwitchMac'] = resultMacStr
confData['RouterId'] = "0.0.0.0"
with open(SYS_PROFILE, 'w') as fileHdl:
json.dump(confData, fileHdl, indent=2)
def isProcessRunning(pidFile):
processId = 0
try:
fp = file(pidFile, "r")
processId = int(fp.read().strip())
fp.close()
if os.path.exists('/proc/%d' % processId):
pass
else:
processId = 0
except IOError:
processId = 0
return (processId != 0)
def getDaemonsInfo (baseDir) :
daemonsList = [
{'name': 'sysd',
'runlevel' : 0,
'params': '-params=' + baseDir + '/params'},
{'name': 'asicd',
'runlevel' : 1,
'params': '-params=' + baseDir + '/params'},
{'name': 'ribd',
'runlevel' : 6,
'params': '-params=' + baseDir + '/params'},
{'name': 'bfdd',
'runlevel' : 7,
'params': '-params=' + baseDir + '/params'},
{'name': 'arpd',
'runlevel' : 5,
'params': '-params=' + baseDir + '/params'},
{'name': 'dhcpd',
'runlevel' : 10,
'params': '-params=' + baseDir + '/params'},
{'name': 'bgpd',
'runlevel' : 8,
'params': '-params=' + baseDir + '/params'},
{'name': 'ospfd',
'runlevel' : 9,
'params': '-params=' + baseDir + '/params'},
{'name': 'lacpd',
'runlevel' : 2,
'params': '-params=' + baseDir + '/params'},
{'name': 'dhcprelayd',
'runlevel' : 11,
'params': '-params=' + baseDir + '/params'},
{'name': 'stpd',
'runlevel' : 3,
'params': '-params=' + baseDir + '/params'},
{'name': 'vrrpd',
'runlevel' : 12,
'params': '-params=' + baseDir + '/params'},
{'name': 'lldpd',
'runlevel' : 4,
'params': '-params=' + baseDir + '/params'},
{'name': 'vxland',
'runlevel' : 13,
'params': '-params=' + baseDir + '/params'},
{'name': 'confd',
'runlevel' : 14,
'params': '-params=' + baseDir + '/params'},
]
disabledDaemons = []
daemonsToStart = []
with open(SYS_PROFILE) as fd:
sysCfg = json.load(fd)
dmnsInfo = sysCfg['Daemons']
disabledDaemons = [ dmn['Name'] for dmn in dmnsInfo if not dmn['Enable']]
for dmn in daemonsList:
if dmn['name'] not in disabledDaemons:
daemonsToStart.append(dmn)
return daemonsToStart
class FlexSwitchDaemon (daemon.Daemon):
def run(self, *args, **kwargs):
cmd = args[0][0]
if type(args[0][1]) ==list:
pargs = args[0][1]
else :
pargs = args[0]
os.execvp(cmd, pargs)
if __name__=="__main__":
parser = OptionParser()
parser.add_option("-d", "--dir",
dest="directory",
action='store',
help="Directory where the binaries are stored")
parser.add_option("-o", "--op",
dest="op",
default="start",
action='store',
help="Operation (start/stop) ")
parser.add_option("-b", "--boot",
dest="boot",
action='store',
help="Type of subsequent boot operation (cold/warm) ")
parser.add_option("-n", "--name",
dest="name",
action='store',
help="Daemon name")
(opts, args) = parser.parse_args()
localBld = False
if opts.directory != None:
localBld = True
baseDir = opts.directory
else:
baseDir = "/opt/flexswitch"
if opts.op != None and opts.op not in ['start', 'stop']:
parser.print_usage()
sys.exit(0)
if opts.boot != None and opts.boot not in ['cold', 'warm']:
parser.print_usage()
sys.exit(0)
if opts.op != 'stop' and opts.boot != None:
parser.print_usage()
sys.exit(0)
if opts.name != None and opts.op not in ['start', 'stop']:
parser.print_usage()
sys.exit(0)
if not localBld:
determineMacAddress()
else:
SYS_PROFILE = baseDir + '/params/systemProfile.json'
pidFileDir = baseDir+'/bin/pids/'
asicdBootModeFile = baseDir + '/params/asicdBootMode.conf'
if opts.boot != None and opts.boot == 'cold':
asicdBootMode = '0'
else:
asicdBootMode = '0' #FIXME:Change this to 1, when we start supporting restart on all apps
if opts.op == 'start':
if ((not os.path.exists(pidFileDir))):
os.makedirs(pidFileDir)
start = datetime.datetime.now()
dmnCount = 0
for dmn in getDaemonsInfo(baseDir):
if opts.name != None and opts.name != dmn['name']:
continue
print "Starting Daemon %s Params: %s" %( dmn['name'], dmn['params'])
dmnCount += 1
pidFile = pidFileDir + dmn['name']+'.pid'
if isProcessRunning(pidFile):
print "process %s is already running" %(dmn['name'])
else:
cmd = baseDir +'/bin/'+ dmn['name']
pargs = (cmd, dmn['params'])
time.sleep(0.02)
pid = os.fork()
if pid == 0:
dmnInst = FlexSwitchDaemon (pidFile,
#stdout= baseDir+'/bin/'+'log.txt',
#stderr= baseDir+'/bin/'+'log.txt',
stdout = '/var/log/syslog',
stderr = '/var/log/syslog',
#stderr= baseDir+'/bin/'+'log.txt',
verbose=2)
dmnInst.start(pargs)
end = datetime.datetime.now()
print 'Total time taken to start all %s daemons is %s' %(dmnCount, end -start)
else:
allDmns = getDaemonsInfo(baseDir)
sortedDmns = reversed(sorted(allDmns,key= lambda dmn:dmn['runlevel']))
for dmn in sortedDmns:
if opts.name != None and opts.name != dmn['name']:
continue
try:
print "Stopping Daemon %s" %( dmn['name'])
pidFile = pidFileDir + dmn['name']+'.pid'
pf = file(pidFile, 'r')
pid = int(pf.read().strip())
pf.close()
try :
#Check if process matching pid file is running
os.kill(pid, 0)
except:
#Process with pid not running, cleanup pid file
os.remove(pidFile)
continue
#Process matching pid exists, perform cleanup
if dmn['name'] == 'asicd':
if os.path.exists(asicdBootModeFile):
os.remove(asicdBootModeFile)
if opts.boot == 'cold':
os.kill(pid, signal.SIGUSR1)
else:
os.kill(pid, signal.SIGUSR1) #FIXME:Change this to SIGHUP, when we start supporting restart on all apps
f = open(asicdBootModeFile, 'w')
f.write(asicdBootMode)
f.close()
else:
os.kill(pid, signal.SIGHUP)
except:
print '*** Failed to stop process [%s]' %(dmn['name'])
time.sleep(1)
for dmn in getDaemonsInfo(baseDir if not localBld else baseDir+'/bin'):
if opts.name != None and opts.name != dmn['name']:
continue
try:
pidFile = pidFileDir + dmn['name']+'.pid'
pf = file(pidFile, 'r')
pid = int(pf.read().strip())
pf.close()
try :
#Check if cleanup completed
os.kill(pid, 0)
except:
#Process with pid successfully cleaned up
os.remove(pidFile)
continue
#Force kill by sending SIGTERM
os.kill(pid, signal.SIGTERM)
os.remove(pidFile)
except:
print '*** Failed to Kill process [%s]' %(dmn['name'])