This repository has been archived by the owner on Oct 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
restapi.py
1643 lines (1359 loc) · 63.8 KB
/
restapi.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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
from django.contrib.auth.management.commands.createsuperuser import is_valid_email
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.db import IntegrityError
from models import Account, ScoreFunction, Package, Service
from flaptor.indextank.rpc import ttypes
from restresource import ProvisionerResource, Resource, JsonResponse, non_empty_argument, int_argument, required_data, optional_data, int_querystring, json_querystring, querystring_argument, required_querystring_argument, check_public_api, get_index_param, get_index_param_or404, wakeup_if_hibernated, authorized_method
from lib import encoder
from lib import mail
from lib.indextank.client import ApiClient
import rpc
import re
from api import models
import time
import storage
LOG_STORAGE_ENABLED = True
""" Data validation and parsing functions """
def _encode_utf8(s):
try:
return s.encode('utf-8')
except:
try:
str(s).decode('utf-8')
return str(s)
except:
try:
return str(s).encode('utf-8')
except:
return None
def __validate_boolean(field_name):
def dovalidate(arg):
if type(arg) != bool:
return HttpResponse('"Invalid \\"%s\\" argument, it should be a json boolean"' % field_name, status=400)
return dovalidate
def __validate_docid(docid):
"""
Validates that a document id is a string, a unicode, or an int (for backwards compatibility).
It can't be empty, nor longer than 1024 bytes.
Valid inputs
>>> __validate_docid("a")
>>> __validate_docid("\xc3\xb1")
>>> __validate_docid(u"\xc3\xb1")
>>> # for backwards compatibility
>>> __validate_docid(123)
>>> __validate_docid(0)
>>> __validate_docid(-1)
Validate length
>>> __validate_docid("a"*1024)
>>> __validate_docid(u"a"*1024)
>>> # 512 2-byte chars are ok
>>> __validate_docid("\xc3\xb1"*512)
>>> e = __validate_docid("a"*1025)
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_docid(u"\xc3"*1025)
>>> isinstance(e, HttpResponse)
True
>>> # 512 2-byte chars are not ok
>>> e = __validate_docid("\xc3\xb1"*513)
>>> isinstance(e, HttpResponse)
True
Validate emptyness
>>> e = __validate_docid(" ")
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_docid("")
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_docid(" "*80)
>>> isinstance(e, HttpResponse)
True
Validate not supported types
>>> e = __validate_docid(80.0)
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_docid([1,2,3])
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_docid({"a":"b"})
>>> isinstance(e, HttpResponse)
True
Validate None
>>> e = __validate_docid(None)
>>> isinstance(e, HttpResponse)
True
"""
if type(docid) in [int, long]:
docid = str(docid)
if not type(docid) in [str,unicode]:
return HttpResponse('"Invalid docid, it should be a String."', status=400)
if docid.strip() == '':
return HttpResponse('"Invalid docid, it shouldnt be empty."', status=400)
udocid = _encode_utf8(docid)
if len(udocid) > 1024:
return HttpResponse('"Invalid docid, it shouldnt be longer than 1024 bytes. It was %d"'%len(udocid), status=400)
def __parse_docid(docid):
if not type(docid) in [str,unicode]:
docid = str(docid)
return docid
def __str_is_integer(val):
try:
i = int(val)
return True
except:
return False
def __validate_fields(fields):
"""
Validates that a document fields is a dictionary with string (or unicode) keys and string (or unicode) values.
The only exception is 'timestamp', that can be an int or a string representation of an int.
The sum of the sizes of all the field values can not be bigger than 100kb.
Returns nothing, unless a validation error was found. In that case, it returns an HttpResponse with the error as body.
Validate documents without errors
>>> __validate_fields({'field1':'value1', 'field2':'value2'})
>>> __validate_fields({'text':'', 'title':u''})
>>> __validate_fields({'text':u'just one field'})
>>> __validate_fields({'field1':'value1 and value2 and value 3 or value4', 'field2':'value2', 'field3':'123'})
Validate documents with errors on field values (int, float, array, dict and None)
As the input for this method comes from json, there can't be objects as values
>>> __validate_fields({'text': 123})
>>> __validate_fields({'text': 42.8})
>>> e = __validate_fields({'text': ['123']})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields({'text': None})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields({'text': {'k':'v'}})
>>> isinstance(e,HttpResponse)
True
Validate documents with errors on field names (int, float and None)
As the input for this method comes from json, there can't be objects as keys
>>> e = __validate_fields({None: '123'})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields({123: 'text'})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields({42.5: 'value'})
>>> isinstance(e,HttpResponse)
True
Validate timestamps
>>> __validate_fields({'timestamp': 123, 'field1':'value1'})
>>> __validate_fields({'timestamp': '123', 'fieldN':'valueN'})
>>> __validate_fields({'timestamp': -123, 'field1':'value1'})
>>> __validate_fields({'timestamp': '-123', 'fieldN':'valueN'})
>>> e = __validate_fields({'timestamp': 'something', 'fieldN': 'valueN'})
>>> isinstance(e,HttpResponse)
True
Validate document size
>>> __validate_fields({'text': 'a'*1024})
>>> __validate_fields({'text': 'a'*1024, 'title':'b'*1024})
>>> # this is the boundary case for 1 field
>>> __validate_fields({'text': 'a'*1024*100})
>>> # a boundary case for 2 fields .. 1 * 9 * 1024 + 10 * 9 * 1024
>>> __validate_fields({'text': 'a'*9*1024, 'title': 'a b c d e '*9*1024})
>>> # a boundary case for 2-byte chars on fields
>>> __validate_fields({'text': '\xc3\xb1'*100*512})
>>> # this is an error case for 1 field
>>> e = __validate_fields({'text': 'a'*1024*101})
>>> isinstance(e,HttpResponse)
True
>>> # this is an error case for 2 fields
>>> e = __validate_fields({'text': 'a'*50*1024, 'title': 'a b c d e '*9*1024})
>>> isinstance(e,HttpResponse)
True
>>> # this is an error case for 10 fields .. 10 * ( 1024 * 11 )
>>> fields = {}
>>> fields.update([("text%d"%i,"123 456 789"*1024) for i in range(0,10)])
>>> e = __validate_fields(fields)
>>> isinstance(e,HttpResponse)
True
>>> # this is an error case for 2-byte chars on fields
>>> e = __validate_fields({"text":"\xc3\xb1"*100*513})
>>> isinstance(e,HttpResponse)
True
>>> # disallow no fields
>>> e = __validate_fields({})
>>> isinstance(e,HttpResponse)
True
>>> # disallow None, Arrays, Numbers and Strings
>>> e = __validate_fields(None)
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields([1, 2, 3])
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields(123)
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields("this is some text")
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_fields(True)
>>> isinstance(e,HttpResponse)
True
"""
if not fields:
return HttpResponse('"At least one field is required. If you\'re trying to delete the document, you should use the delete api"', status=400)
if not isinstance(fields, dict):
return HttpResponse('"fields should be a JSON Object, e.g: {\'text\': \'something\'} "', status=400)
for k, v in fields.iteritems():
# timestamp gets special treatment, it should be an integer
if 'timestamp' == k:
if not type(v) == int and not (type(v) == str and __str_is_integer(v)):
return HttpResponse('"Invalid timestamp: %s. It should be an integer."' % fields['timestamp'], status=400)
continue
# any other key should be a string or unicode
if not isinstance(k,str) and not isinstance(k,unicode):
return HttpResponse('"Name for field %s is not a String"' % (k), status=400)
if isinstance(v,int) or isinstance(v,float):
v = str(v)
if not isinstance(v,str) and not isinstance(v,unicode):
return HttpResponse('"Value for field %s is not a String nor a number"' % (k), status=400)
ev = _encode_utf8(v)
ek = _encode_utf8(k)
if ek is None:
return HttpResponse('"Invalid name for field %s"' % (k), status=400)
if ev is None:
return HttpResponse('"Invalid content for field %s: %s"' % (k, v), status=400)
# verify document size
doc_size = sum(map(lambda (k,v) : len(v) if type(v) in [str, unicode] else 0, fields.iteritems()))
if doc_size > 1024 * 100:
return HttpResponse('"Invalid document size. It shouldn\'t be bigger than 100KB. Got %d bytes"' % (doc_size), status=400)
def __parse_fields(fields):
if 'timestamp' not in fields:
fields['timestamp'] = str(int(time.time()))
for k, v in fields.iteritems():
fields[k] = _encode_utf8(v)
return fields
def __validate_categories(categories):
"""
Validates that a document categories is a dictionary with string (or unicode) keys and string (or unicode) values.
Returns nothing, unless a validation error was found. In that case, it returns an HttpResponse with the error as body
Validate categories without errors
>>> __validate_categories({'field1':'value1', 'field2':'value2'})
>>> __validate_categories({'text':'', 'title':u''})
>>> __validate_categories({'text':u'just one field'})
>>> __validate_categories({'field1':'value1 and value2 and value 3 or value4', 'field2':'value2', 'field3':'123'})
Validate documents with errors on category values (int, float, array, dict and None)
As the input for this method comes from json, there can't be objects as values
>>> e = __validate_categories({'text': 123})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_categories({'text': 42.8})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_categories({'text': ['123']})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_categories({'text': None})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_categories({'text': {'k':'v'}})
>>> isinstance(e,HttpResponse)
True
Validate documents with errors on category names (int, float and None)
As the input for this method comes from json, there can't be objects as keys
>>> e = __validate_categories({None: '123'})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_categories({123: 'text'})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_categories({42.5: 'value'})
>>> isinstance(e,HttpResponse)
True
"""
for k, v in categories.iteritems():
ev = _encode_utf8(v)
ek = _encode_utf8(k)
if not isinstance(k,str) and not isinstance(k,unicode):
return HttpResponse('"Name for category %s is not a String"' % (k), status=400)
if not isinstance(v,str) and not isinstance(v,unicode):
return HttpResponse('"Value for category %s is not a String"' % (k), status=400)
if ek is None:
return HttpResponse('"Invalid name for category %s"' % (k), status=400)
if ev is None:
return HttpResponse('"Invalid content for category %s: %s"' % (k, v), status=400)
def __parse_categories(categories):
parsed = {}
for k, v in categories.iteritems():
parsed[k] = _encode_utf8(v).strip()
return parsed
def __validate_variables(variables):
"""
Validates that variables for a document is a dict with string representations of positive ints as keys and floats as values
variable mappings without errors
>>> __validate_variables({"4":8, "5":2.5})
>>> __validate_variables({"1":2})
>>> __validate_variables({"10":2})
>>> # the next line is kinda valid. "2" can be parsed to float.
>>> __validate_variables({"1":"2"})
variable mappings with errors on keys
>>> e = __validate_variables({"-10":2})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_variables({"var1":2})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_variables({"10":2, "v3":4.5})
>>> isinstance(e,HttpResponse)
True
variable mappings with errors on values
>>> e = __validate_variables({"1":[2.5]})
>>> isinstance(e,HttpResponse)
True
>>> e = __validate_variables({"1":2, "2":{2.5:2}})
>>> isinstance(e,HttpResponse)
True
"""
for k, v in variables.iteritems():
if not k.isdigit():
return HttpResponse('"Invalid variable index: %s. It should be integer."' % k, status=400)
try:
float(v)
except (ValueError, TypeError):
return HttpResponse('"Invalid variable value for index %s: %s. It should be a float"' % (k,v), status=400)
def __parse_variables(variables):
parsed = {}
for k, v in variables.iteritems():
parsed[int(k)] = float(v)
return parsed
def __validate_document(document):
if type(document) is not dict:
return HttpResponse('"Document should be a JSON object"', status=400)
if 'docid' not in document:
return HttpResponse('"Document should have a docid attribute"', status=400)
if 'fields' not in document:
return HttpResponse('"Document should have a fields attribute"', status=400)
response = None
response = response or __validate_docid(document['docid'])
response = response or __validate_fields(document['fields'])
if 'variables' in document:
response = response or __validate_variables(document['variables'])
if 'categories' in document:
response = response or __validate_categories(document['categories'])
if response:
return response
def __parse_document(document):
document['docid'] = __parse_docid(document['docid'])
document['fields'] = __parse_fields(document['fields'])
if 'variables' in document:
document['variables'] = __parse_variables(document['variables'])
if 'categories' in document:
document['categories'] = __parse_categories(document['categories'])
return document
def __validate_query(query):
"""
Validates that a query is a string or a unicode.
It can't be empty.
Valid inputs
>>> __validate_query("a")
>>> __validate_query("\xc3\xb1")
>>> __validate_query(u"\xc3\xb1")
Validate emptyness
>>> e = __validate_query(" ")
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_query("")
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_query(" "*80)
>>> isinstance(e, HttpResponse)
True
Validate not supported types
>>> e = __validate_query(80.0)
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_query([1,2,3])
>>> isinstance(e, HttpResponse)
True
>>> e = __validate_query({"a":"b"})
>>> isinstance(e, HttpResponse)
True
Validate None
>>> e = __validate_query(None)
>>> isinstance(e, HttpResponse)
True
"""
if query is None:
return HttpResponse('"Invalid query. It cannot be NULL"', status=400)
if type(query) not in [str,unicode]:
return HttpResponse('"Invalid query. It MUST be a String"', status=400)
if query.strip() == '' :
return HttpResponse('"Invalid query. It cannot be a empty"', status=400)
def __parse_query(query):
return _encode_utf8(query.lower())
""" Argument validation decorators """
required_index_name = non_empty_argument('index_name', 'Index name cannot be empty')
""" Data validation decorators """
required_categories_data = required_data('categories', __validate_categories, __parse_categories)
required_variables_data = required_data('variables', __validate_variables, __parse_variables)
required_fields_data = required_data('fields', __validate_fields, __parse_fields)
required_docid_data = required_data('docid', __validate_docid, __parse_docid)
optional_public_search_data = optional_data('public_search', __validate_boolean('public_search'))
optional_docid_data = optional_data('docid', __validate_docid, __parse_docid)
required_definition_data = required_data('definition')
required_query_data = required_data('query', __validate_query, __parse_query)
optional_variables_data = optional_data('variables', __validate_variables, __parse_variables)
required_integer_function = int_argument('function', 'Function number should be a non-negative integer')
def required_documents(func):
def decorated(self, request, data, **kwargs):
if type(data) is list:
if not data:
return HttpResponse('"Invalid batch insert. At least one document is required"', status=400)
for i in xrange(len(data)):
response = __validate_document(data[i])
if response:
response.content = '"Invalid batch insert, in document #%d of %d: %s"' % (i+1, len(data), response.content[1:-1])
return response
data[i] = __parse_document(data[i])
kwargs['batch_mode'] = True
kwargs['documents'] = data
else:
response = __validate_document(data)
if response:
return response
kwargs['batch_mode'] = False
kwargs['documents'] = [__parse_document(data)]
return func(self, request, data=data, **kwargs)
return decorated
def required_docids(func):
def decorated(self, request, data, **kwargs):
if not data:
docids = request.GET.getlist('docid')
if docids:
if len(docids) > 1:
data = []
for docid in docids:
data.append({'docid':docid})
else:
data = {'docid':docids[0]}
else:
return HttpResponse('"If no body is given, you should include a docid argument in the querystring"', status=400)
if type(data) is list:
if not data:
return HttpResponse('"Invalid batch delete. At least one docid is required"', status=400)
for i in xrange(len(data)):
if not data[i].has_key('docid'):
return HttpResponse('"Invalid batch delete. Document #%d of %d doesn\'t have a docid parameter"' % (i+1, len(data)), status=400)
response = __validate_docid(data[i]['docid'])
if response:
response.content = '"Invalid batch delete, in docid #%d of %d: %s"' % (i+1, len(data), response.content[1:-1])
return response
data[i]['docid'] = __parse_docid(data[i]['docid'])
kwargs['bulk_mode'] = True
kwargs['documents'] = data
else:
if 'docid' in data:
response = __validate_docid(data['docid'])
if response:
response.content
return response
data['docid'] = __parse_docid(data['docid'])
kwargs['bulk_mode'] = False
kwargs['documents'] = [data]
else:
return HttpResponse('"Argument docid is required in the request body"', status=400)
return func(self, request, data=data, **kwargs)
return decorated
""" Shared bulk delete code """
def delete_docs_from_index(resource, index, documents):
"""
resource: A Resource (from restresource.py). Needed just to LOG errors
index: The index to delete documents from. Every deploy for that index will be hit.
documents: list of documents to delete. **Need** 'docid' on each of them.
"""
indexers = rpc.get_indexer_clients(index)
responses = []
for doc in documents:
ret = {'deleted': True}
try:
for indexer in indexers:
indexer.delDoc(doc['docid'])
except Exception:
resource.logger.exception('"Failed to delete %s on %s (%s)', doc['docid'], index.code, index.name)
resource.error_logger.exception('"Failed to delete %s on %s (%s)', doc['docid'], index.code, index.name)
ret['deleted'] = False
ret['error'] = '"Currently unable to delete the requested document"'
responses.append(ret)
return responses
""" Util functions for request processing """
def metadata_for_index(index):
return dict(code=index.code, creation_time=index.creation_time.isoformat(), started=index.is_ready(), size=index.current_docs_number, public_search=index.public_api, status=index.status)
def build_logrecord_for_add(index, document):
return ttypes.LogRecord(index_code=index.code,
docid=document['docid'],
deleted=False,
fields=document['fields'],
variables=document.get('variables', {}),
categories=document.get('categories', {}))
def build_logrecord_for_delete(index, document):
return ttypes.LogRecord(index_code=index.code,
docid=document['docid'],
deleted=True)
log_writers = None
log_addresses = None
def send_log_storage_batch(resource, index, records):
global log_addresses
global log_writers
try:
storage_services = Service.objects.filter(name='storage')
if storage_services:
addresses = set((service.host, int(service.port), service.type) for service in storage_services)
if addresses != log_addresses:
log_writers = [(rpc.getReconnectingLogWriterClient(h,p), t == 'optional') for h,p,t in addresses]
log_addresses = addresses
for writer, optional in log_writers:
try:
writer.send_batch(ttypes.LogBatch(records=records))
except:
if optional:
resource.logger.exception('Optional storage failed to receive batch - IGNORING. %d records for index %s', len(records), index.code)
resource.error_logger.exception('Optional storage failed to receive batch - IGNORING. %d records for index %s', len(records), index.code)
else:
raise
return True
else:
resource.logger.error('No storage services found. %d records for index %s', len(records), index.code)
resource.error_logger.error('No storage services found. %d records for index %s', len(records), index.code)
return False
except:
resource.logger.exception('Error sending batch to log storage. %d records for index %s', len(records), index.code)
resource.error_logger.exception('Error sending batch to log storage. %d records for index %s', len(records), index.code)
return False
"""
Version resource ======================================================
"""
class Version(Resource):
authenticated = False
def GET(self, request, version):
return HttpResponse('"API V %s : Documentation"' % version)
"""
Indexes resource ======================================================
"""
class Indexes(Resource):
authenticated = True
def GET(self, request, version):
metadata = {}
for index in self.get_account().indexes.all():
metadata[index.name] = metadata_for_index(index)
# 200 OK : json of the indexes metadata
return JsonResponse(metadata)
"""
Index resource ======================================================
"""
class Index(Resource):
authenticated = True
# gets index metadata
@required_index_name
@get_index_param_or404
def GET(self, request, version, index):
return JsonResponse(metadata_for_index(index))
# creates a new index for the given name
@required_index_name
@optional_public_search_data
def PUT(self, request, data, version, index_name, public_search=None):
account = self.get_account()
indexes = account.indexes.filter(name=index_name)
if indexes.count() > 1:
self.logger.exception('Inconsistent state: more than one index with name %s', index_name)
self.error_logger.exception('Inconsistent state: more than one index with name %s', index_name)
return HttpResponse('Unable to create/update your index. Please contact us.', status=500)
elif indexes.count() == 1:
if not public_search is None:
index = indexes[0]
index.public_api = public_search
index.save()
# 204 OK: index already exists
return HttpResponse(status=204)
else:
current_count = account.indexes.filter(deleted=False).count()
max_count = account.package.max_indexes
if not current_count < max_count:
msg = '"Unable to create. Too many indexes for the account (maximum: %d)"' % max_count
return HttpResponse(msg, status=409) #conflict
# basic index data
try:
index = account.create_index(index_name, public_search)
except IntegrityError:
return HttpResponse(status=204) # already exists
mail.report_new_index(index)
# 201 OK : index created
return JsonResponse(metadata_for_index(index), status=201)
@required_index_name
@get_index_param
def DELETE(self, request, data, version, index):
if not index:
return HttpResponse(status=204)
rpc.get_deploy_manager().delete_index(index.code)
mail.report_delete_index(index)
return HttpResponse()
"""
Document resource ======================================================
"""
class Document(Resource):
authenticated = True
@required_index_name
@required_querystring_argument('docid')
@get_index_param_or404
def GET(self, request, version, index, docid):
self.logger.debug('id=%s', docid)
doc = storage.storage_get(index.code, docid)
if doc is None:
raise Http404
self.set_message('Retrieved document %s' % docid)
return JsonResponse(doc)
def _insert_document(self, index, indexers, document):
tdoc = ttypes.Document(fields=document['fields'])
docid = document['docid']
variables = document.get('variables', {})
categories = document.get('categories', {})
success = { 'added': True }
try:
for indexer in indexers:
indexer.addDoc(docid, tdoc, int(tdoc.fields['timestamp']), variables)
if categories:
indexer.updateCategories(docid, categories)
except Exception, e:
self.logger.exception('Failed to index %s on %s (%s)', docid, index.code, index.name)
self.error_logger.exception('Failed to index %s on %s (%s)', docid, index.code, index.name)
success['added'] = False
success['error'] = '"Currently unable to index the requested document"'
return success
def _validate_variables(self, index, documents):
max_variables = index.configuration.get_data().get('max_variables')
for i in xrange(len(documents)):
if 'variables' in documents[i]:
for k in documents[i]['variables'].keys():
if k < 0 or k >= max_variables:
if len(documents) == 1:
return HttpResponse('"Invalid key in variables: \'%d\' (it should be in the range [0..%d]"' % (k, max_variables-1), status=400)
else:
return HttpResponse('"Invalid batch insert, in document #%d of %d: Invalid variable index %d. Valid keys are in range [0-%d]"' % (i+1, len(documents), k, max_variables-1), status=400)
@required_index_name
@required_documents
@get_index_param_or404
@wakeup_if_hibernated
def PUT(self, request, data, version, index, documents, batch_mode):
if batch_mode:
self.logger.debug('batch insert: %d docs', len(documents))
else:
self.logger.debug('id=%s fields=%s variables=%s categories=%s', documents[0].get('docid'), documents[0].get('fields'), documents[0].get('variables'), documents[0].get('categories'))
if not index.is_ready():
return HttpResponse('"Index is not ready."', status=409)
response = self._validate_variables(index, documents)
if response:
return response
rt = []
indexers = rpc.get_indexer_clients(index)
if LOG_STORAGE_ENABLED:
records = [build_logrecord_for_add(index, d) for d in documents]
if not send_log_storage_batch(self, index, records):
return HttpResponse('"Currently unable to insert the requested document(s)."', status=503)
for document in documents:
rt.append(self._insert_document(index, indexers, document))
if not batch_mode:
if rt[0]['added']:
return HttpResponse()
else:
return HttpResponse(rt[0]['error'], status=503)
return JsonResponse(rt)
@required_index_name
@required_docids
@get_index_param_or404
@wakeup_if_hibernated
def DELETE(self, request, data, version, index, documents, bulk_mode):
if bulk_mode:
self.logger.debug('bulk delete: %s docids', len(documents))
else:
self.logger.debug('id=%s qsid=%s', data['docid'], request.GET.get('docid'))
if not index.is_ready():
return HttpResponse('"Index is not ready"', status=409)
if LOG_STORAGE_ENABLED:
records = [build_logrecord_for_delete(index, d) for d in documents]
if not send_log_storage_batch(self, index, records):
return HttpResponse('"Currently unable to delete the requested document."', status=503)
indexers = rpc.get_indexer_clients(index)
responses = delete_docs_from_index(self, index, documents)
if not bulk_mode:
if responses[0]['deleted']:
return HttpResponse()
else:
return HttpResponse(responses[0]['error'], status=503)
return JsonResponse(responses)
"""
Categories resource ======================================================
"""
class Categories(Resource):
authenticated = True
@required_index_name
@required_docid_data
@required_categories_data
@get_index_param_or404
@wakeup_if_hibernated
def PUT(self, request, data, version, categories, index, docid):
self.logger.debug('id=%s categories=%s', docid, categories)
if not index.is_writable():
return HttpResponse('"Index is not ready"', status=409)
if LOG_STORAGE_ENABLED:
records = [ttypes.LogRecord(index_code=index.code, docid=docid, deleted=False, categories=categories)]
if not send_log_storage_batch(self, index, records):
return HttpResponse('"Currently unable to update the requested document."', status=503)
indexers = rpc.get_indexer_clients(index)
failed = False
for indexer in indexers:
try:
indexer.updateCategories(docid, categories)
except Exception, e:
if isinstance(e, ttypes.IndextankException):
return HttpResponse(e.message, status=400)
else:
self.logger.exception('Failed to update variables for %s on %s (%s)', docid, index.code, index.name)
self.error_logger.exception('Failed to update variables for %s on %s (%s)', docid, index.code, index.name)
failed = True
break
if failed:
return HttpResponse('"Currently unable to update the categories for the requested document."', status=503)
else:
self.set_message('Updated categories for %s' % docid)
return HttpResponse()
"""
Variables resource ======================================================
"""
class Variables(Resource):
authenticated = True
@required_index_name
@required_docid_data
@required_variables_data
@get_index_param_or404
@wakeup_if_hibernated
def PUT(self, request, data, version, variables, index, docid):
self.logger.debug('id=%s variables=%s', docid, variables)
if not index.is_writable():
return HttpResponse('"Index is not ready"', status=409)
if LOG_STORAGE_ENABLED:
records = [ttypes.LogRecord(index_code=index.code, docid=docid, deleted=False, variables=variables)]
if not send_log_storage_batch(self, index, records):
return HttpResponse('"Currently unable to update the requested document."', status=503)
indexers = rpc.get_indexer_clients(index)
failed = False
for indexer in indexers:
try:
indexer.updateBoost(docid, variables)
except Exception, e:
if isinstance(e, ttypes.IndextankException) and e.message.startswith('Invalid boost index'):
return HttpResponse(e.message.replace('boost', 'variable'), status=400)
else:
self.logger.exception('Failed to update variables for %s on %s (%s)', docid, index.code, index.name)
self.error_logger.exception('Failed to update variables for %s on %s (%s)', docid, index.code, index.name)
failed = True
break
if failed:
return HttpResponse('"Currently unable to index the requested document."', status=503)
else:
self.set_message('Updated variables for %s' % docid)
return HttpResponse()
"""
Functions resource ======================================================
"""
class Functions(Resource):
# gets the functions metadata
@required_index_name
@get_index_param_or404
@wakeup_if_hibernated
def GET(self, request, version, index):
#asking for writability in a get sounds odd... but jorge and spike
#think it's ok for functions.
if not index.is_writable():
return HttpResponse('"Index not ready to list functions."', status=409)
indexer = rpc.get_indexer_clients(index)[0]
functions = indexer.listScoreFunctions()
return JsonResponse(functions)
"""
Function resource ======================================================
"""
class Function(Resource):
authenticated = True
# TODO GET could return the function definition
# writes a function for the given number
@required_index_name
@required_integer_function
@required_definition_data
@get_index_param_or404
@wakeup_if_hibernated
def PUT(self, request, data, version, index, function, definition):
self.logger.debug('f=%d', function)
if (function < 0):
return HttpResponse('"Function index cannot be negative."', status=400)
if not index.is_writable():
return HttpResponse('"Index is not writable"', status=409)
indexers = rpc.get_indexer_clients(index)
failed = False
for indexer in indexers:
try:
indexer.addScoreFunction(function, definition)
except:
self.logger.warn('Failed to add function %s with definition: %s', function, data)
failed = True
break
if failed:
return HttpResponse('"Unable to add the requested function. Check your syntax."', status=400)
else:
sf, _ = ScoreFunction.objects.get_or_create(index=index, name=function)
sf.definition = definition
sf.save()
self.set_message('set to %s' % (definition))
return HttpResponse()
@required_index_name
@required_integer_function
@get_index_param_or404
@wakeup_if_hibernated
def DELETE(self, request, data, version, index, function):
self.logger.debug('f=%d', function)
if (function < 0):
return HttpResponse('"Function index cannot be negative."', status=400)
if not index.is_writable():
return HttpResponse('"Index is not writable"', status=409)
indexers = rpc.get_indexer_clients(index)
failed = False
for indexer in indexers:
try:
indexer.removeScoreFunction(function)
except:
self.logger.exception('Failed to remove function %s', function)
self.error_logger.exception('Failed to remove function %s', function)
failed = True
break
if failed:
return HttpResponse('"Failed to remove the requested function."', status=503)
else: