-
Notifications
You must be signed in to change notification settings - Fork 4
/
cdn_report.py
executable file
·283 lines (196 loc) · 7.53 KB
/
cdn_report.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
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
#! /usr/bin/python3
# This script queries the Red Hat Content delivery Network and reports on
# system and entitlement usage
#
# Author: John Herr
#
import json,sys
import time
import argparse
import requests
from datetime import datetime
from natsort import natsorted
consumer = {}
pool = {}
poolusage = {}
hosts = {}
consumersortlist = []
duplicatesortlist = []
usagesortlist = []
requests.packages.urllib3.disable_warnings()
parser = argparse.ArgumentParser(description="Query Red Hat CDN")
parser.add_argument('--checkin', action='store_true', help = 'Display days since host checkin')
parser.add_argument('--days', type=int, help = 'Display hosts who have not checked in within this number of days or longer.')
parser.add_argument('--duplicates', action='store_true', help = 'Display information about duplicate hosts')
parser.add_argument('--reverse', action='store_true', help = 'Reverse the sort order of output')
parser.add_argument('--user', required=True, help = 'CDN user account name. Required option.')
parser.add_argument('--password', required=True, help = 'CDN user account password. Required option.')
parser.add_argument('--ownerid', required=True, help = 'The org id of the CDN user, can be retrieved using the "subscription-manager identity" command on a registered system. Required option.')
parser.add_argument('--silent', action='store_true', help = 'Just print the data, no headers or information about what we are doing.')
cliopts = parser.parse_args()
if cliopts.reverse:
reverse_sort = True
else:
reverse_sort = False
def print_checkin():
# Print Checkin Report
#
if not cliopts.silent:
print("{:70} | {:^36} | {:^20} | {:^12}".format(
"Host",
"ID",
"Last Checking (Days)",
"Entitlements Consumed",
)
)
print("\n" + '-' * 156)
if not cliopts.days:
days = 0
else:
days = cliopts.days
for sitem in natsorted(consumersortlist, reverse=reverse_sort):
item = sitem.split()[1]
if consumer[item]["checkin"] >= days:
print("{:70} | {:36} | {!s:20} | {:12}".format(
consumer[item]["name"],
consumer[item]["uuid"],
consumer[item]["checkin"],
consumer[item]["entitlementcount"],
)
)
def print_pool_usage():
## Print Pool usage
#
if not cliopts.silent:
print("{:^110} | {:^34} | {:^12} | {:^8} | {:^8}".format(
"Name",
"Pool ID",
"Quantity",
"Consumed",
"Exported",
)
)
print("\n" + '-' * 184)
for item in pool:
usagesortlist.append( "{} {}".format( len( pool[item]['usage'] ), item ) )
for sitem in natsorted(usagesortlist, reverse=reverse_sort):
item = sitem.split()[1]
if pool[item]['quantity'] < 0:
quantity = "unlimited"
else:
quantity = pool[item]['quantity']
# print("\n" + '-' * 184)
print("{:110} | {:34} | {:12} | {:8} | {:8}".format(
pool[item]['name'],
item,
quantity,
pool[item]['consumed'],
pool[item]['exported'],
)
)
if len(pool[item]['usage']) > 0:
if not cliopts.silent:
print("{:>30} | {:^36} | {:70}".format( "Attached Systems:", "System ID", "Name" ))
for id in pool[item]['usage']:
print("{:30} | {:36} | {:70} Last Checkin (days): {}".format( "", consumer[id]['uuid'], consumer[id]["name"], consumer[id]["checkin"]))
def print_consumer_duplicates():
duplicate_count = 0
duplicate_systems = 0
for host in consumer:
name = consumer[host]['name']
uuid = consumer[host]['uuid']
seconds = consumer[host]['checkin_secs']
if name not in hosts:
hosts[name] = {}
# hosts[name][seconds] = host
hosts[name][seconds] = uuid
for item in hosts:
dup_num = len(hosts[item])
if dup_num > 1:
duplicate_count += dup_num
duplicate_systems += 1
duplicatesortlist.append( "{} {}".format( len(hosts[item]), item))
if not cliopts.silent:
print("Hosts with duplicates: ", duplicate_systems)
print("Duplicate systems: ", duplicate_count)
print("Freeable systems: ", duplicate_count - duplicate_systems)
print("{:^3} | {:^74} | {:^12} | {:^8}".format(
"Count",
"Name",
"Last Checkin (EPOCH)",
"ID",
)
)
print('-' * 124)
for sitem in natsorted(duplicatesortlist, reverse=reverse_sort):
count, item = sitem.split(' ')
print ( "# {:3} {:80} ".format(count, item), end="")
for tim in natsorted(hosts[item], reverse=True):
print ("{:>20} {}".format(tim, hosts[item][tim]))
# Build a dictionary of all the pools
#
if not cliopts.silent:
print("Getting list of pools from CDN.")
cdn_request = requests.get(
'https://subscription.rhsm.redhat.com/subscription/owners/{}/pools?include=id&include=productName&include=quantity&include=consumed&include=exported'.format( cliopts.ownerid ),
auth=(cliopts.user, cliopts.password),
verify=False,
)
#print ( cdn_request.text )
jsonobj = json.loads( cdn_request.text.lower() )
#print ( json.dumps(jsonobj, indent=4, sort_keys=True) )
for poolkey in jsonobj:
pool[ poolkey["id"] ] = {
'quantity': poolkey["quantity"],
'consumed': poolkey["consumed"],
'exported': poolkey["exported"],
'name': poolkey["productname"],
'usage': [],
}
# Get consumer information
#
#jsonobj = json.loads( open('owners_consumers.json').read() )
if not cliopts.silent:
print("Getting list of hosts from CDN.")
cdn_request = requests.get(
'https://subscription.rhsm.redhat.com/subscription/owners/{}/consumers?include=id&include=uuid&include=name&include=lastCheckin&include=created'.format( cliopts.ownerid ),
auth=(cliopts.user, cliopts.password),
verify=False,
)
#print ( cdn_request.text )
jsonobj = json.loads( cdn_request.text.lower() )
#print ( json.dumps(jsonobj, indent=4, sort_keys=True) )
#sys.exit("debug done")
for ckey in jsonobj:
if not ckey["created"]:
secs_create = "0"
else:
try:
secs_create = datetime.strptime(ckey["created"], "%Y-%m-%dt%H:%M:%S+0000").strftime("%s")
except:
secs_create = datetime.strptime(ckey["created"], "%Y-%m-%dt%H:%M:%S.000+0000").strftime("%s")
if not ckey["lastcheckin"]:
secs_checkin = 0
days_checkin = 0
else:
try:
secs_checkin = datetime.strptime(ckey["lastcheckin"], "%Y-%m-%dT%H:%M:%S+0000").strftime("%s")
except:
secs_checkin = datetime.strptime(ckey["lastcheckin"], "%Y-%m-%dT%H:%M:%S.000+0000").strftime("%s")
days_checkin = int( ( int( time.time() ) - int( secs_checkin ) ) / 86400 )
if days_checkin < 0:
days_checkin = "0"
consumer[ ckey["id"] ] = {
'name': ckey["name"],
'uuid': ckey["uuid"],
'create': secs_create,
'checkin': days_checkin,
'checkin_secs': secs_checkin,
'entitlementcount': 0,
}
consumersortlist.append( "{} {}".format( days_checkin, ckey["id"] ) )
# ----------------------------
if cliopts.checkin:
print_checkin()
if cliopts.duplicates:
print_consumer_duplicates()