-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathXSFeatureNetworkReset.py
More file actions
452 lines (395 loc) · 14.2 KB
/
XSFeatureNetworkReset.py
File metadata and controls
452 lines (395 loc) · 14.2 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
# (c) 2007-2009 Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 only.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
if __name__ == "__main__":
raise Exception("This script is a plugin for xsconsole and cannot run independently")
from XSConsoleStandard import *
pool_conf = '%s/pool.conf' % (Config.Inst().XCPConfigDir())
interface_reconfigure = '%s/interface-reconfigure' % (Config.Inst().LibexecPath())
inventory_file = '/etc/xensource-inventory'
management_conf = '/etc/firstboot.d/data/management.conf'
network_reset = '/tmp/network-reset'
def read_dict_file(fname):
f = open(fname, 'r')
d = {}
for l in f.readlines():
k, v = l.split('=', 1)
d[k.strip()] = v.strip(" \n'")
return d
def read_inventory():
return read_dict_file(inventory_file)
def read_management_conf():
return read_dict_file(management_conf)
def write_inventory(inventory):
f = open(inventory_file, 'w')
for k in inventory:
f.write(k + "='" + inventory[k] + "'\n")
f.close()
def valid_vlan(vlan):
if not re.match('\d+$', vlan):
return False
if int(vlan)<0 or int(vlan)>=4095:
return False
return True
class NetworkResetDialogue(Dialogue):
def __init__(self):
Dialogue.__init__(self)
data = Data.Inst()
data.Update() # Pick up current 'connected' states
choiceDefs = []
# Determine pool role
self.master_ip = None
f = open(pool_conf, 'r')
try:
l = f.readline()
ls = l.split(':')
if ls[0] == 'slave':
self.master_ip = ls[1]
finally:
f.close()
try:
conf = read_management_conf()
self.device = conf['LABEL']
except:
self.device = "eth0"
try:
conf = read_management_conf()
self.vlan = conf['VLAN']
except:
self.vlan = ''
self.modeMenu = Menu(self, None, Lang("Select IP Address Configuration Mode"), [
ChoiceDef(Lang("DHCP"), lambda: self.HandleModeChoice('DHCP') ),
ChoiceDef(Lang("Static"), lambda: self.HandleModeChoice('STATIC') )
])
# Get best guess of current values
self.mode = 'DHCP'
self.IP = '0.0.0.0'
self.netmask = '0.0.0.0'
self.gateway = '0.0.0.0'
self.dns = '0.0.0.0'
self.ChangeState('INITIAL')
def BuildPane(self):
pane = self.NewPane(DialoguePane(self.parent))
pane.TitleSet(Lang("Emergency Network Reset"))
pane.AddBox()
def UpdateFieldsINITIAL(self):
pane = self.Pane()
pane.ResetFields()
pane.AddTitleField(Lang("!! WARNING !!"))
pane.AddWrappedTextField(Lang("This command will reboot the host and reset its network configuration."))
pane.NewLine()
pane.AddWrappedTextField(Lang("As part of this utility, VMs running on this host will be forcefully shutdown."))
pane.NewLine()
pane.AddWrappedTextField(Lang("Before continuing:"))
pane.AddWrappedTextField(Lang("- Where possible, cleanly shutdown VMs."))
pane.AddWrappedTextField(Lang("- Disable HA if this host is part of a resource pool with HA enabled."))
pane.AddKeyHelpField( { Lang("<Enter>") : Lang("Continue"), Lang("<Esc>") : Lang("Cancel") } )
def UpdateFieldsDEVICE(self):
pane = self.Pane()
pane.ResetFields()
pane.AddTitleField(Lang("Enter the Primary Management Interface to be used after reset"))
pane.AddInputField(Lang("Device name", 18), self.device, 'device')
pane.AddInputField(Lang("VLAN (Optional)", 18), self.vlan, 'vlan')
pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel") } )
if pane.InputIndex() is None:
pane.InputIndexSet(0) # Activate first field for input
def UpdateFieldsMODE(self):
pane = self.Pane()
pane.ResetFields()
pane.AddTitleField(Lang("Select the IP configuration mode to be used after reset"))
pane.AddMenuField(self.modeMenu)
pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel") } )
def UpdateFieldsMASTERIP(self):
pane = self.Pane()
pane.ResetFields()
pane.AddTitleField(Lang("Specify Pool Master's IP Address"))
pane.AddWrappedTextField(Lang("The host is a pool slave."))
pane.AddWrappedTextField(Lang("Please confirm or correct the IP address of the pool master."))
pane.NewLine()
pane.AddInputField(Lang("IP Address", 14), self.master_ip, 'master_ip')
pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel") } )
if pane.CurrentInput() is None:
pane.InputIndexSet(0)
def UpdateFieldsSTATICIP(self):
pane = self.Pane()
pane.ResetFields()
pane.AddTitleField(Lang("Enter static IP address configuration"))
pane.AddInputField(Lang("IP Address", 14), self.IP, 'IP')
pane.AddInputField(Lang("Netmask", 14), self.netmask, 'netmask')
pane.AddInputField(Lang("Gateway", 14), self.gateway, 'gateway')
pane.AddInputField(Lang("DNS Server", 14), self.dns, 'dns')
pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel") } )
if pane.InputIndex() is None:
pane.InputIndexSet(0) # Activate first field for input
def UpdateFieldsPRECOMMIT(self):
pane = self.Pane()
pane.ResetFields()
pane.AddWrappedTextField(Lang("Press <Enter> to reset the network configuration."))
pane.AddWrappedTextField(Lang("This will cause the host to reboot."))
pane.NewLine()
pane.AddWrappedTextField(Lang("The Primary Management Interface will be reconfigured with the following settings:"))
pane.AddStatusField(Lang("NIC", 16), self.device)
if self.vlan != '':
pane.AddStatusField(Lang("VLAN", 16), self.vlan)
pane.AddStatusField(Lang("IP Mode", 16), self.mode)
if self.mode == 'static':
pane.AddStatusField(Lang("IP Address", 16), self.IP)
pane.AddStatusField(Lang("Netmask", 16), self.netmask)
pane.AddStatusField(Lang("Gateway", 16), self.gateway)
pane.AddStatusField(Lang("DNS Server", 16), self.dns)
pane.AddKeyHelpField( { Lang("<Enter>") : Lang("Apply Changes and Reboot"), Lang("<Esc>") : Lang("Cancel") } )
def UpdateFields(self):
self.Pane().ResetPosition()
getattr(self, 'UpdateFields'+self.state)() # Despatch method named 'UpdateFields'+self.state
def ChangeState(self, inState):
self.state = inState
self.BuildPane()
self.UpdateFields()
def HandleKeyINITIAL(self, inKey):
handled = True
pane = self.Pane()
if inKey == 'KEY_ENTER':
self.ChangeState('DEVICE')
elif inKey == 'KEY_ESCAPE':
handled = False
else:
pass # Leave handled as True
return handled
def HandleKeyDEVICE(self, inKey):
handled = True
pane = self.Pane()
if inKey == 'KEY_ENTER':
if pane.IsLastInput():
inputValues = pane.GetFieldValues()
self.device = inputValues['device']
self.vlan = inputValues['vlan']
if self.device == "":
pane.InputIndexSet(None)
Layout.Inst().PushDialogue(InfoDialogue(Lang('Invalid device name')))
elif (self.vlan != '') and not valid_vlan(self.vlan):
pane.InputIndexSet(None)
Layout.Inst().PushDialogue(InfoDialogue(Lang('VLAN tag must be between 0 and 4094')))
else:
self.ChangeState('MODE')
else:
pane.ActivateNextInput()
elif inKey == 'KEY_TAB':
pane.ActivateNextInput()
elif inKey == 'KEY_BTAB':
pane.ActivatePreviousInput()
elif pane.CurrentInput().HandleKey(inKey):
pass # Leave handled as True
else:
handled = False
return handled
def HandleKeyMODE(self, inKey):
return self.modeMenu.HandleKey(inKey)
def HandleKeyMASTERIP(self, inKey):
handled = True
pane = self.Pane()
if pane.CurrentInput() is None:
pane.InputIndexSet(0)
if inKey == 'KEY_ENTER':
inputValues = pane.GetFieldValues()
self.master_ip = inputValues['master_ip']
try:
failedName = Lang('Master IP')
IPUtils.AssertValidIP(self.master_ip)
self.ChangeState('PRECOMMIT')
except:
pane.InputIndexSet(None)
Layout.Inst().PushDialogue(InfoDialogue(Lang('Invalid ')+failedName))
elif pane.CurrentInput().HandleKey(inKey):
pass # Leave handled as True
else:
handled = False
return handled
def HandleKeySTATICIP(self, inKey):
handled = True
pane = self.Pane()
if inKey == 'KEY_ENTER':
if pane.IsLastInput():
inputValues = pane.GetFieldValues()
self.IP = inputValues['IP']
self.netmask = inputValues['netmask']
self.gateway = inputValues['gateway']
self.dns = inputValues['dns']
try:
failedName = Lang('IP Address')
IPUtils.AssertValidIP(self.IP)
failedName = Lang('Netmask')
IPUtils.AssertValidNetmask(self.netmask)
failedName = Lang('Gateway')
IPUtils.AssertValidIP(self.gateway)
failedName = Lang('DNS Server')
IPUtils.AssertValidIP(self.dns)
if self.master_ip == None:
self.ChangeState('PRECOMMIT')
else:
self.ChangeState('MASTERIP')
except:
pane.InputIndexSet(None)
Layout.Inst().PushDialogue(InfoDialogue(Lang('Invalid ')+failedName))
else:
pane.ActivateNextInput()
elif inKey == 'KEY_TAB':
pane.ActivateNextInput()
elif inKey == 'KEY_BTAB':
pane.ActivatePreviousInput()
elif pane.CurrentInput().HandleKey(inKey):
pass # Leave handled as True
else:
handled = False
return handled
def HandleKeyPRECOMMIT(self, inKey):
handled = True
pane = self.Pane()
if inKey == 'KEY_ENTER':
self.Commit()
# Reboot
Layout.Inst().ExitBannerSet(Lang("Rebooting..."))
Layout.Inst().ExitCommandSet('mount -o remount, ro /')
Layout.Inst().ExitCommandSet('/sbin/reboot -f')
XSLog('Initiating reboot')
else:
handled = False
return handled
def HandleKey(self, inKey):
handled = False
if hasattr(self, 'HandleKey'+self.state):
handled = getattr(self, 'HandleKey'+self.state)(inKey)
if not handled and inKey == 'KEY_ESCAPE':
Layout.Inst().PopDialogue()
handled = True
return handled
def HandleModeChoice(self, inChoice):
if inChoice == 'DHCP':
self.mode = 'dhcp'
if self.master_ip == None:
self.ChangeState('PRECOMMIT')
else:
self.ChangeState('MASTERIP')
else:
self.mode = 'static'
self.ChangeState('STATICIP')
def Commit(self):
# Update master's IP, if needed and given
if self.master_ip != None:
f = open(pool_conf, 'w')
try:
f.write('slave:' + self.master_ip)
finally:
f.close()
# Construct bridge name for management interface based on convention
if self.device[:3] == 'eth':
bridge = 'xenbr' + self.device[3:]
else:
bridge = 'br' + self.device
# Ensure xapi is not running
os.system('service xapi stop >/dev/null 2>/dev/null')
# Reconfigure new management interface
if os.access('/tmp/do-not-use-networkd', os.F_OK):
if_args = ' --force ' + bridge + ' rewrite --mac=x --device=' + self.device + ' --mode=' + self.mode
if self.mode == 'static':
if_args += ' --ip=' + self.IP + ' --netmask=' + self.netmask
if self.gateway != '':
if_args += ' --gateway=' + self.gateway
os.system(interface_reconfigure + if_args + ' >/dev/null 2>/dev/null')
else:
os.system('service xcp-networkd stop >/dev/null 2>/dev/null')
try: os.remove('/var/xapi/networkd.db')
except: pass
# Update interfaces in inventory file
inventory = read_inventory()
if self.vlan:
inventory['MANAGEMENT_INTERFACE'] = 'xentemp'
else:
inventory['MANAGEMENT_INTERFACE'] = bridge
inventory['CURRENT_INTERFACES'] = ''
write_inventory(inventory)
ipv6 = self.IP.find(':') > -1
# Rewrite firstboot management.conf file, which will be picked it by xcp-networkd on restart (if used)
f = open(management_conf, 'w')
try:
f.write("LABEL='" + self.device + "'\n")
f.write(("MODEV6" if ipv6 else "MODE") + "='" + self.mode + "'\n")
if self.vlan != '':
f.write("VLAN='" + self.vlan + "'\n")
if self.mode == 'static':
if ipv6:
f.write("IPv6='" + self.IP + "/" + self.netmask + "'\n")
else:
f.write("IP='" + self.IP + "'\n")
f.write("NETMASK='" + self.netmask + "'\n")
if self.gateway != '':
f.write(("IPv6_GATEWAY" if ipv6 else "GATEWAY") + "='" + self.gateway + "'\n")
if self.dns != '':
f.write("DNS='" + self.dns + "'\n")
finally:
f.close()
# Write trigger file for XAPI to continue the network reset on startup
f = open(network_reset, 'w')
try:
f.write('DEVICE=' + self.device + '\n')
f.write(('MODE_V6' if ipv6 else 'MODE') + '=' + self.mode + '\n')
if self.vlan != '':
f.write('VLAN=' + self.vlan + '\n')
if self.mode == 'static':
if ipv6:
f.write('IPV6=' + self.IP + '/' + self.netmask + '\n')
else:
f.write('IP=' + self.IP + '\n')
f.write('NETMASK=' + self.netmask + '\n')
if self.gateway != '':
f.write(('GATEWAY_V6' if ipv6 else 'GATEWAY') + '=' + self.gateway + '\n')
if self.dns != '':
f.write('DNS=' + self.dns + '\n')
finally:
f.close()
# Reset the domain 0 network interface naming configuration
# back to a fresh-install state for the currently-installed
# hardware.
os.system("/etc/sysconfig/network-scripts/interface-rename.py --reset-to-install")
class XSFeatureNetworkReset:
@classmethod
def StatusUpdateHandler(cls, inPane):
data = Data.Inst()
warning = """This command will reboot the host and reset its network configuration.
As part of this utility all running VMs will be forcefully shutdown.
Before running this command:
- Shutdown running VMs.
- Disable HA if enabled on the pool."""
inPane.AddTitleField(Lang("Emergency Network Reset"))
inPane.AddWrappedTextField(warning)
inPane.AddKeyHelpField( {
Lang("<Enter>") : Lang("Reset Networking")
} )
@classmethod
def ActivateHandler(cls):
DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(NetworkResetDialogue()))
def Register(self):
Importer.RegisterNamedPlugIn(
self,
'EMERGENCY_NETWORK_RESET', # Key of this plugin for replacement, etc.
{
'menuname' : 'MENU_NETWORK',
'menupriority' : 800,
'menutext' : Lang('Emergency Network Reset') ,
'needsauth' : False,
'statusupdatehandler' : XSFeatureNetworkReset.StatusUpdateHandler,
'activatehandler' : XSFeatureNetworkReset.ActivateHandler
}
)
# Register this plugin when module is imported
XSFeatureNetworkReset().Register()