forked from mozilla/inventory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
189 lines (161 loc) · 5.98 KB
/
views.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
from django.http import HttpResponse
from django.core.exceptions import ValidationError
from django.db import transaction
from systems.models import System
from core.range.utils import range_usage
from core.search.compiler.django_compile import compile_to_q
from core.range.ip_choosing_utils import (
integrate_real_ranges, calc_template_ranges
)
from core.network.models import Network
from bulk_action.import_utils import loads, dumps, system_import, BadImportData
from MySQLdb import OperationalError
import MySQLdb
import pprint
import simplejson as json
def bulk_import(main_blob, load_json=True):
try:
if load_json:
json_blob = loads(main_blob)
else:
json_blob = main_blob
except ValueError, e: # Can't find JSONDecodeError
return None, {'errors': str(e)}
try:
systems = json_blob['systems']
except (KeyError, TypeError):
return None, {'errors': 'Main JSON needs to have a key "systems".'}
commit = json_blob.get('commit', False)
if not isinstance(systems, dict):
return None, {'errors': 'Main JSON blob must be a dict of systems'}
@transaction.commit_manually
def do_import():
try:
for i, s_blob in enumerate(systems.values()):
save_functions = sorted(
system_import(s_blob), key=lambda f: f[0]
)
for priority, fn in save_functions:
fn()
except BadImportData, e:
transaction.rollback()
return None, {
'errors': 'Found an issue while processing system #{0}'
'blob: {1}\nBad blob was:\n{2}'.format(
i, e.msg, e.bad_blob
)
}
except ValidationError, e:
transaction.rollback()
field_errors = ''
if hasattr(e, 'message_dict'):
for field, errors in e.message_dict.iteritems():
field_errors += "{0}: {1} ".format(field, ' '.join(errors))
else:
field_errors = ', '.join(e.messages)
transaction.rollback()
return None, {
'errors': 'Found an issue while processing system #{0}: '
'{field_errors}'.format(i, field_errors=field_errors), # noqa
'blob': s_blob,
'blob_number': i
}
except MySQLdb.Warning, e:
transaction.rollback()
return None, {
'errors': (
'There was an error while processing system number #{0}: '
'{error}.'.format(i, error=e.message)
),
'blob': s_blob,
'blob_number': i
}
except Exception, e:
transaction.rollback()
return None, {
'errors': 'Please tell someone about this error: {0}'.format(e), # noqa
'blob': s_blob,
'blob_number': i
}
else:
if commit:
transaction.commit()
else:
transaction.rollback()
return {'systems': systems}, None
return do_import()
def bulk_action_import(request):
raw_data = request.raw_post_data
if not raw_data:
return HttpResponse(dumps({'errors': 'what do you want?'}))
systems, errors = bulk_import(raw_data)
return HttpResponse(json.dumps(systems or errors))
def bulk_action_export(request):
search = request.GET.get('q', '')
if not search:
return HttpResponse(dumps({'errors': 'what do you want?'}))
q_map, errors = compile_to_q(search)
if errors:
return HttpResponse(dumps({'errors': errors}))
try: # We might have to catch shitty regular expressions
bundles = System.get_bulk_action_list(q_map['SYS'])
except OperationalError as why:
return HttpResponse(dumps({'error_messages': str(why)}))
pprint.pprint(bundles)
return HttpResponse(dumps({'systems': bundles}))
def bulk_gather_vlan_pools(request):
vlan_name = request.GET.get('vlan_name', None)
vlan_number = request.GET.get('vlan_number', None)
site_name = request.GET.get('site_name', None)
ip_type = request.GET.get('ip_type', None)
if not site_name:
return HttpResponse(dumps({
'errors': 'Site name was not provided'
}))
if not ip_type:
return HttpResponse(dumps({
'errors': 'IP type is required here.'
}))
if vlan_name and vlan_number:
s = 'site=:{site_name} AND vlan=:{vlan_name},{vlan_number}'.format(
site_name=site_name, vlan_name=vlan_name, vlan_number=vlan_number
)
elif vlan_name:
s = 'site=:{site_name} AND vlan=:{vlan_name}'.format(
site_name=site_name, vlan_name=vlan_name
)
elif vlan_number:
s = 'site=:{site_name} AND vlan=:{vlan_number}'.format(
site_name=site_name, vlan_number=vlan_number
)
else:
return HttpResponse(dumps({
'errors': 'Not enough vlan information was provided'
}))
q_map, errors = compile_to_q(s)
if errors:
return None, errors
networks = Network.objects.filter(q_map['NET']).filter(ip_type=ip_type)
if networks.count() > 1:
return HttpResponse(dumps({
'errors': "Using the search '{s}', too many networks were "
"found. Please be more specific and specify a range.".format(s=s)
}))
if not networks.count():
return HttpResponse(dumps({
'errors': "Using the search '{s}', no networks were "
"found.".format(s=s)
}))
ranges = integrate_real_ranges(
networks[0], calc_template_ranges(networks[0])
)
free_ranges = []
for r in ranges:
if r['rtype'] == 'special purpose':
continue
free_ranges += range_usage(
r['start'], r['end'], ip_type
)['free_ranges']
return HttpResponse(dumps({
'free_ranges': free_ranges
}))