-
Notifications
You must be signed in to change notification settings - Fork 1
/
port_status.py
executable file
·221 lines (184 loc) · 6.39 KB
/
port_status.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
#!/usr/bin/python
# Get server and port list from controller and
# extract IP addresses from the response.
# Then send ping to these IPs to check if the port is active.
# With this test, we can test if routing is correct.
# Result shows servers and ports failed getting ping response.
# Reference http://four-eyes.net/2012/11/openstack-api-python-script-example/
import argparse
import getopt
import json
import sys
import urllib2
import os
import environment as env
import datetime
def sendRequest(url, token=None, payload=None):
"""
Make a request and send request.
headers will be list of {key, value} dict.
Returns response.
"""
request = urllib2.Request(url)
request.add_header("Content-type", "application/json")
if token != None:
request.add_header("X-Auth-Token", token)
request = urllib2.urlopen(request, payload)
json_data = json.loads(request.read())
request.close()
return json_data
def getToken(url, user, tenant, password):
"""
Returns a token to the user given a tenant,
user name, password, and OpenStack API URL.
"""
url = url + '/tokens'
data = {
"auth":{
"tenantName": tenant,
"passwordCredentials":{
"username": user,
"password": password
}
}
}
jsonPayload = json.dumps(data)
return sendRequest(url, payload=jsonPayload)
def getPorts(url, token):
"""
Returns ports for the given tenant.
"""
url = url + '/v2.0/ports'
return sendRequest(url, token)
def getNetworks(url, token, interface):
"""
Returns network name list
"""
def _get_networks(url, token):
url = url + '/v2.0/networks'
return sendRequest(url, token)
def _return_net_type(network):
if network['name'].split('.')[-1] =='private':
return 'eth1'
return 'eth0'
networks = _get_networks(url, token)
networkNames = []
for network in networks['networks']:
net_type = _return_net_type(network)
if interface == None or interface == net_type:
networkNames.append(network['name'])
return networkNames
def getServers(url, token, hostname):
"""
Returns instances for the given tenant.
"""
url = url + '/servers/detail?all_tenants=1'
if hostname != None:
url = url + ('&host=%s') % hostname
return sendRequest(url, token)
def getActiveServers(url, token, hostname):
"""
Returns active instances for the given tenant.
"""
url = url + '/servers/detail?all_tenants=1&status=ACTIVE'
if hostname != None:
url = url + ('&host=%s') % hostname
result = sendRequest(url, token)
activeServers = []
for server in result['servers']:
if server['OS-EXT-STS:power_state'] == 1:
activeServers.append(server)
return {'servers': activeServers}
def getHypervisors(url, token):
"""
Returns hypervisor list.
"""
url = url + '/os-hypervisors'
return sendRequest(url, token)
def isValidHypervisor(hypervisors, hostname):
"""
Returns if the given hostname is valid.
"""
for hypervisor in hypervisors['hypervisors']:
if hypervisor['hypervisor_hostname'] == hostname:
return True
return False
def checkPortStatus(ip):
"""
Returns port active status with ping test.
"""
cmd = 'ping -c 1 -W 2 ' + ip
if os.system(cmd) == 0:
return "ACTIVE"
else:
return "DOWN"
def getPortStatus(ports):
"""
Returns status of all ports.
"""
downPorts = []
for port in ports['ports']:
for ip in port['fixed_ips']:
status = checkPortStatus(ip['ip_address'])
if status == "DOWN":
downPorts.append({'id': port['id'], 'ip': ip['ip_address']})
return downPorts
def getPortDownServers(servers, networks):
"""
Returns server port active status with ping test.
"""
downServers = []
for server in servers['servers']:
for network in networks:
try:
for ip in server['addresses'][network]:
status = checkPortStatus(ip['addr'])
if status == "DOWN":
downServers.append({"id": server['id'], "name": server['name'], "ip": ip['addr']})
except KeyError:
# Pass if the network is not allocated for the VM
continue
return downServers
# Build our required arguments list
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--cnode", help="Full hostname of cnode to check,\
all ports will be return if not specified.", type=str)
parser.add_argument("-i", "--interface", help="Full hostname of cnode to check.", type=str)
args = parser.parse_args()
# Get admin token
adminToken = getToken(env.AUTH_URL, env.USERNAME, env.TENANT, env.PASSWORD)
adminTokenID = adminToken['access']['token']['id']
adminTokenTenantID = adminToken['access']['token']['tenant']['id']
# Get Quantum service endpoint
for item in adminToken['access']['serviceCatalog']:
if item['name'] == "quantum":
adminQuantumURL = item['endpoints'][0]['adminURL']
if item['name'] == "nova":
adminNovaURL = item['endpoints'][0]['adminURL']
# Validate arugments were given
hypervisors = getHypervisors(adminNovaURL, adminTokenID)
if args.cnode != None and (type(args.cnode) != type(str()) or
isValidHypervisor(hypervisors, args.cnode) == False):
sys.stderr.write('Invalid conde: %s\n\n' % args.cnode)
parser.print_help()
sys.exit(2)
if args.interface != None and (args.interface != 'eth0' and
args.interface != 'eth1'):
sys.stderr.write('Invalid interface name: %s\n\n' % args.interface)
parser.print_help()
sys.exit(2)
# Get servers for given tenant
servers = getActiveServers(adminNovaURL, adminTokenID, args.cnode)
networks = getNetworks(adminQuantumURL, adminTokenID, args.interface)
portDownServers = getPortDownServers(servers, networks)
#ports = getPorts(adminQuantumURL, adminTokenID)
#downPorts = getPortStatus(ports)
print ""
print "==================== PORT DOWN SERVERS: ", args.cnode, "======================="
f = open('/var/lib/port_status.log', 'a')
for server in portDownServers:
data = "[%s] Server ID:%s Name:%s IP:%s\n" % (datetime.datetime.now(), server['id'], server['name'], server['ip'])
print data
f.write(data)
f.close()
print ""