This repository has been archived by the owner on Mar 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pult.wsgi
1342 lines (1155 loc) · 65.7 KB
/
pult.wsgi
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
# -*- coding: utf-8 -*-
import os
import os.path
import sys
import uuid
import tempfile, shutil
import zipfile
import sqlite3
import unicodedata
import string
from io import StringIO
import json
from json2html import *
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from threading import Thread
import datetime
import re
import whois
from ipwhois import IPWhois
local_path = os.path.split(__file__)[0]
if local_path not in sys.path:
sys.path.insert(0, local_path)
import prefs
CONFIG_NAMES = []
for name in prefs.CONFIGS:
CONFIG_NAMES.append(name)
def read(environ, length):
stream = environ['wsgi.input']
body = tempfile.NamedTemporaryFile(mode='w+b')
while length > 0:
part = stream.read(min(length, 1024*200)) # 200KB buffer size
if not part: break
body.write(part)
length -= len(part)
body.seek(0)
environ['wsgi.input'] = body
return body
def array2str(arrs, sql):
sql2 = StringIO()
sql2.write("[")
for line in arrs:
if type(line) == list:
if len(line)>0:
array2str(line, sql2)
elif len(line.strip())>0:
if sql2.tell() > 1:
sql2.write(',')
sql2.write('"')
sql2.write(line.strip().replace(">", ">").replace("<", "<").replace("\"", """).replace('\n', "<br>").replace('\t', "	").replace("'", "'").replace('\\', "\"))
sql2.write('"')
sql2.write("]")
if sql2.tell() != 2: # '[]' - empty array
if sql.tell() > 1:
sql.write(',')
sql.write(sql2.getvalue())
def prepareErrorTableLine(r, output, secret, issueN):
print("<tr", sep='', end='', file=output)
if len(r[5]) != 0 and r[10] is not None:
print(" class='marked original_conf'", sep='', end='', file=output)
elif len(r[5]) != 0:
print(" class='marked'", sep='', end='', file=output)
elif r[10] is not None:
print(" class='original_conf'", sep='', end='', file=output)
print(">", sep='', end='', file=output)
if issueN == 0:
print("<td align='center'><span class='errorId'><a href='", prefs.SITE_URL, "/s" if secret else "", "/reports/",str(r[0]),"'>",str(r[0]).zfill(5),"</a></span><br><span class='descTime'>",r[9],"<br>",r[11],"</span></td>", sep='', file=output)
errors_txt = r[1]+"<br><br>"
try:
errors_json = json.loads(r[1])
errors_txt = json2html.convert(json=errors_json, escape=0)
except:
erros_txt = r[1]
print("<td style='word-wrap: break-word'>",errors_txt,"</td>", file=output)
print("<td style='word-wrap: break-word;vertical-align: top;'>","<br>".join(r[2]),"</td>", sep='', file=output)
txt = r[5].replace("'","&")
if secret:
print("<td align='center'><input type='text' size='10' id='line",str(r[0]), "' title='", txt ,"' value='", txt, "' onchange='mark(\"line",str(r[0]),"\")'/>", sep='', file=output)
print("<br><small><a href='", prefs.SITE_URL,"/s/delete/",str(r[0]), "' ",'''onclick='return confirm("Вы уверены?")'>удалить</a></small>''', sep='', file=output)
else:
print("<td align='center'><input type='text' size='10' id='line",str(r[0]), "' title='", txt ,"' disabled value='", txt, "'/>", sep='', file=output)
print("<span class='descTime'><br>", r[6], "<br>", r[7], "</span>", sep='', file=output)
print("</td></tr>", sep='', file=output)
# строит html таблицу с описанием ошибок или таблицу для одной ошибки с номером issueN
# возвращает список stackId, присутствующих в выборке. Используется только если issueN != 0, а значит stackId последней и единственной записи.
# При построении таблицы выполняется группировка по номеру ошибки. Записи сортированные.
def prepareErrorTable(cur, output, secret, issueN = 0):
print("<table style='width: 100%; table-layout : fixed;' border=1><tr>", sep='', file=output)
if issueN == 0:
print("<th style='width: 3%'>N</th>", sep='', end='', file=output)
print("<th style='width: 60%'>Ошибки, errors</th><th style='width: 30%'>Конфигурация, версия и расширения</th><th style='width: 7%'>Метка</th></tr>", sep='', file=output)
pr = None
prev_issueN = 0
r = None
stackId = []
for r in cur.fetchall():
conf = r[2]+", "+r[3]
id = str(r[8])
stackId.append(id)
if len(r[4]) > 0 and issueN != 0:
ext_json = json.loads(r[4])
try:
ext_txt = json2html.convert(json=ext_json)
except ValueError:
ext_txt = str(ext_json)
conf += '<details><summary>'+str(len(ext_json))+' расширений</summary>'+ext_txt+"</details>\n"
if prev_issueN != r[0]:
if pr is not None:
prepareErrorTableLine(pr, output, secret, issueN)
prev_issueN = r[0]
pr = list(r)
pr[2] = {conf: 1}
else:
pr[2][conf] = 1
if pr is not None:
prepareErrorTableLine(pr, output, secret, issueN)
print("</table>", sep='', file=output)
return stackId
def readReport(fzip_name, environ):
tdir = tempfile.TemporaryDirectory()
with zipfile.ZipFile(fzip_name, 'r') as f:
zipInfo = f.infolist()
for member in zipInfo:
if member.filename == 'report.json':
f.extract(member, path=tdir.name)
with open(tdir.name+"/report.json", "r", encoding='utf-8') as read_file:
report = json.load(read_file)
tdir.cleanup()
return report
def send_mail():
conn = sqlite3.connect(prefs.DATA_PATH+"/reports.db")
try:
cur = conn.cursor()
SQLPacket = """select smtpQueue.issueId, min(reportStack.configName) configName, issue.errors from smtpQueue
inner join reportStack on reportStack.issueId=smtpQueue.issueId
inner join issue on reportStack.issueId=issue.issueId
group by smtpQueue.issueId, issue.errors"""
cur.execute(SQLPacket)
errors = []
for r in cur.fetchall():
errors.append(r)
cur.close()
SQLPacket = "delete from smtpQueue where issueId = ?"
s = None
s = smtplib.SMTP(prefs.SMTP_HOST, prefs.SMTP_PORT, timeout=10)
s.set_debuglevel(1)
#s.starttls()
if len(prefs.SMTP_LOGIN) > 0:
s.login(prefs.SMTP_LOGIN, prefs.SMTP_PASSWORD)
for r in errors:
output = StringIO()
print('Новая ошибка в сервисе регистрации ошибок: ', sep='', end='', file=output)
print(prefs.SITE_DOMAIN, prefs.SITE_URL, "/s/reports/", r[0], '\n', r[2], sep='', end='\n', file=output)
msg = MIMEText(output.getvalue(), 'plain', 'utf-8')
msg['Subject'] = Header('Ошибка '+r[1]+': '+r[2], 'utf-8')
msg['From'] = prefs.SMTP_FROM
msg['To'] = ", ".join(prefs.CONFIGS[r[1]][1])
s.sendmail(msg['From'], prefs.CONFIGS[r[1]][1], msg.as_string())
cur = conn.cursor()
cur.execute(SQLPacket, (r[0],))
cur.close()
conn.commit();
output.close()
finally:
if s is not None:
s.quit()
conn.close()
def insertReportStack(conn, report, issueId):
t = StringIO()
if 'extentions' in report['configInfo']:
array2str(report['configInfo']['extentions'], t)
else:
print("", sep='', end='', file=t)
i = (issueId, report['configInfo']['name'], report['configInfo']['version'], t.getvalue())
cur = conn.cursor()
cur.execute("select stackId from reportStack where issueId=? and configName=? and configVersion=? and extentions=?", i)
t = cur.fetchone()
cur.close()
stackId = t[0] if t is not None else None
if stackId is None:
cur = conn.cursor()
cur.execute("insert into reportStack (issueId,configName,configVersion,extentions) values (?,?,?,?)", i)
cur.close()
cur = conn.cursor()
cur.execute("select stackId from reportStack where issueId=? and configName=? and configVersion=? and extentions=?", i)
stackId = cur.fetchone()[0]
cur.close()
return stackId
def whois_cache(conn, environ):
cur = conn.cursor()
cur.execute("select time from whois where ip=?", (environ['REMOTE_ADDR'],))
whois_name = cur.fetchone()
cur.close()
if whois_name is not None:
year = datetime.datetime.now().strftime('%y')
if whois_name[0][6:8] != year:
cur = conn.cursor()
cur.execute("delete from whois where ip=?", (environ['REMOTE_ADDR'],))
cur.close()
conn.commit()
print("clear whois cache:", environ['REMOTE_ADDR'], whois_name[0], sep=' ', end='', file=environ["wsgi.errors"])
whois_name = None
if whois_name is None:
name = None
try:
name = whois.whois(environ['REMOTE_ADDR'])
except Exception as e:
print('ERROR: whois(', environ['REMOTE_ADDR'], ') ', str(e), sep=' ', end='', file=environ["wsgi.errors"])
pass
if name is not None and (name.domain_name is not None or name.org is not None):
cur = conn.cursor()
try:
cur.execute("insert into whois values (?,?,?,?)", (environ['REMOTE_ADDR'], name.domain_name, name.org, datetime.datetime.now().strftime('%d.%m.%y %H:%M')))
except sqlite3.IntegrityError as e:
pass
cur.close()
conn.commit()
else:
try:
obj = IPWhois(environ['REMOTE_ADDR'])
res = obj.lookup_whois()
except Exception as e:
print('ERROR: IPWhois(', environ['REMOTE_ADDR'], ') ', str(e), sep=' ', end='', file=environ["wsgi.errors"])
pass
if res is not None:
cur = conn.cursor()
try:
cur.execute("insert into whois values (?,?,?,?)", (environ['REMOTE_ADDR'], res['asn_cidr'], res['asn_description'], datetime.datetime.now().strftime('%d.%m.%y %H:%M')))
except sqlite3.IntegrityError as e:
pass
cur.close()
conn.commit()
def insertReport(conn, report, stackId, fn, environ, issueId, changeEnabled):
i = (report['time'],
report['sessionInfo']['userName'] if 'userName' in report['sessionInfo'] else "",
report['clientInfo']['appVersion'],
report['clientInfo']['platformType'],
report['serverInfo']['type'],
report['sessionInfo']['dataSeparation'],
report['serverInfo']['dbms'],
report['clientInfo']['systemInfo']['clientID'] if 'systemInfo' in report['clientInfo'] else "",
1,
fn,
1 if report['configInfo']['changeEnabled'] else 0,
stackId,
"<span class=\"descTime\">" + report['time'] + "</span> <span class=\"desc\">" + report['errorInfo']['userDescription'] + "</span>" if 'userDescription' in report['errorInfo'] and report['errorInfo']['userDescription'] != '' else None,
environ['REMOTE_ADDR'],
1 if 'additionalFiles' in report or 'additionalData' in report else 0,
report['errorInfo']['applicationErrorInfo']['stackHash'],
1 if 'screenshot' in report and report['screenshot'] is not None else 0)
cur = conn.cursor()
cur.execute("insert into report values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", i)
cur.close()
if not report['configInfo']['changeEnabled'] and changeEnabled != 0:
cur = conn.cursor()
cur.execute("update issue set changeEnabled=0 where issueId=(?)", (issueId,))
cur.close()
def inStopLists(environ):
blocked = False
addr = environ['REMOTE_ADDR']
for bl in prefs.BLACKLIST:
if addr[:len(bl)] == bl:
blocked = True
print("Address blocked by blacklist - ", addr, sep='', end='', file=environ['wsgi.errors'])
break
if not blocked and len(prefs.WHITELIST) > 0:
blocked = True
for wl in prefs.WHITELIST:
if addr[:len(wl)] == wl:
blocked = False
break
if blocked:
print("Address blocked by whitelist - ", addr, sep='', end='', file=environ['wsgi.errors'])
return blocked
def platformError(errors, environ):
try:
if errors[-1][0].startswith('При работе формы произошла системная ошибка'):
print("p1:", str(errors[-1]), file=environ["wsgi.errors"])
return True
if len(errors[-1][1]) > 0 and errors[-1][1][0] == "NetworkError": # ошибка обмена по сети
print("p2:", str(errors[-1]), file=environ["wsgi.errors"])
return True
if len(errors) > 1 and errors[1][0].startswith('Ошибка передачи данных между клиентом и сервером'):
print("p3:", str(errors[1]), file=environ["wsgi.errors"])
return True
if len(errors) > 1 and errors[1][0].startswith('Превышен максимальный расход памяти сервера за один вызов'):
print("p4:", str(errors[1]), file=environ["wsgi.errors"])
return True
if len(errors) > 1 and errors[-1][0].startswith('Внутренняя ошибка'):
print("p5:", str(errors[-1]), file=environ["wsgi.errors"])
return True
except:
print(str(errors), file=environ["wsgi.errors"])
raise
return False
def errorInConf(errors, stack, environ):
try:
if errors[0][0].startswith('{ВнешняяОбработка.') or errors[0][0].startswith('{ВнешнийОтчет.'):
print("e1:", errors[0][0], file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('{ВнешняяОбработка.') or errors[-1][0].startswith('{ВнешнийОтчет.'):
print("e4:", errors[-1][0], file=environ["wsgi.errors"])
return False
if errors[0][0].find('Неизвестный модуль') != -1:
print("e5:", errors[0][0], file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('Ошибка при выполнении файловой операции'):
print("e6:", errors[-1][0], file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('Конфликт блокировок при выполнении транзакции'):
print("e7:", errors[-1][0], file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('Ошибка блокировки объекта'):
print("e8:", errors[-1][0], file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('Ошибка совместного доступа к файлу'):
print("e9:", errors[-1][0], file=environ["wsgi.errors"])
return False
if errors[0][0].startswith('{Справочник.ВерсииРасширений.'):
print("e10:", errors[0][0], file=environ["wsgi.errors"])
return False
if errors[0][0].startswith('{mngbase'):
print("e11:", errors[0][0], file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('Не удалось заблокировать таблицу'):
print("e12:", errors[-1][0], file=environ["wsgi.errors"])
return False
if errors[0][0].startswith('{ОбщийМодуль.ЭлектроннаяПодпись') or errors[0][0].startswith('{ОбщийМодуль.РаботаСЭП'): # при проблемах с криптопровайдером в этом модуле генеряться ошибки
print("e13:", errors[0][0], file=environ["wsgi.errors"])
return False
if errors[0][0].startswith('{ОбщийМодуль.НапоминанияПользователяГлобальный') or errors[0][0].startswith('{ОбщийМодуль.СтандартныеПодсистемы') or errors[0][0].startswith('{ОбщийМодуль.ОбработкаНовостей') or errors[0][0].startswith('{ОбщийМодуль.СоединенияИБГлобальный'): # БСП
print("e14:", errors[0][0], file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('Недостаточно прав') or errors[-1][0].startswith('Нарушение прав доступа') or (len(errors[-1][1]) > 0 and errors[-1][1][0] == "AccessViolation"):
print("r1:", str(errors[-1]), file=environ["wsgi.errors"])
return False
if errors[-1][0].startswith('Ошибка доступа к файлу'):
print("r2:", str(errors[-1]), file=environ["wsgi.errors"])
return False
if len(errors[0][1]) > 0 and errors[0][1][-1] == "ExceptionRaisedFromScript":
print("u1:", str(errors[0]), file=environ["wsgi.errors"])
return False
if len(errors[-1][1]) > 0 and errors[-1][1][-1] == "ScriptCompileError":
print("c1:", str(errors[-1]), file=environ["wsgi.errors"])
return False
for e1 in errors:
e = e1[0]
dot = e.find('.')
if dot != -1:
space = e.find(' ', 2, dot)
if space != -1 and not e.startswith('{E'): # расширение, но не патч
print("e2:", e, file=environ["wsgi.errors"])
return False
if e.find('_', dot+1) != -1: # в имени объекта метаданных в тч в тексте ошибки есть подчеркивание, значит объект нетиповой или в тексте ошибки есть упоминание нетипового объекта
print("e3:", e, file=environ["wsgi.errors"])
return False
except:
print(str(errors), file=environ["wsgi.errors"])
raise
# Вызов из объекта пользователя
try:
for s1 in stack:
s = s1[0]
dot = s.find('.')
if dot != -1:
space = s.find(' ', 1, dot)
if space != -1 and not s.startswith('E'): #расширение, но не патч
print("s5:", s, file=environ["wsgi.errors"])
return False
pod = s.find('_', dot+1)
if pod != -1 and not(len(s) > pod+11 and s[pod:pod+11] == "__ОТЛАДКА__"): # в имени объекта метаданных есть подчеркивание, значит объект нетиповой, но в модуле __ОТЛАДКА__ ловим ошибку
print("s6:", s, file=environ["wsgi.errors"])
return False
if s.startswith('ВнешняяОбработка.') or s.startswith('ВнешнийОтчет.') or s.startswith('Справочник.ДополнительныеОтчетыИОбработки.') or s.startswith('ОбщийМодуль.ДополнительныеОтчетыИОбработки.'):
print("s4:", s, file=environ["wsgi.errors"])
return False
if s1[-1].find('ВнешняяОбработка') != -1 or s1[-1].find('ВнешнийОбъект') != -1:
print("s7:", s1[-1], file=environ["wsgi.errors"])
return False
if s.startswith('Обработка.ТестированиеШМД') or s.startswith('"Справочник.ВизуализаторыМедицинскихДокументов') or s.startswith('Обработка.ШМДВебДокумента'):
print("s8:", s, file=environ["wsgi.errors"])
return False
except:
print(str(stack), file=environ["wsgi.errors"])
raise
return True
def clear(conn, output, delete):
if not delete:
cur = conn.cursor()
cur.execute("select count(*) from issue")
totalErrorsCount = cur.fetchone()[0]
cur.close()
print("<p>Ошибок в базе - ", str(totalErrorsCount), "</p>", sep='', end='', file=output)
cur = conn.cursor()
cur.execute("select count(*) from report")
totalReportsCount = cur.fetchone()[0]
cur.close()
print("<p>Отчетов в базе - ", str(totalReportsCount), "</p>", sep='', end='', file=output)
# выбираем все отчеты и ошибки, которые надо оставить по критерию - конфа/версия
stackIds = set()
issueIds = set()
reportsCount = 0
for name in prefs.CONFIGS:
sql = StringIO()
start = True
print("select issueId, stackId from reportStack where configName='", name,"' and (", sep='', end='', file=sql)
for ver in prefs.CONFIGS[name][0]:
if not start:
print(" or", sep='', end='', file=sql)
else:
start = False
print(" configVersion like '", ver,"%'", sep='', end='', file=sql)
print(")", sep='', end='', file=sql)
cur = conn.cursor()
cur.execute(sql.getvalue())
for r in cur.fetchall():
issueIds.add(str(r[0]))
stackIds.add(str(r[1]))
cur.close()
sql.close()
# удаляем по блеклисту, не трогаем ошибки с комментариями
if len(prefs.BLACKLIST) > 0:
sql = StringIO()
cur = conn.cursor()
print("select reportStackId, file, issue.issueId from report innert join reportStack on reportStack.stackId=reportStackId inner join issue on issue.issueId=reportStack.issueId where issue.marked='' and (", sep='', end='', file=sql)
start = True
for ip in prefs.BLACKLIST:
if start:
start = False
else:
print(" or ", sep='', end='', file=sql)
print("REMOTE_ADDR like '", ip,"%'", sep='', end='', file=sql)
print(")", sep='', end='', file=sql)
cur = conn.cursor()
cur.execute(sql.getvalue())
if not delete:
print("<p>Удаляются отчеты от хостов из блеклиста:</p><ol>", file=output)
for r in cur.fetchall():
if str(r[0]) in stackIds:
stackIds.remove(str(r[0]))
if str(r[2]) in issueIds:
issueIds.remove(str(r[2]))
if len(r[1]) > 0 and os.path.exists(prefs.DATA_PATH+"/"+r[1]):
if delete:
os.remove(prefs.DATA_PATH+"/"+r[1])
elif not delete:
print("<li>"+prefs.DATA_PATH+"/"+r[1]+"</li>", file=output)
reportsCount += 1
if not delete:
print("</ol>", file=output)
cur.close()
sql.close()
# удаляем все отчеты, которые не соотвествуют критерию - конфа/версия
cur = conn.cursor()
cur.execute("select file from report where reportStackId not in ("+",".join(stackIds)+")")
if not delete:
print("<p>Удаляются отчеты неподдерживаемых конфигураций и версий:</p><ol>", file=output)
for r in cur.fetchall():
if len(r[0]) > 0 and os.path.exists(prefs.DATA_PATH+"/"+r[0]):
if delete:
os.remove(prefs.DATA_PATH+"/"+r[0])
elif not delete:
print("<li>"+prefs.DATA_PATH+"/"+r[0]+"</li>", file=output)
reportsCount += 1
if not delete:
print("</ol>", file=output)
cur.close()
if delete:
# удаляем все отчеты, которые не соотвествуют критерию - конфа/версия
cur = conn.cursor()
cur.execute("delete from report where reportStackId not in ("+",".join(stackIds)+")")
cur.close()
# удаляем все стеки, которые не соотвествуют критерию - конфа/версия
cur = conn.cursor()
cur.execute("delete from reportStack where stackId not in ("+",".join(stackIds)+")")
cur.close()
# получить список ошибок на которые ссылаются удаляемые репорты, но при этом есть ссылки на неудаляемые
cur = conn.cursor()
cur.execute("select reportStack.issueId from reportStack inner join report on reportStack.stackId=report.reportStackId where report.reportStackId in (" + ",".join(stackIds) + ")")
for r in cur.fetchall():
issueIds.add(str(r[0]))
cur.close()
if delete:
cur = conn.cursor()
cur.execute("delete from issue where issueId not in (" + ",".join(issueIds) + ")")
cur.close()
else:
cur = conn.cursor()
cur.execute("select issueId from issue where issueId not in (" + ",".join(issueIds) + ")")
print("<p>Удаляются ошибки:</p>", file=output)
errorsCount = 0
for r in cur.fetchall():
print("<a href='", prefs.SITE_URL, "/s/reports/",str(r[0]),"'>",str(r[0]).zfill(5),"</a><br>", sep='', file=output)
errorsCount += 1
cur.close()
print("</ol>", file=output)
print("<p>Удаляется ошибок: ", errorsCount, ", отчетов: ", reportsCount, "</p>", sep='', file=output)
print("<p>Остается ошибок: ", len(issueIds), ", отчетов: ", str(totalReportsCount-reportsCount), "</p>", sep='', file=output)
conn.commit()
def application(environ, start_response):
if environ['PATH_INFO'] == '/style.css':
style = b'''H2 {
font-family: Verdana, Tahoma, Arial, sans-serif;
}
H3 {
font-family: Verdana, Tahoma, Arial, sans-serif;
}
.descTime {
font-size: 70%;
}
.desc {
font-weight: bold;
color: red;
}
.errorId {
font-weight: bold;
color: black;
background-color: rgb(255,200,200);
font-family: Verdana, Tahoma, Arial, sans-serif;
font-size: 120%;
}
table {
display: table;
border-collapse: separate;
box-sizing: border-box;
white-space: normal;
line-height: normal;
font-weight: normal;
font-size: small;
font-style: normal;
color: -internal-quirk-inherit;
text-align: start;
border: 1px outset;
border-spacing: 0px;
border-color: grey;
font-variant: normal;
font-family: Verdana, Tahoma, Arial, sans-serif;
}
.marked {
background-color: rgb(190,255,255) !important;
}
.original_conf {
background-color: rgb(255,135,135);
}
.settings_table {
width: 50%;
font-family: Verdana, Tahoma, Arial, sans-serif;
}
p {
font-family: Verdana, Tahoma, Arial, sans-serif;
contain: content;
}
.refli {
font-family: Verdana, Tahoma, Arial, sans-serif;
list-style-type: circle;
margin-bottom: 5px
}
details {
display:inline;
}
details > summary {
font-size: 10px;
background-color: lightgrey;
padding: 0px;
margin: 0px 10px 5px 10px;
}
.summary {
font-size: 10px;
background-color: lightgrey;
padding: 0px;
margin: 0px 10px 5px 10px;
}
'''
start_response('200 OK', [
('Content-Type', 'text/css; charset=utf-8'),
('Content-Length', str(len(style)))
])
return [style]
if environ['PATH_INFO'] == '/tables.js':
output = StringIO()
print('''function mark(line) {
input = document.getElementById(line)
var error = line.substring(4)
var v = input.value
var http = new XMLHttpRequest();
http.open('POST', "''', prefs.SITE_URL, '''/s/markError/"+error, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if (http.status != 200) {
alert(http.status + " " + http.responseText);
}
}
http.send(v)
if (v.length == 0) {
input.parentElement.parentElement.classList.remove("marked")
} else {
input.parentElement.parentElement.classList.add("marked")
}
}
function selectConfig(configName, errorsList) {
if (configName != 'sn')
document.location.href="''', prefs.SITE_URL, '''/s/"+errorsList+"/"+configName.substring(1)
else
document.location.href="''', prefs.SITE_URL, '''/s/"+errorsList
}
function selectNetwork(network, errorsList) {
if (network != '')
document.location.href="''', prefs.SITE_URL, '''/s/"+errorsList+"/"+network.replace(/\//g, "⁄")
else
document.location.href="''', prefs.SITE_URL, '''/s/"+errorsList
}
''', sep='', file=output)
ret = output.getvalue().encode('UTF-8')
start_response('200 OK', [
('Content-Type', 'text/html; charset=utf-8'),
('Content-Length', str(len(ret)))
])
return [ret]
if environ['PATH_INFO'] == '/getInfo':
needSendReport = False
length = int(environ.get('CONTENT_LENGTH', '0'))
if length > 10000: # 10 kb limit
raise Exception('File is too large - '+environ.get('CONTENT_LENGTH', 0))
body = environ['wsgi.input'].read(length).decode('utf-8')
if len(body) > 1:
query = json.loads(body)
output = StringIO()
if 'test' in query:
needSendReport = True
elif query['configName'] in prefs.CONFIGS:
needSendReport = True
if needSendReport:
ret = '{"needSendReport":true,"userMessage":"Рекомендуем сформировать и отправить отчет разработчикам 1С:Медицина. При необходимости получения обратной связи свяжитесь с линией консультации по адресу med@1c.ru"}'.encode('UTF-8')
else:
ret = b'{"needSendReport":false}'
start_response('200 OK', [
('Content-Type', 'application/json; charset=utf-8'),
('Content-Length', str(len(ret)))
])
return [ret]
if environ['PATH_INFO'] == '/pushReport':
length = int(environ.get('CONTENT_LENGTH', 0))
if length > 10000000: # 10 mb limit
raise Exception('File is too large - '+environ.get('CONTENT_LENGTH', 0))
fzip = read(environ, length)
report = readReport(fzip.name, environ)
conn = sqlite3.connect(prefs.DATA_PATH+"/reports.db")
conn.execute("PRAGMA foreign_keys=ON;")
needStoreReport = False
if 'configInfo' in report and 'systemInfo' in report['clientInfo'] and report['configInfo']['name'] in prefs.CONFIGS:
try:
cur = conn.cursor()
cur.execute("select count(*) from clients where clientID=? and configName=?", (report['clientInfo']['systemInfo']['clientID'], report['configInfo']['name']))
cnt = cur.fetchone()[0]
cur.close()
if cnt == 0:
cur = conn.cursor()
cur.execute("insert into clients values (?,?,?,?,?)", (report['clientInfo']['systemInfo']['clientID'], report['configInfo']['name'], report['configInfo']['version'], environ['REMOTE_ADDR'], datetime.datetime.now().strftime('%d.%m.%y %H:%M')))
cur.close()
if prefs.USE_WHOIS:
whois_cache(conn, environ)
else:
cur = conn.cursor()
cur.execute("select count(*) from clients where clientID=? and configName=? and configVersion<>?", (report['clientInfo']['systemInfo']['clientID'], report['configInfo']['name'], report['configInfo']['version']))
cnt = cur.fetchone()[0]
cur.close()
if cnt != 0: # было обновление версии у клиента
cur = conn.cursor()
cur.execute("update clients set configVersion=?, time=? where clientID=? and configName=? and configVersion<>?", (report['configInfo']['version'], datetime.datetime.now().strftime('%d.%m.%y %H:%M'), report['clientInfo']['systemInfo']['clientID'], report['configInfo']['name'], report['configInfo']['version']))
cur.close()
else:
cur = conn.cursor()
cur.execute("update clients set time=? where clientID=? and configName=? and configVersion=?", (datetime.datetime.now().strftime('%d.%m.%y %H:%M'), report['clientInfo']['systemInfo']['clientID'], report['configInfo']['name'], report['configInfo']['version']))
cur.close()
conn.commit()
except Exception as e:
print(repr(e), file=environ["wsgi.errors"])
raise
if not inStopLists(environ):
for ver in prefs.CONFIGS[report['configInfo']['name']][0]:
if ver == report['configInfo']['version'][:len(ver)]:
needStoreReport = True
break
if needStoreReport:
# Если IP не в стоплисте и нет стека, ошибки или информации и конфе или ошибка во внешних объектах, то игнорируем отчет, так как нам интересны только ошибки модулей нашей конфы
full_data = ('stackHash' in report['errorInfo']['applicationErrorInfo'] and 'errors' in report['errorInfo']['applicationErrorInfo'] and 'configInfo' in report)
in_stop = inStopLists(environ)
in_conf = None
platform = None
if full_data and not in_stop:
in_conf = not prefs.ONLY_IN_CONF or errorInConf(report['errorInfo']['applicationErrorInfo']['errors'], report['errorInfo']['applicationErrorInfo']['stack'], environ)
if in_conf:
platform = platformError(report['errorInfo']['applicationErrorInfo']['errors'], environ)
if full_data and not in_stop and in_conf and not platform:
prev_issue = None
te = StringIO()
array2str(report['errorInfo']['applicationErrorInfo']['errors'], te)
# схлапываем те строки, которые размножают одну ошибку в отчетах
errors = re.sub(r"'file://.*?'", r"file://[path]", te.getvalue())
# убираем непечатные символы, русский берем из http://www.fileformat.info/info/unicode/category/index.htm
errors = u''.join([c for c in errors if unicodedata.category(c) in ('Lu', 'Ll') or c in string.printable])
cur = conn.cursor()
cur.execute("select issueId, changeEnabled, cnt, marked from issue where errors=?", (errors,))
issue = cur.fetchone()
cur.close()
fn = str(uuid.uuid4())+".zip"
needSendMail = False
needStoreReport = False
time = report['time'][:10]
if prefs.USE_WHOIS:
whois_cache(conn, environ)
if issue is None:
cur = conn.cursor()
cur.execute("insert into issue (errors, time) values (?,?)", (errors, time))
cur.close()
cur = conn.cursor()
cur.execute("select issueId, changeEnabled, cnt from issue where errors=?", (errors,))
row = cur.fetchone()
issueid = row[0]
changeEnabled = row[1]
cnt = row[2]
cur.close()
stack = insertReportStack(conn, report, issueid)
insertReport(conn, report, stack, fn, environ, issueid, changeEnabled)
needStoreReport = True
else:
issueid = issue[0]
changeEnabled = issue[1]
cnt = issue[2]
marked = issue[3]
if not(len(marked) > 1 and marked[0]) == "*": # ошибка отмечена как неподлежащая регистрации
cur = conn.cursor()
cur.execute("update issue set time=? where issueId=?", (time, issueid))
cur.close()
if 'systemInfo' in report['clientInfo'] and 'additionalFiles' not in report and 'additionalData' not in report:
i = (issueid, report['clientInfo']['systemInfo']['clientID'], report['configInfo']['name'], report['configInfo']['version'])
prev_reports = None
if 'screenshot' in report and report['screenshot'] is not None:
cur = conn.cursor()
# в запросе не учитываем записи с пустыми отчетами (удаленные из файловой системы по ошибке). Такие записи оставляем для истории
cur.execute("select report.rowid, report.count, report.userDescription from report inner join reportStack on reportStackId=stackId where hasScreenshot=1 and file!='' and issueId=? and clientID=? and configName=? and configVersion=?", i)
prev_reports = cur.fetchone()
cur.close()
else:
cur = conn.cursor()
# в запросе не учитываем записи с пустыми отчетами (удаленные из файловой системы по ошибке). Такие записи оставляем для истории
cur.execute("select report.rowid, report.count, report.userDescription from report inner join reportStack on reportStackId=stackId where file!='' and issueId=? and clientID=? and configName=? and configVersion=?", i)
prev_reports = cur.fetchone()
cur.close()
if prev_reports is not None:
descTime = report['time'][0:10]+" "+report['time'][11:]
if prev_reports[2] is not None and 'userDescription' in report['errorInfo'] and report['errorInfo']['userDescription'] != '':
SQLPacket = "update report set count="+str(prev_reports[1]+1)+", time='"+report['time']+"', userDescription='"
SQLPacket += prev_reports[2] +"<br><span class=\"descTime\">"+descTime+"</span> <span class=\"desc\">"+report['errorInfo']['userDescription']+"</span>'"
elif prev_reports[2] is None and 'userDescription' in report['errorInfo'] and report['errorInfo']['userDescription'] != '':
SQLPacket = "update report set count="+str(prev_reports[1]+1)+", time='"+report['time']+"', userDescription='"
SQLPacket += "<span class=\"descTime\">"+descTime+"</span> <span class=\"desc\">"+report['errorInfo']['userDescription']+"</span>'"
elif prev_reports[2] is not None:
SQLPacket = "update report set count="+str(prev_reports[1]+1)+", userDescription='"+prev_reports[2] +"<br><span class=\"descTime\">"+descTime+"</span>'"
else:
SQLPacket = "update report set count="+str(prev_reports[1]+1)+", userDescription='<span class=\"descTime\">"+descTime+"</span>'"
SQLPacket += " where rowid="+str(prev_reports[0])
cur = conn.cursor()
cur.execute(SQLPacket)
cur.close()
else:
stack = insertReportStack(conn, report, issueid)
insertReport(conn, report, stack, fn, environ, issueid, changeEnabled)
needStoreReport = True
cur = conn.cursor()
cur.execute('''select count(*) from (select *
from issue
inner join reportStack on reportStack.issueId=issue.issueId
inner join report on reportStack.stackId=report.reportStackId
where issue.issueId=? group by clientID)''', (issueid,))
cnt2 = cur.fetchone()[0]
cur.close()
cur = conn.cursor()
cur.execute("update issue set cnt=? where issueId=?", (cnt2, issueid))
cur.close()
if cnt != cnt2 and cnt == prefs.MIN_REPORTS and marked == '' and len(prefs.SMTP_HOST) > 0 and len(prefs.SMTP_FROM) > 0 and len(prefs.CONFIGS[report['configInfo']['name']][1]) > 0:
needSendMail = True
cur = conn.cursor()
cur.execute("insert into smtpQueue values (?)", (issueid,))
cur.close()
print("debug: need send", sep=' ', end='', file=environ["wsgi.errors"])
else:
stack = insertReportStack(conn, report, issueid)
insertReport(conn, report, stack, fn, environ, issueid, changeEnabled)
needStoreReport = True
else:
print("report already marked-'", marked, "' issueid=", issueid, sep='', end='', file=environ["wsgi.errors"])
conn.commit()
if needSendMail:
Thread(target=send_mail, args=()).start()
if needStoreReport:
shutil.copy(fzip.name, prefs.DATA_PATH+"/"+fn)
else:
t = StringIO()
print("report filtered: stopList - ", in_stop, ", full_data - ", full_data, ", in_conf - ", in_conf, ", platform - ", platform, sep='', end='', file=environ["wsgi.errors"])
conn.close()
start_response('200 OK', [
('Content-Type', 'application/json; charset=utf-8'),
('Content-Length', '0')
])
return b""
if environ['PATH_INFO'] == '/s/settings':
output = StringIO()
print('''<!DOCTYPE html><html><head>
<meta charset='utf-8'>
<link rel='stylesheet' href="''', prefs.SITE_URL, '''/style.css">
<title>Настройки сервиса регистрации ошибок 1С:Медицина</title>
</head><body><H2>Настройки сервиса регистрации ошибок</H2>
<p>Конфигурации и их версии, по которым принимаются отчеты об ошибках - </p>''', json2html.convert(json=prefs.CONFIGS, table_attributes="border=1 class='settings_table'"), '''
<p>В словаре (dict) ключ - имя конфигурации, значение - массив из 2-х массивов.</p>
<ul><li class='refli'>1-й список - список допустимых версий. Если список пустой, то отчеты не принимаются.
Пустая строка в версия - принимаются любые версии. Неполное задание версии допускатся.</li>
<li class='refli'>2-й список - список email, которым будет отправлено сообщение о регистрации новой ошибки.</li></ul>
<p>Отчет считается новой ошибкой, если образуется уникальная комбинация из следующих данных из отчета:</p>
<ul>
<li class='refli'>Текст ошибки</li>
<li class='refli'>Хеш стека ошибки конфигурации</li></ul>
<p>Если список email пустой, то почта для этой конфигурации не отправляется.</p>''', sep='', file=output)
print("<hr>Для изменения настроек необходимо изменить значения соответствующих переменных в файле prefs.py. После чего перестартовать апач.", sep='', file=output)
print("<hr><p>Черный список IP-адресов</p>", prefs.BLACKLIST, sep='', file=output)
print("<p>Белый список IP-адресов</p>", prefs.WHITELIST, sep='', file=output)
print("<hr><h3>Перейти:</h3>", sep='', file=output)
print("<ul><li class='refli'><a href='", prefs.SITE_URL, "/s/errorsList'>Список ошибок</a></lu>", sep='', file=output)
print("<li class='refli'><a href='", prefs.SITE_URL, "/s/clear'>Удаление отчетов неподдерживаемых версий и конфигураций, ошибок от IP из черного списка</a></li>", sep='', file=output)
print("</ul></body></html>", sep='', end='', file=output)
ret = output.getvalue().encode('UTF-8')
start_response('200 OK', [
('Content-Type', 'text/html; charset=utf-8'),
('Content-Length', str(len(ret)))
])
return [ret]
if environ['PATH_INFO'] == '/s/clients':
output = StringIO()
print('<!DOCTYPE html><html><head>', sep='', end='', file=output)
print("<meta charset='utf-8'>", sep='', file=output)
print("<link rel='stylesheet' href='", prefs.SITE_URL, "/style.css'>", sep='', file=output)
print("<title>Пользователи конфигураций</title>", sep='', file=output)
print("</head><body><h2>Пользователи конфигураций, отправившие отчеты об ошибках</h2>", sep='', file=output)
print("<p><small><span class='marked'>Бирюзовый фон</span> - отчеты регистрируются в соответствии с настройками</small></p>", sep='', file=output)
arms = 0
actual_arms = 0
clients = 0
conn = sqlite3.connect(prefs.DATA_PATH+"/reports.db")
conn.execute("PRAGMA foreign_keys=ON;")
cur = conn.cursor()
cur.execute('''select name, ifnull(org, name), configName, configVersion, count(clientID), max(clients.time)
from clients left join whois on ip=REMOTE_ADDR
group by ifnull(org, name), configName, configVersion
order by ifnull(org, name), configName, length(configVersion) DESC, configVersion DESC ''')
print("<table style='width: 100%; table-layout : fixed;' border=1><tr><th style='width: 10%'>FQDN или сеть</th><th style='width: 70%'>Описание</th><th style='width: 10%'>Конфигурация</th><th style='width: 10%'>Версия</th><th style='width: 5%'>АРМов</th><th style='width:7%'>Актуальность</th></tr>", sep='', file=output)
for r in cur.fetchall():
style = ''
for ver in prefs.CONFIGS[r[2]][0]:
if ver == r[3][:len(ver)]:
style = " class='marked'"
break