Debian Codegraph @

docs/labs/lab06-provisioning/mlag_issu.py

raw
1 #!/usr/bin/env python3
2 #
3 # python3 mlag_issu <upgrade inventory file> <MLAG peer to upgrade: 'peer1' or 'peer2'>"
4 #
5 # # Example of upgrade inventory file (YAML)
6 # cvp_hosts:
7 # - 192.168.0.191
8 # - 192.168.0.192
9 # - 192.168.0.193
10 # cvp_username: cvpadmin
11 # target_eos_version: 4.25.4M
12 # target_terminattr_version: 1.13.6
13 # mlag_couples:
14 # - peer1: leaf101-1
15 # peer2: leaf101-2
16 # - peer1: leaf102-1
17 # peer2: leaf102-2
18 #
19 # Note: upgrades are performed in parallel
20
21 import sys
22 import time
23 from getpass import getpass
24 import requests
25 from requests.packages.urllib3.exceptions import InsecureRequestWarning
26 from datetime import datetime
27 from cvprac.cvp_client import CvpClient
28 from cvprac.cvp_client_errors import CvpLoginError, CvpApiError
29 from pprint import pprint
30 from operator import itemgetter
31 import yaml
32
33 class CvpDeviceUpgrader(object):
34 def __init__(self, hosts, username, password):
35 requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
36 self.cvp_hosts = hosts
37 self.cvp_user = username
38 self.cvp_password = password
39 self.session = self._open_cvp_session()
40
41 def _open_cvp_session(self):
42 try:
43 client = CvpClient()
44 client.connect(
45 nodes=self.cvp_hosts,
46 username=self.cvp_user,
47 password=self.cvp_password,
48 request_timeout=300,
49 connect_timeout=30
50 )
51 return(client)
52 except CvpLoginError as e:
53 print(f"Cannot connect to CVP API: {e}")
54 exit()
55
56 def create_mlag_issu_change_control(self, taskIDs, deviceIDs):
57 cc_id = f"CC_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
58 cc_name = f"Change Control {cc_id}"
59
60 stages = {
61 'root': {
62 'name': f"{cc_name} Root",
63 'rows': {'values': [
64 {'values': [f"preU_{cc_id}"]},
65 {'values': [f"U_{cc_id}"]},
66 {'values': [f"postU_{cc_id}"]},
67 ]},
68 },
69 f"preU_{cc_id}": {
70 'name': 'pre_upgrade',
71 'rows': {'values': [
72 {'values': [f"preU_{cc_id}_{i}" for i in range(len(deviceIDs))]},
73 ]},
74 },
75 f"U_{cc_id}": {
76 'name': 'upgrade',
77 'rows': {'values': [
78 {'values': [f"U_{cc_id}_{i}" for i in range(len(taskIDs))]},
79 ]},
80 },
81 f"postU_{cc_id}": {
82 'name': 'post_upgrade',
83 'rows': {'values': [
84 {'values': [f"postU_{cc_id}_{i}" for i in range(len(deviceIDs))]},
85 ]},
86 },
87 }
88
89 for i, device_id in enumerate(deviceIDs):
90 stages[f"preU_{cc_id}_{i}"] = {
91 'name': 'Check MLAG Health',
92 'action': {
93 'name': 'mlaghealthcheck',
94 'timeout': 0,
95 'args': {'values': {'DeviceID': device_id}},
96 },
97 }
98 stages[f"postU_{cc_id}_{i}"] = {
99 'name': 'Check MLAG Health',
100 'action': {
101 'name': 'mlaghealthcheck',
102 'timeout': 0,
103 'args': {'values': {'DeviceID': device_id}},
104 },
105 }
106
107 for i, task_id in enumerate(taskIDs):
108 stages[f"U_{cc_id}_{i}"] = {
109 'name': 'Image Upgrade',
110 'action': {
111 'name': 'task',
112 'timeout': 3000,
113 'args': {'values': {'TaskID': task_id}},
114 },
115 }
116
117 custom_cc = {
118 'key': {'id': cc_id},
119 'change': {
120 'name': cc_name,
121 'notes': 'MLAG ISSU Change Control',
122 'rootStageId': 'root',
123 'stages': {'values': stages},
124 },
125 }
126 try:
127 res = self.session.api.change_control_create_with_custom_stages(custom_cc)
128 except Exception as e:
129 print(str(e))
130 return None
131 print(f"Change control {cc_id} created")
132 return cc_id
133
134 def get_mlag_issu_change_control_logs(self, ccID, startTime):
135 end_time = int(time.time() * 1000)
136 cc_logs_data = {'category': 'ChangeControl',
137 'objectKey': ccID,
138 'dataSize': 15000,
139 'startTime': startTime,
140 'endTime': end_time
141 }
142 logs = self.session.post('/cvpservice/audit/getLogs.do',
143 data=cc_logs_data,
144 timeout=self.session.api.request_timeout
145 )
146 for log in sorted(logs['data'], key=itemgetter('dateTimeInLongFormat')):
147 if log['subObjectName'] and 'Command(s)' not in log['activity']:
148 log_date = datetime.fromtimestamp(log['dateTimeInLongFormat']/1000)
149 print(f"{log_date} {log['subObjectName']}: {log['activity']}")
150 return(end_time + 1)
151
152 def run_mlag_issu_change_control(self, ccID):
153 print(f"Automatic approval of change control {ccID}")
154 self.session.api.change_control_approve(ccID, datetime.utcnow().isoformat() + 'Z')
155 time.sleep(2)
156 print(f"Starting the execution of change control {ccID}")
157 start_time = int(time.time() * 1000)
158 self.session.api.change_control_start(ccID)
159 time.sleep(2)
160 cc = self.session.api.change_control_get_one(ccID)
161 cc_status = cc['value']['status']
162 cc_error = cc['value'].get('error', '')
163 start_time = self.get_mlag_issu_change_control_logs(ccID, start_time)
164 while cc_status == 'CHANGE_CONTROL_STATUS_RUNNING':
165 time.sleep(30)
166 cc = self.session.api.change_control_get_one(ccID)
167 cc_status = cc['value']['status']
168 cc_error = cc['value'].get('error', '')
169 start_time = self.get_mlag_issu_change_control_logs(ccID, start_time)
170 print(f"Change control {ccID} final status: {cc_status}")
171 if cc_error:
172 print(f"Change control {ccID} had the following errors: {cc_error}")
173 else:
174 print(f"Change control {ccID} completed without errors")
175
176 def main():
177 if len(sys.argv) != 3:
178 print(f"Usage: python3 {sys.argv[0]} <input file path> <MLAG peer to upgrade: peer1/peer2>")
179 exit()
180 try:
181 with open(sys.argv[1], 'r') as yf:
182 params = yaml.safe_load(yf)
183 except Exception as e:
184 print(e)
185 exit()
186 cvp_password = getpass(prompt=f"CVP password for user {params['cvp_username']}: ")
187 cvpdu = CvpDeviceUpgrader(
188 hosts=params['cvp_hosts'],
189 username=params['cvp_username'],
190 password=cvp_password
191 )
192 image_bundle = None
193 for bundle in cvpdu.session.api.get_image_bundles()['data']:
194 eos_match = False
195 terminattr_match = False
196 for img in bundle['imageIds']:
197 if params['target_eos_version'] in img:
198 eos_match = True
199 elif params['target_terminattr_version'] in img:
200 terminattr_match = True
201 if eos_match and terminattr_match:
202 image_bundle = bundle
203 break
204 if image_bundle is None:
205 print(f"Cannot find an image bundle with EOS {params['target_eos_version']} and TerminAttr {params['target_terminattr_version']}")
206 exit()
207 hostnames = [couple[sys.argv[2]] for couple in params['mlag_couples']]
208 devices_to_upgrade = list()
209 inventory = cvpdu.session.api.get_inventory()
210 for hostname in hostnames:
211 provisioned = False
212 for dev in inventory:
213 if dev['hostname'] == hostname:
214 provisioned = True
215 devices_to_upgrade.append(dev)
216 break
217 if not provisioned:
218 print(f"Device with hostname {hostname} is not provisioned in CVP")
219 if not devices_to_upgrade:
220 print('none of the mentioned devices is provisioned in CVP')
221 exit()
222 print(f"Devices to upgrade: {', '.join([dev['hostname'] for dev in devices_to_upgrade])}")
223 task_ids = list()
224 for device in devices_to_upgrade:
225 response = cvpdu.session.api.apply_image_to_device(image_bundle, device)['data']
226 if response['status'] == 'success':
227 task_ids.extend(response['taskIds'])
228 device_ids = [device['serialNumber'] for device in devices_to_upgrade]
229 cc_id = cvpdu.create_mlag_issu_change_control(task_ids, device_ids)
230 if cc_id is None:
231 print('Failed to create the MLAG ISSU change control')
232 exit()
233 time.sleep(2)
234 cvpdu.run_mlag_issu_change_control(cc_id)
235
236 if __name__ == '__main__':
237 main()