forked from CiscoDevNet/startnow-Intro-to-Python-buildpacks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
231 lines (220 loc) · 8.26 KB
/
main.py
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
#!/usr/bin/env python
"""
Main python file that calls app.aci_conn.ConnectACI
"""
import datetime
import argparse
import json
import os
import sys
from urllib.parse import urlparse
from app.aci_conn import ConnectACI
import app.aci_webex as webex
def main(url, username, password, webex_token=None, webex_room=None):
"""
POST logins into APIC and Prints Status Update
Arguments:
url (str): url of APIC
username (str): APIC api username
password (str): APIC api password
message (str): Str message to be sent
webex_token (cls): Api token for future requests
webex_room (str): Name of webex room
webex_email (str): Email to be added to the webex room
return: None
"""
aci = ConnectACI(url, username, password)
tenants = aci.get_tenant()['imdata']
tenant_count = len(tenants)
health = aci.get_aci_health()
old_tenants = get_old_tenant()
webex_card = create_webex_card(aci.username, tenants, tenant_count, health,old_tenants)
if webex_token:
token = webex.get_webex_token(webex_token)
webex.send_webex_message(token, webex_room=webex_room, webex_card=webex_card)
else:
get_aci_stats(aci.username, tenant_count, tenants,
health, old_tenants)
update_log(tenants)
def get_aci_stats(name, tenant_count, tenants, health, old_tenants):
"""
POST logins into APIC and Prints Status Update
Arguments:
name (str): APIC username
tenant_count (int): Number of ACI tenants
tenants (dict): ACI tenant dict
health (dict): ACI health dict
old_tenants (list): List of logged ACI tenants
current_time (str): Today's datetime
return: None
"""
current_time = get_date()
null_tenant = 0
print("\n")
print("#" * 10 + " APIC STATUS UPDATE " + "#" * 13)
print(f" ✅ {name} Logged in at: " + current_time + "\n")
print("\n- FabricOverallHealth:")
if len(health['imdata']) > 0:
print(" " * 12 +
"healthAvg: "\
f"{health['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthAvg']}")
print(" " * 12 +
"healthMax: "\
f"{health['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthMax']}")
print(" " * 12 +
"healthMin: "\
f"{health['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthMin']}\n")
else:
print(" " * 12 + "Data Not Found")
print("- List of New Tenants: ")
for i in tenants:
if i['fvTenant']['attributes']['name'] not in old_tenants:
print(" " * 12 + f"{i['fvTenant']['attributes']['name']} **NEW-TENANT**")
null_tenant += 1
else:
print(" " * 12 + f"{i['fvTenant']['attributes']['name']}")
if null_tenant == 0:
print(" " * 12 + "*NO NEW TENANTS*\n")
print(f"- Tentant Count: {tenant_count}")
print("#" * 44 + "\n")
def create_webex_card(aci_username, tenants, tenant_count, health, old_tenants):
"""
Method creates adaptive card for webex message
Arguments:
aci_username (str): APIC username
tenants (dict): ACI tenant dict
tenant_count (int): Number of ACI tenants
health (dict): ACI health dict
return: Adaptive card Dict
rtype: dict
"""
now = datetime.datetime.now()
fabric_health = [
{
"title": "Logged by :",
"value": str(aci_username)
},
{
"title": "Health Avg : ",
"value": str(f"{health['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthAvg']}")
},
{
"title": "Health Max : ",
"value": str(f"{health['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthMax']}")
},
{
"title": "Health Min : ",
"value": str(f"{health['imdata'][0]['fabricOverallHealthHist5min']['attributes']['healthMin']}")
},
{
"title": "Tenant Count :",
"value": str(tenant_count)
}
]
tenant_list = [
{
"type": "TextBlock",
"text": "DevNet Sandbox ACI Tenants",
"horizontalAlignment": "Left",
"spacing": "None",
"size": "Large",
"color": "Attention",
"wrap": True
}
]
today = f'Created {now.strftime("%d-%B-%Y")}'
with open("./cards/card.json") as temp_v:
cards = json.load(temp_v)
cards[0]['content']['body'][1]['items'][1]['facts'] = fabric_health
cards[0]['content']['body'][0]['items'][1]['columns'][1]['items'][1]['text'] = today
for i in tenants:
tenant_list.append({
"type": "TextBlock",
"text": str(i['fvTenant']['attributes']['name']),
"horizontalAlignment": "Left",
"spacing": "None",
"size": "medium",
"wrap": True
}
)
cards[0]['content']['body'][2]['columns'][0]['items'] = tenant_list
return cards
def get_old_tenant():
"""
Method returns list of logged ACI Tenants
rtype: list
"""
old_tenants = []
with open("tenant_log.txt", "r") as file:
old_tenants = file.read().splitlines()
return old_tenants
def update_log(tenants):
"""
Method updates tenant_log.txt
Arguments:
tenants (str):
"""
with open("tenant_log.txt", "w") as file:
for tenant in tenants:
file.write(f"{tenant['fvTenant']['attributes']['name']}\n")
def get_date():
"""
GET Current Date and Time
return: Date/time '03-05-2021 12:04'
rtype: str
"""
return datetime.datetime.now().strftime("%d-%B-%Y")
def validate_url(url):
"""
Method validates http url
Arguments:
url (str): Address of APIC 'http://' or 'https://'
rtype: None
"""
valid_url = {"http", "https"}
result = urlparse(url)
if result.scheme not in valid_url:
sys.exit("Please enter APIC url in 'http(s)://www.cisco.com' format.")
if __name__ == "__main__":
# Argparse grabs commandline arguments
# Defaults to DevNet ACI Always on Sandbox Creds
parser = argparse.ArgumentParser(description="Arguments: url, username, password,"\
" webex_token, webex_room")
parser.add_argument("--url", help="Optional argument to pass url or ip of APIC"\
"\nDefault: 'https://sandboxapicdc.cisco.com'")
parser.add_argument("--username", help="Optional argument to pass username for APIC user"\
"\nDefault: 'admin'")
parser.add_argument("--password", help="Optional argument to pass password for FMC user"\
"\nDefault: 'ciscopsdt'")
parser.add_argument("--webex_token", help="Optional argument to pass webex api token")
parser.add_argument("--webex_room", help="Optional argument to pass webex room name"\
"\n***NOTE*** arg must be passed with token")
args = parser.parse_args()
args = vars(args)
if args['url'] is None:
if 'url' in os.environ:
args['url'] = os.environ['url']
else:
args['url'] = "https://sandboxapicdc.cisco.com"
validate_url(args['url'])
if args['username'] is None:
if 'username' in os.environ:
args['username'] = os.environ['username']
else:
args['username'] = "admin"
if args['password'] is None:
if 'password' in os.environ:
args["password"] = os.environ['password']
else:
args['password'] = "ciscopsdt"
if args['webex_token'] is None:
if 'webex_token' in os.environ:
args['webex_token'] = os.environ['webex_token']
if args['webex_token']:
if args['webex_room'] is None:
if 'webex_room' in os.environ:
args['webex_room'] = os.environ['webex_room']
else:
print("Please pass in 'webex_token' and 'webex_room' args")
sys.exit("For more info see 'main.py --help'")
main(**args)