90c292bcd397be2858d38eadea17047129b40b13
[releng.git] / utils / lab-reconfiguration / reconfigUcsNet.py
1 #!/usr/bin/python
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #  http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 # This script reconfigure UCSM vnics for varios OPNFV deployers
15 # Usage: reconfigUcsNet.py [options]
16 #
17 # Options:
18 # -h, --help            show this help message and exit
19 # -i IP, --ip=IP        [Mandatory] UCSM IP Address
20 # -u USERNAME, --username=USERNAME
21 #                       [Mandatory] Account Username for UCSM Login
22 # -p PASSWORD, --password=PASSWORD
23 #                       [Mandatory] Account Password for UCSM Login
24 # -f FILE, --file=FILE
25 #                       [Optional] Yaml file with network config you want to set for POD
26 #                       If not present only current network config will be printed
27 #
28
29 import getpass
30 import optparse
31 import platform
32 import yaml
33 import time
34 import sys
35 from UcsSdk import *
36 from collections import defaultdict
37
38 POD_PREFIX = "POD-2"
39 INSTALLER = "POD-21"
40
41 def getpassword(prompt):
42     if platform.system() == "Linux":
43         return getpass.unix_getpass(prompt=prompt)
44     elif platform.system() == "Windows" or platform.system() == "Microsoft":
45         return getpass.win_getpass(prompt=prompt)
46     else:
47         return getpass.getpass(prompt=prompt)
48
49
50 def get_servers(handle=None):
51     """
52     Return list of servers
53     """
54     orgObj = handle.GetManagedObject(None, OrgOrg.ClassId(), {OrgOrg.DN : "org-root"})[0]
55     servers = handle.GetManagedObject(orgObj, LsServer.ClassId())
56     for server in servers:
57         if server.Type == 'instance' and POD_PREFIX in server.Dn:
58             yield server
59
60
61 def set_boot_policy(handle=None, server=None, policy=None):
62     """
63     Modify Boot policy of server
64     """
65     obj = handle.GetManagedObject(None, LsServer.ClassId(), {
66             LsServer.DN: server.Dn})
67     handle.SetManagedObject(obj, LsServer.ClassId(), {
68             LsServer.BOOT_POLICY_NAME: policy} )
69     print " Configured boot policy: {}".format(policy)
70
71
72 def ack_pending(handle=None, server=None):
73     """
74     Acknowledge pending state of server
75     """
76     handle.AddManagedObject(server, LsmaintAck.ClassId(), {
77             LsmaintAck.DN: server.Dn + "/ack",
78             LsmaintAck.DESCR:"",
79             LsmaintAck.ADMIN_STATE:"trigger-immediate",
80             LsmaintAck.SCHEDULER:"",
81             LsmaintAck.POLICY_OWNER:"local"}, True)
82     print " Pending-reboot -> Acknowledged."
83
84
85 def get_vnics(handle=None, server=None):
86     """
87     Return list of vnics for given server
88     """
89     vnics = handle.ConfigResolveChildren(VnicEther.ClassId(), server.Dn, None, YesOrNo.TRUE)
90     return vnics.OutConfigs.GetChild()
91
92
93 def get_network_config(handle=None):
94     """
95     Print current network config
96     """
97     print "\nCURRENT NETWORK CONFIG:"
98     print " d - default, t - tagged"
99     for server in get_servers(handle):
100         print ' {}'.format(server.Name)
101         print '  Boot policy: {}'.format(server.OperBootPolicyName)
102         for vnic in get_vnics(handle, server):
103             print '  {}'.format(vnic.Name)
104             print '   {}'.format(vnic.Addr)
105             vnicIfs = handle.ConfigResolveChildren(VnicEtherIf.ClassId(), vnic.Dn, None, YesOrNo.TRUE)
106             for vnicIf in vnicIfs.OutConfigs.GetChild():
107                 if vnicIf.DefaultNet == 'yes':
108                     print '    Vlan: {}d'.format(vnicIf.Vnet)
109                 else:
110                     print '    Vlan: {}t'.format(vnicIf.Vnet)
111
112
113 def add_interface(handle=None, lsServerDn=None, vnicEther=None, templName=None, order=None, macAddr=None):
114     """
115     Add interface to server specified by server.DN name
116     """
117     print " Adding interface: {}, template: {}, server.Dn: {}".format(vnicEther, templName, lsServerDn)
118     obj = handle.GetManagedObject(None, LsServer.ClassId(), {LsServer.DN:lsServerDn})
119     vnicEtherDn = lsServerDn + "/ether-" + vnicEther
120     params = {
121         VnicEther.STATS_POLICY_NAME: "default",
122         VnicEther.NAME: vnicEther,
123         VnicEther.DN: vnicEtherDn,
124         VnicEther.SWITCH_ID: "A-B",
125         VnicEther.ORDER: order,
126         "adminHostPort": "ANY",
127         VnicEther.ADMIN_VCON: "any",
128         VnicEther.ADDR: macAddr,
129         VnicEther.NW_TEMPL_NAME: templName,
130         VnicEther.MTU: "1500"}
131     handle.AddManagedObject(obj, VnicEther.ClassId(), params, True)
132
133
134 def remove_interface(handle=None, vnicEtherDn=None):
135     """
136     Remove interface specified by Distinguished Name (vnicEtherDn)
137     """
138     print " Removing interface: {}".format(vnicEtherDn)
139     obj = handle.GetManagedObject(None, VnicEther.ClassId(), {VnicEther.DN:vnicEtherDn})
140     handle.RemoveManagedObject(obj)
141
142
143 def read_yaml_file(yamlFile):
144     """
145     Read vnic config from yaml file
146     """
147     # TODO: add check if vnic templates specified in file exist on UCS
148     with open(yamlFile, 'r') as stream:
149         return yaml.load(stream)
150
151
152 def set_network(handle=None, yamlFile=None):
153     """
154     Configure VLANs on POD according specified network
155     """
156     # add interfaces and bind them with vNIC templates
157     print "\nRECONFIGURING VNICs..."
158     pod_data = read_yaml_file(yamlFile)
159     network = pod_data['network']
160
161     for index, server in enumerate(get_servers(handle)):
162         # Assign template to interface
163         for iface, data in network.iteritems():
164             add_interface(handle, server.Dn, iface, data['template'], data['order'], data['mac-list'][index])
165
166         # Remove other interfaces which have not assigned required vnic template
167         vnics = get_vnics(handle, server)
168         for vnic in vnics:
169             if not any(data['template'] in vnic.OperNwTemplName for iface, data in network.iteritems()):
170                 remove_interface(handle, vnic.Dn)
171                 print "  {} removed, template: {}".format(vnic.Name, vnic.OperNwTemplName)
172
173         # Set boot policy template
174         if not INSTALLER in server.Dn:
175             set_boot_policy(handle, server, pod_data['boot-policy'])
176
177
178 if __name__ == "__main__":
179     # Latest urllib2 validate certs by default
180     # The process wide "revert to the old behaviour" hook is to monkeypatch the ssl module
181     # https://bugs.python.org/issue22417
182     import ssl
183     if hasattr(ssl, '_create_unverified_context'):
184         ssl._create_default_https_context = ssl._create_unverified_context
185     try:
186         handle = UcsHandle()
187         parser = optparse.OptionParser()
188         parser.add_option('-i', '--ip',dest="ip",
189                         help="[Mandatory] UCSM IP Address")
190         parser.add_option('-u', '--username',dest="userName",
191                         help="[Mandatory] Account Username for UCSM Login")
192         parser.add_option('-p', '--password',dest="password",
193                         help="[Mandatory] Account Password for UCSM Login")
194         parser.add_option('-f', '--file',dest="yamlFile",
195                         help="[Optional] Yaml file contains network config you want to set on UCS POD1")
196         (options, args) = parser.parse_args()
197
198         if not options.ip:
199             parser.print_help()
200             parser.error("Provide UCSM IP Address")
201         if not options.userName:
202             parser.print_help()
203             parser.error("Provide UCSM UserName")
204         if not options.password:
205             options.password=getpassword("UCSM Password:")
206
207         handle.Login(options.ip, options.userName, options.password)
208
209         # Change vnic template if specified in cli option
210         if (options.yamlFile != None):
211             set_network(handle, options.yamlFile)
212             time.sleep(5)
213
214         print "\nWait until Overall Status of all nodes is OK..."
215         timeout = time.time() + 60*10   #10 minutes timeout
216         while True:
217             list_of_states = []
218             for server in get_servers(handle):
219                 if server.OperState == "pending-reboot":
220                     ack_pending(handle,server)
221                 list_of_states.append(server.OperState)
222             print " {}, {} seconds remains.".format(list_of_states, round(timeout-time.time()))
223             if all(state == "ok" for state in list_of_states):
224                 break
225             if time.time() > timeout:
226                 raise Exception("Timeout reached while waiting for OK status.")
227             time.sleep(5)
228
229         # Show current vnic MACs and VLANs
230         get_network_config(handle)
231
232         handle.Logout()
233
234     except Exception, err:
235         handle.Logout()
236         print "Exception:", str(err)
237         import traceback, sys
238         print '-'*60
239         traceback.print_exc(file=sys.stdout)
240         print '-'*60
241         sys.exit(1)