-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodel.py
436 lines (365 loc) · 15.1 KB
/
model.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2017 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors:
# Alberto Pérez García-Plaza <[email protected]>
#
"""Stuff to deal with index patterns from JSON files genrated by Kidash.
"""
import csv
import json
import logging
from unittest import TestCase
class Schema(object):
"""Intends to represent index structure in order
to compare ES mappings against other compatible
structures whose types does not match one to one,
like Kibana types.
schema_name -- schema identifier
__properties -- dictionary of properties. Example:
{
'properties':{
'author_name': {
'type': 'text',
'analyzed': true,
'agg': true
}
...
}
}
"""
# List of types allowed for properties in this Schema
__supported_types = ['text', 'keyword', 'number', 'date', 'boolean',
'_source', 'geo_point', 'object']
# ES meta fields are excluded using the following list
__excluded_props = ['_all', '_field_names', '_id', '_index', '_meta',
'_parent', '_score', '_routing', '_source', '_type',
'_uid']
# In mbox enriched indexes is_mbox is defined
__excluded_props += ['is_gmane_message', 'is_mbox_message']
# Cache from askbot could not include this field
__excluded_props += ['is_askbot_comment']
# Cache from confluence could not include this field
__excluded_props += ['is_attachment', 'is_comment', 'is_new_page']
# Old ocean unique identifier
__excluded_props += ['ocean-unique-id']
def __init__(self, schema_name):
self.schema_name = schema_name
self.__properties = {}
@staticmethod
def check_type(src_type):
"""Checks if type is valid
TypeError -- when type is not supported
"""
if src_type not in Schema.__supported_types:
raise TypeError("Type not supported:", src_type)
return src_type
def add_property(self, pname, ptype, agg=False):
"""Adds a new property to the current schema. If there
is already a property with same name, that property
will be updated.
Each schema property will have 3 fields:
- name
- type
- agg
Keyword arguments:
pname -- property names
ptype -- property type
agg -- is this property aggregatable in Kibana?
"""
# Exclude ES internal properties
if pname not in self.__excluded_props:
schema_type = self.check_type(ptype)
self.__properties[pname] = {'type': schema_type}
if agg:
self.__properties[pname]['agg'] = True
def get_properties(self):
"""Returns a dictionary containing all schema properties.
Example:
{
'properties':{
'author_name': {
'type': 'text',
'analyzed': true,
'agg': true
}
...
}
}
"""
return self.__properties
def compare_properties(self, schema):
"""Compares two schemas. The schema used to call the method
will be the one we compare from, in advance 'source schema'.
The schema passed as parameter will be the 'target schema'.
Returns -- dictionary {status, correct, missing, distinct, message}
being:
status 'OK' if all properties in source schema exist in target
schema with same values. 'KO' in other case.
correct: list of properties that matches.
missing: list of properties missing from target schema.
distinct: list of properties in both schemas but having
with different values.
message: a string with additional information.
"""
test_case = TestCase('__init__')
test_case.maxDiff = None
status = 'OK'
correct = []
missing = []
distinct = []
msg = ''
for pname, pvalue in self.get_properties().items():
if pname not in schema.get_properties():
missing.append(pname)
msg = msg + '\n' + '* Missing property: ' + pname
status = 'KO'
else:
try:
test_case.assertDictEqual(pvalue,
schema.get_properties()[pname])
correct.append(pname)
except AssertionError as e:
distinct.append(pname)
msg = "%s\n* Type mismatch: \n\t%s: %s" %\
(msg, pname, str(e).replace('\n', '\n\t'))
status = 'KO'
return {'status': status, 'correct': correct, 'missing': missing,
'distinct': distinct, 'msg': msg}
class IndexPattern(Schema):
""" Represents an Index Pattern from Kibana/Kidash """
# Correspondence between Schema types and panel (index pattern) types
# There's no keyword and text types when exporting using kidash
# We could build those by following:
# - If type==string and analyzed==False ==> keyword
# - If type==string and analyzed==True ==> text
# We use a dictionary defined below to match those cases
__types = {'text': {'type': 'string', 'analyzed': True},
'keyword': {'type': 'string', 'analyzed': False},
'number': {'type': 'number', 'analyzed': False}}
def __init__(self, schema_name, time_field_name):
super().__init__(schema_name)
self.time_field_name = time_field_name
@classmethod
def from_json(cls, ip_json):
"""Builds a Panel object from a Kidash panel JSON file"""
index_pattern = cls(schema_name=ip_json['id'],
time_field_name=ip_json['value']['timeFieldName'])
# Get index pattern fields
fields_json = json.loads(ip_json['value']['fields'])
for json_field in fields_json:
if 'scripted' in json_field and json_field['scripted']:
# Don't check Kibana generated scripted fields
continue
if 'aggregatable' not in json_field:
logging.error('%s does not include aggregatable field. ' +
'Excluded from field checking.', json_field)
continue
index_pattern.add_property(pname=json_field['name'],
ptype=json_field['type'],
agg=json_field['aggregatable'],
analyzed=json_field['analyzed'])
return index_pattern
@staticmethod
def get_schema_type(src_type, analyzed):
"""Type conversion from index pattern types to schema types.
"""
out_type = src_type
for schema_type in IndexPattern.__types:
if src_type == IndexPattern.__types[schema_type]['type']:
if analyzed == IndexPattern.__types[schema_type]['analyzed']:
out_type = schema_type
return out_type
def add_property(self, pname, ptype, agg=False, analyzed=False):
"""Overwrites parent method for type conversion
"""
schema_type = self.get_schema_type(src_type=ptype, analyzed=analyzed)
super().add_property(pname, schema_type, agg)
class ESMapping(Schema):
"""Represents an ES Mapping"""
__mapping_types = {'long': 'number',
'integer': 'number',
'float': 'number',
'double': 'number'}
__non_aggregatables = {'text'}
@classmethod
def from_csv(cls, index_name, csv_file):
"""Builds a ESMapping object from a CSV schema definition
CSV Format:
field_name, es_type
:param raw_csv: CSV file to parse
:returns: ESMapping
"""
es_mapping = cls(schema_name=index_name)
with open(csv_file) as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
# With current CSVs is not possible to know which
# fields should be aggregatable. If we rely on
# '__non_aggregatables' list, then text fields would
# be non-aggregatables by default. Nevertheless, we
# want them to be aggregatables in most cases. As a
# quick fix while CSV schema specification improves,
# we will assume that fields defined as text in CSVs
# must be aggregatables in ESMapping.
property_type = row['type']
if property_type == 'text':
agg = True
else:
agg = None
es_mapping.add_property(pname=row['name'], ptype=property_type,
agg=agg)
return es_mapping
@classmethod
def from_json(cls, index_name, mapping_json):
"""Builds a ESMapping object from an ES JSON mapping
We don't know the exact name due to the aliases:
GET git/_mapping
Could retrieve:
{
"git_enriched": {
"mappings": {
"items": {
"dynamic_templates": [
{...}
],
"properties": {
"Author": {
...
So we need to take name as input parameter.
We can even find several indices if an alias groups them:
GET affiliations/_mapping
{
"git_enriched": {
...
},
"gerrit_enriched": {
...
We store all properties together in the same Schema.
"""
es_mapping = cls(schema_name=index_name)
# Get a list of all index mappings in JSON
mapping_list = list(mapping_json.values())
# Extract properties from all those grouped indices
for nested_json in mapping_list:
# nested_json = mapping_list[0]
items = nested_json['mappings']['items']['properties'].items()
for prop, value in items:
# Support for nested properties:
# "channel_purpose": {
# "properties": {
# "value": {
# "type": "keyword"
# },
# "creator": {
# "type": "keyword"
# },
# "last_set": {
# "type": "long"
# }
# }
# },
if 'properties' in value:
for nested_prop, nested_value in value['properties'].items():
prop_name = prop + '.' + nested_prop
agg = None
if 'fielddata' in nested_value:
agg = nested_value['fielddata']
if 'type' in nested_value:
ptype = nested_value['type']
else:
logging.warning('Not adding to es_mapping checking ' +
'the nested value: %s', nested_value)
continue
es_mapping.add_property(pname=prop_name,
ptype=ptype,
agg=agg)
# Support for "regular" properties
# "channel_id": {
# "type": "keyword"
# },
else:
agg = None
if 'fielddata' in value:
agg = value['fielddata']
es_mapping.add_property(pname=prop, ptype=value['type'],
agg=agg)
return es_mapping
@staticmethod
def get_schema_type(src_type):
"""Type conversion from ES mapping types to schema types.
"""
out_type = src_type
if src_type in ESMapping.__mapping_types:
out_type = ESMapping.__mapping_types[src_type]
return out_type
def add_property(self, pname, ptype, agg=None):
"""Overwrites parent method for type conversion
"""
schema_type = self.get_schema_type(src_type=ptype)
# Those fields not explicitely specified as aggregatable or not will be
# aggregatables depending on their type
schema_agg = agg
if schema_agg is None:
if schema_type in self.__non_aggregatables:
schema_agg = False
else:
schema_agg = True
super().add_property(pname, schema_type, schema_agg)
class Panel(object):
""" Bitergia Dashboard Panel """
def __init__(self):
""" Create a Panel containing a list of IndexPatterns.
Example:
{
'git':
'time_field_name': 'grimoire_creation_date',
'schema_name': 'git',
'properties':{
'author_name': {
'type': 'text',
'analyzed': true,
'fielddata': true
}
...
}
}
}
"""
self.__index_patterns = {}
@classmethod
def from_json(cls, panel_json):
"""Builds a Panel object from a Kidash panel JSON file"""
panel = cls()
index_patterns_json = panel_json['index_patterns']
for ip_json in index_patterns_json:
index_pattern = IndexPattern.from_json(ip_json)
panel.add(index_pattern=index_pattern)
return panel
def add(self, index_pattern):
"""Add an IndexPattern object to current panel.
Keyword arguments:
index_pattern -- IndexPattern instance
"""
self.__index_patterns[index_pattern.schema_name] = index_pattern
def get_index_pattern(self, name):
"""Returns index pattern given its name"""
return self.__index_patterns[name]
def get_index_patterns(self):
"""Returns Panel index patterns"""
return self.__index_patterns