forked from ombegov/dcoi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimportIDCData.py
281 lines (250 loc) · 8.15 KB
/
importIDCData.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
276
277
278
279
280
281
###
# This script may be used to import IDC spreadsheets to a local sqlite database
# The spreadsheet must be in the historical IDC format.
###
from __future__ import print_function
import os
import csv
import sys
import itertools
import sqlite3
import argparse
import re
import io
import config
def main():
# Variables we will re-use
parser = argparse.ArgumentParser(description='Import IDC spreadsheets.')
parser.add_argument('quarter', type=is_quarter,
help='The year and quarter this data was reported ( format: YYYYq# )')
parser.add_argument('filename', type=is_path,
help='file or directory to import')
args = parser.parse_args()
conn = sqlite3.connect(config.DB_CONFIG['file'])
# For a single file.
if os.path.isfile(args.filename):
import_file(args.filename, args.quarter, conn)
# For a director of files.
elif(os.path.isdir(args.filename)):
for f in os.listdir(args.filename):
theFile = os.path.join(args.filename, f)
if os.path.isfile(theFile):
import_file(theFile, args.quarter, conn)
conn.close()
# Lowercase the field keys by updating the header row, for maximum compatiblity.
def lower_headings(iterator):
return itertools.chain([next(iterator).lower()], iterator)
# Checks if a path is an actual directory
def is_path(filename):
if os.path.isfile(filename):
return filename
elif os.path.isdir(filename):
return filename
else:
msg = "{0} is not a directory".format(filename)
raise argparse.ArgumentTypeError(msg)
def is_quarter(quarter):
if re.match('^[0-9]{4}q[1-4]$', quarter):
return quarter
else:
msg = "{0} is not a valid quarter. Must match 2018q3 or similar".format(quarter)
raise argparse.ArgumentTypeError(msg)
def import_file(filename, q, conn):
c = conn.cursor()
print('Importing ', filename)
year, quarter = q.split('q')
quarter = int(quarter)
year = int(year)
agencies = []
rows = []
with io.open(filename, 'r') as datafile:
headings = None
for line in datafile:
# Remove non-utf-8 characters that cause things to fail.
line = bytes(line, 'utf-8').decode('utf-8', 'ignore')
if headings == None:
headings = line.lower()
continue
# This is a mildly-hacky way too only parse the current line.
try:
reader = csv.DictReader([headings, line])
row = next(reader)
except StopIteration:
continue
# We only want valid records.
if row.get('record validity') != 'Valid Facility':
continue
# Overwrite any previous data for this agency for the specified quarter.
if row.get('agency abbreviation') not in agencies:
agencies.append(row.get('agency abbreviation'))
# When DEBUGging import problems, uncomment this. This is very slow otherwise.
# TODO: make this a commandline flag.
print('Clearing {} {} q{}'.format(row.get('agency abbreviation'), year, quarter))
c.execute('DELETE FROM datacenters WHERE year=:year AND quarter=:quarter AND agency=:agency',
{
'year': year,
'quarter': quarter,
'agency': row.get('agency abbreviation')
}
)
# Flush previous rows.
if len(rows):
c.executemany('''
INSERT INTO datacenters
(
id,
quarter,
year,
agency,
component,
ownershipType,
sharedServicesPosition,
tier,
country,
grossFloorArea,
keyMissionFacility,
keyMissionFacilityType,
optimizationExempt,
electricityMetered,
avgElectricityUsage,
avgITElectricityUsage,
underutilizedServers,
downtimeHours,
plannedAvailabilityHours,
mainframesCount,
HPCCount,
serverCount,
virtualHostCount,
closingStage,
closingTargetDate,
comments
) VALUES (
:id,
:quarter,
:year,
:agency,
:component,
:ownershipType,
:sharedServicesPosition,
:tier,
:country,
:grossFloorArea,
:keyMissionFacility,
:keyMissionFacilityType,
:optimizationExempt,
:electricityMetered,
:avgElectricityUsage,
:avgITElectricityUsage,
:underutilizedServers,
:downtimeHours,
:plannedAvailabilityHours,
:mainframesCount,
:HPCCount,
:serverCount,
:virtualHostCount,
:closingStage,
:closingTargetDate,
:comments
)
''', rows)
rows = []
conn.commit()
print(row.get('data center id'), year, quarter)
# This field is squirrelly
optimizationExempt = row.get('omb optimization exempt decision', '')
if optimizationExempt is not None:
optimizationExempt = int(optimizationExempt.lower() == 'yes')
else:
optimizationExempt = 0
rows.append({
'id' : row.get('data center id'),
'quarter' : quarter,
'year': year,
'agency' : row.get('agency abbreviation'),
'component' : row.get('component'),
'ownershipType' : row.get('ownership type'),
'sharedServicesPosition' : row['inter-agency shared services position'],
'tier' : row.get('data center tier'),
'country' : row.get('country'),
'grossFloorArea' : row.get('gross floor area'),
'keyMissionFacility' : int(row.get('key mission facility').lower() == 'yes'),
'keyMissionFacilityType' : row.get('key mission facility type'),
'optimizationExempt': optimizationExempt,
'electricityMetered' : int(row.get('electricity is metered').lower() == 'yes'),
'avgElectricityUsage' : row.get('avg electricity usage'),
'avgITElectricityUsage' : row.get('avg it electricity usage'),
'underutilizedServers' : row.get('underutilized servers'),
'downtimeHours' : row.get('actual hours of facility downtime'),
'plannedAvailabilityHours' : row.get('planned hours of facility availability'),
'mainframesCount' : row.get('total mainframes'),
'HPCCount' : row.get('total hpc cluster nodes'),
'serverCount' : row.get('total servers'),
'virtualHostCount' : row.get('total virtual hosts'),
'closingStage' : row.get('closing stage'),
'closingTargetDate' : row.get('closing fiscal year') + ' ' + row.get('closing quarter'),
'comments' : row.get('comments')
})
# Flush previous rows.
if len(rows):
c.executemany('''
INSERT INTO datacenters
(
id,
quarter,
year,
agency,
component,
ownershipType,
sharedServicesPosition,
tier,
country,
grossFloorArea,
keyMissionFacility,
keyMissionFacilityType,
optimizationExempt,
electricityMetered,
avgElectricityUsage,
avgITElectricityUsage,
underutilizedServers,
downtimeHours,
plannedAvailabilityHours,
mainframesCount,
HPCCount,
serverCount,
virtualHostCount,
closingStage,
closingTargetDate,
comments
) VALUES (
:id,
:quarter,
:year,
:agency,
:component,
:ownershipType,
:sharedServicesPosition,
:tier,
:country,
:grossFloorArea,
:keyMissionFacility,
:keyMissionFacilityType,
:optimizationExempt,
:electricityMetered,
:avgElectricityUsage,
:avgITElectricityUsage,
:underutilizedServers,
:downtimeHours,
:plannedAvailabilityHours,
:mainframesCount,
:HPCCount,
:serverCount,
:virtualHostCount,
:closingStage,
:closingTargetDate,
:comments
)
''', rows)
conn.commit()
if __name__ == '__main__':
main()
exit()