forked from diskoverdata/diskover-community
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diskover.py
executable file
·2241 lines (2020 loc) · 87.8 KB
/
diskover.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""diskover - Elasticsearch file system crawler
diskover is a file system crawler that index's
your file metadata into Elasticsearch.
See README.md or https://github.com/shirosaidev/diskover
for more information.
Copyright (C) Chris Park 2017-2019
diskover is released under the Apache 2.0 license. See
LICENSE for the full license text.
"""
from scandir import scandir
from rq import SimpleWorker, Queue
from rq.registry import StartedJobRegistry
from datetime import datetime
from random import randint
try:
import configparser as ConfigParser
except ImportError:
import ConfigParser
from multiprocessing import cpu_count
from threading import Thread, Lock
try:
from queue import Queue as PyQueue
except ImportError:
from Queue import Queue as PyQueue
import progressbar
import argparse
import logging
import imp
import time
import math
import re
import os
import sys
import json
import calendar
version = '1.5.0.6'
__version__ = version
IS_PY3 = sys.version_info >= (3, 0)
def print_banner(version):
"""This is the print banner function.
It prints a random banner.
"""
c = randint(1, 4)
if c == 1:
color = '31m'
elif c == 2:
color = '32m'
elif c == 3:
color = '33m'
elif c == 4:
color = '35m'
b = randint(1, 4)
if b == 1:
banner = """\033[%s
________ .__ __
\______ \ |__| _____| | _________ __ ___________
| | \| |/ ___/ |/ / _ \ \/ // __ \_ __ \\ /)___(\\
| ` \ |\___ \| < <_> ) /\ ___/| | \/ (='.'=)
/_______ /__/____ >__|_ \____/ \_/ \___ >__| (\\")_(\\")
\/ \/ \/ \/
v%s
https://shirosaidev.github.io/diskover
Crawling all your stuff.
Support diskover on Patreon or PayPal :)\033[0m
""" % (color, version)
elif b == 2:
banner = """\033[%s
___ ___ ___ ___ ___ ___ ___ ___
/\ \ /\ \ /\ \ /\__\ /\ \ /\__\ /\ \ /\ \\
/::\ \ _\:\ \ /::\ \ /:/ _/_ /::\ \ /:/ _/_ /::\ \ /::\ \\
/:/\:\__\ /\/::\__\ /\:\:\__\ /::-"\__\ /:/\:\__\ |::L/\__\ /::\:\__\ /::\:\__\\
\:\/:/ / \::/\/__/ \:\:\/__/ \;:;-",-" \:\/:/ / |::::/ / \:\:\/ / \;:::/ /
\::/ / \:\__\ \::/ / |:| | \::/ / L;;/__/ \:\/ / |:\/__/
\/__/ \/__/ \/__/ \|__| \/__/ \/__/ \|__|
v%s
https://shirosaidev.github.io/diskover
Bringing light to the darkness.
Support diskover on Patreon or PayPal :)\033[0m
""" % (color, version)
elif b == 3:
banner = """\033[%s
_/_/_/ _/ _/
_/ _/ _/_/_/ _/ _/ _/_/ _/ _/ _/_/ _/ _/_/
_/ _/ _/ _/_/ _/_/ _/ _/ _/ _/ _/_/_/_/ _/_/
_/ _/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/
_/_/_/ _/ _/_/_/ _/ _/ _/_/ _/ _/_/_/ _/
v%s
https://shirosaidev.github.io/diskover
"I didn't even know that was there."
Support diskover on Patreon or PayPal :)\033[0m
""" % (color, version)
elif b == 4:
banner = """\033[%s
__ __
/\ \ __ /\ \\
\_\ \/\_\ ____\ \ \/'\\ ___ __ __ __ _ __ //
/'_` \/\ \ /',__\\\ \ , < / __`\/\ \/\ \ /'__`\/\`'__\\ ('>
/\ \L\ \ \ \/\__, `\\\ \ \\\`\ /\ \L\ \ \ \_/ |/\ __/\ \ \/ /rr
\ \___,_\ \_\/\____/ \ \_\ \_\ \____/\ \___/ \ \____\\\ \\_\\ *\))_
\/__,_ /\/_/\/___/ \/_/\/_/\/___/ \/__/ \/____/ \\/_/
v%s
https://shirosaidev.github.io/diskover
"Holy s*i# there are so many temp files."
Support diskover on Patreon or PayPal :)\033[0m
""" % (color, version)
sys.stdout.write(banner)
sys.stdout.write('\n')
sys.stdout.flush()
def load_config():
"""This is the load config function.
It checks for config file and loads in
the config settings.
"""
configsettings = {}
config = ConfigParser.ConfigParser()
dir_path = os.path.dirname(os.path.realpath(__file__))
# check if env var for config file and use that
try:
configfile = os.environ['DISKOVER_CONFIG']
except KeyError:
configfile = '%s/diskover.cfg' % dir_path
pass
# Check for config file
if not os.path.isfile(configfile):
print('Config file %s not found, exiting.' % configfile)
sys.exit(1)
config.read(configfile)
# Check if any sections missing from config and exit if there is
try:
try:
d = config.get('excludes', 'dirs')
dirs = d.split(',')
configsettings['excluded_dirs'] = set(dirs)
except ConfigParser.NoOptionError:
configsettings['excluded_dirs'] = set([])
try:
f = config.get('excludes', 'files')
files = f.split(',')
configsettings['excluded_files'] = set(files)
except ConfigParser.NoOptionError:
configsettings['excluded_files'] = set([])
try:
d = config.get('includes', 'dirs')
dirs = d.split(',')
configsettings['included_dirs'] = set(dirs)
except (ConfigParser.NoOptionError):
configsettings['included_dirs'] = set([])
try:
f = config.get('includes', 'files')
files = f.split(',')
configsettings['included_files'] = set(files)
except ConfigParser.NoOptionError:
configsettings['included_files'] = set([])
try:
configsettings['ownersgroups_uidgidonly'] = config.get('ownersgroups', 'uidgidonly').lower()
except ConfigParser.NoOptionError:
configsettings['ownersgroups_uidgidonly'] = "false"
try:
configsettings['ownersgroups_domain'] = config.get('ownersgroups', 'domain').lower()
except ConfigParser.NoOptionError:
configsettings['ownersgroups_domain'] = "false"
try:
configsettings['ownersgroups_domainsep'] = config.get('ownersgroups', 'domainsep')
except ConfigParser.NoOptionError:
configsettings['ownersgroups_domainsep'] = "\\"
try:
configsettings['ownersgroups_keepdomain'] = config.get('ownersgroups', 'keepdomain').lower()
except ConfigParser.NoOptionError:
configsettings['ownersgroups_keepdomain'] = "false"
try:
t = config.get('autotag', 'files')
if os.path.isfile("%s/%s" % (os.getcwd(),t)):
atf = json.loads(open("%s/%s" % (os.getcwd(),t)).read())
else:
atf = json.loads(t)
configsettings['autotag_files'] = atf
except ValueError as e:
raise ValueError("Error in config autotag files: %s" % e)
except ConfigParser.NoOptionError:
configsettings['autotag_files'] = []
try:
t = config.get('autotag', 'dirs')
if os.path.isfile("%s/%s" % (os.getcwd(),t)):
atd = json.loads(open("%s/%s" % (os.getcwd(),t)).read())
else:
atd = json.loads(t)
configsettings['autotag_dirs'] = atd
except ValueError as e:
raise ValueError("Error in config autotag dirs: %s" % e)
except ConfigParser.NoOptionError:
configsettings['autotag_dirs'] = []
try:
configsettings['costpergb'] = float(config.get('storagecost', 'costpergb'))
except ConfigParser.NoOptionError:
configsettings['costpergb'] = 0.03
try:
configsettings['costpergb_base'] = int(config.get('storagecost', 'base'))
except ConfigParser.NoOptionError:
configsettings['costpergb_base'] = 2
try:
s = config.get('storagecost', 'paths')
if os.path.isfile("%s/%s" % (os.getcwd(),s)):
scp = json.loads(open("%s/%s" % (os.getcwd(),s)).read())
else:
scp = json.loads(s)
configsettings['costpergb_paths'] = scp
except ValueError as e:
raise ValueError("Error in config storagecost paths: %s" % e)
except ConfigParser.NoOptionError:
configsettings['costpergb_paths'] = []
try:
s = config.get('storagecost', 'times')
if os.path.isfile("%s/%s" % (os.getcwd(),s)):
sct = json.loads(open("%s/%s" % (os.getcwd(),s)).read())
else:
sct = json.loads(s)
configsettings['costpergb_times'] = sct
except ValueError as e:
raise ValueError("Error in config storagecost times: %s" % e)
except ConfigParser.NoOptionError:
configsettings['costpergb_times'] = []
try:
configsettings['costpergb_priority'] = config.get('storagecost', 'priority')
except ConfigParser.NoOptionError:
configsettings['costpergb_priority'] = "path"
try:
configsettings['aws'] = config.get('elasticsearch', 'aws').lower()
except ConfigParser.NoOptionError:
configsettings['aws'] = "false"
try:
h = config.get('elasticsearch', 'host')
hosts = h.split(',')
configsettings['es_host'] = hosts
except ConfigParser.NoOptionError:
configsettings['es_host'] = ['localhost']
try:
configsettings['es_port'] = int(config.get('elasticsearch', 'port'))
except ConfigParser.NoOptionError:
configsettings['es_port'] = 9200
try:
configsettings['es_user'] = config.get('elasticsearch', 'user')
except ConfigParser.NoOptionError:
configsettings['es_user'] = ""
try:
configsettings['es_password'] = config.get('elasticsearch', 'password')
except ConfigParser.NoOptionError:
configsettings['es_password'] = ""
try:
configsettings['index'] = config.get('elasticsearch', 'indexname')
except ConfigParser.NoOptionError:
configsettings['index'] = ""
try:
configsettings['es_timeout'] = int(config.get('elasticsearch', 'timeout'))
except ConfigParser.NoOptionError:
configsettings['es_timeout'] = 10
try:
configsettings['es_maxsize'] = int(config.get('elasticsearch', 'maxsize'))
except ConfigParser.NoOptionError:
configsettings['es_maxsize'] = 10
try:
configsettings['es_max_retries'] = int(config.get('elasticsearch', 'maxretries'))
except ConfigParser.NoOptionError:
configsettings['es_max_retries'] = 0
try:
configsettings['es_wait_status_yellow'] = config.get('elasticsearch', 'wait').lower()
except ConfigParser.NoOptionError:
configsettings['es_wait_status_yellow'] = "false"
try:
configsettings['es_chunksize'] = int(config.get('elasticsearch', 'chunksize'))
except ConfigParser.NoOptionError:
configsettings['es_chunksize'] = 500
try:
configsettings['index_shards'] = int(config.get('elasticsearch', 'shards'))
except ConfigParser.NoOptionError:
configsettings['index_shards'] = 5
try:
configsettings['index_replicas'] = int(config.get('elasticsearch', 'replicas'))
except ConfigParser.NoOptionError:
configsettings['index_replicas'] = 1
try:
configsettings['index_refresh'] = config.get('elasticsearch', 'indexrefresh')
except ConfigParser.NoOptionError:
configsettings['index_refresh'] = "1s"
try:
configsettings['disable_replicas'] = config.get('elasticsearch', 'disablereplicas').lower()
except ConfigParser.NoOptionError:
configsettings['disable_replicas'] = "false"
try:
configsettings['index_translog_size'] = config.get('elasticsearch', 'translogsize')
except ConfigParser.NoOptionError:
configsettings['index_translog_size'] = "512mb"
try:
configsettings['es_scrollsize'] = int(config.get('elasticsearch', 'scrollsize'))
except ConfigParser.NoOptionError:
configsettings['es_scrollsize'] = 100
try:
configsettings['redis_host'] = config.get('redis', 'host')
except ConfigParser.NoOptionError:
configsettings['redis_host'] = "localhost"
try:
configsettings['redis_port'] = int(config.get('redis', 'port'))
except ConfigParser.NoOptionError:
configsettings['redis_port'] = 6379
try:
configsettings['redis_socket'] = config.get('redis', 'socket')
except ConfigParser.NoOptionError:
configsettings['redis_socket'] = ""
try:
configsettings['redis_password'] = config.get('redis', 'password')
except ConfigParser.NoOptionError:
configsettings['redis_password'] = ""
try:
configsettings['redis_cachedirtimes'] = config.get('redis', 'cachedirtimes').lower()
except ConfigParser.NoOptionError:
configsettings['redis_cachedirtimes'] = "false"
try:
configsettings['redis_dirtimesttl'] = int(config.get('redis', 'dirtimesttl'))
except ConfigParser.NoOptionError:
configsettings['redis_dirtimesttl'] = 604800
try:
configsettings['redis_db'] = int(config.get('redis', 'db'))
except ConfigParser.NoOptionError:
configsettings['redis_db'] = 0
try:
configsettings['redis_rq_timeout'] = int(config.get('redis', 'timeout'))
except ConfigParser.NoOptionError:
configsettings['redis_rq_timeout'] = 180
try:
configsettings['redis_ttl'] = int(config.get('redis', 'ttl'))
except ConfigParser.NoOptionError:
configsettings['redis_ttl'] = 500
try:
configsettings['redis_queue'] = config.get('redis', 'queue')
except ConfigParser.NoOptionError:
configsettings['redis_queue'] = "diskover"
try:
configsettings['redis_queue_crawl'] = config.get('redis', 'queuecrawl')
except ConfigParser.NoOptionError:
configsettings['redis_queue_crawl'] = "diskover_crawl"
try:
configsettings['redis_queue_calcdir'] = config.get('redis', 'queuecalcdir')
except ConfigParser.NoOptionError:
configsettings['redis_queue_calcdir'] = "diskover_calcdir"
try:
configsettings['adaptivebatch_startsize'] = int(config.get('adaptivebatch', 'startsize'))
except ConfigParser.NoOptionError:
configsettings['adaptivebatch_startsize'] = 50
try:
configsettings['adaptivebatch_maxsize'] = int(config.get('adaptivebatch', 'maxsize'))
except ConfigParser.NoOptionError:
configsettings['autobatch_maxsize'] = 500
try:
configsettings['adaptivebatch_stepsize'] = int(config.get('adaptivebatch', 'stepsize'))
except ConfigParser.NoOptionError:
configsettings['adaptivebatch_stepsize'] = 10
try:
configsettings['adaptivebatch_maxfiles'] = int(config.get('adaptivebatch', 'maxfiles'))
except ConfigParser.NoOptionError:
configsettings['adaptivebatch_maxfiles'] = 50000
try:
configsettings['listener_host'] = config.get('socketlistener', 'host')
except ConfigParser.NoOptionError:
configsettings['listener_host'] = "localhost"
try:
configsettings['listener_port'] = int(config.get('socketlistener', 'port'))
except ConfigParser.NoOptionError:
configsettings['listener_port'] = 9999
try:
configsettings['listener_maxconnections'] = int(config.get('socketlistener', 'maxconnections'))
except ConfigParser.NoOptionError:
configsettings['listener_maxconnections'] = 5
try:
configsettings['listener_twcport'] = int(config.get('socketlistener', 'twcport'))
except ConfigParser.NoOptionError:
configsettings['listener_twcport'] = 9998
try:
configsettings['diskover_path'] = config.get('paths', 'diskoverpath')
except ConfigParser.NoOptionError:
configsettings['diskover_path'] = "./diskover.py"
try:
configsettings['python_path'] = config.get('paths', 'pythonpath')
except ConfigParser.NoOptionError:
configsettings['python_path'] = "python"
try:
configsettings['md5_readsize'] = int(config.get('dupescheck', 'readsize'))
except ConfigParser.NoOptionError:
configsettings['md5_readsize'] = 65536
try:
configsettings['dupes_maxsize'] = int(config.get('dupescheck', 'maxsize'))
except ConfigParser.NoOptionError:
configsettings['dupes_maxsize'] = 1073741824
try:
configsettings['dupes_checkbytes'] = int(config.get('dupescheck', 'checkbytes'))
except ConfigParser.NoOptionError:
configsettings['dupes_checkbytes'] = 64
try:
configsettings['dupes_restoretimes'] = config.get('dupescheck', 'restoretimes').lower()
except ConfigParser.NoOptionError:
configsettings['dupes_restoretimes'] = "false"
try:
configsettings['dupes_threads'] = int(config.get('dupescheck', 'threads'))
except ConfigParser.NoOptionError:
configsettings['dupes_threads'] = 8
try:
configsettings['crawlbot_botsleep'] = float(config.get('crawlbot', 'sleeptime'))
except ConfigParser.NoOptionError:
configsettings['crawlbot_botsleep'] = 0.1
try:
configsettings['crawlbot_botthreads'] = int(config.get('crawlbot', 'botthreads'))
except ConfigParser.NoOptionError:
configsettings['crawlbot_botthreads'] = 8
try:
configsettings['crawlbot_dirlisttime'] = int(config.get('crawlbot', 'dirlisttime'))
except ConfigParser.NoOptionError:
configsettings['crawlbot_dirlisttime'] = 3600
try:
configsettings['gource_maxfilelag'] = float(config.get('gource', 'maxfilelag'))
except ConfigParser.NoOptionError:
configsettings['gource_maxfilelag'] = 5
try:
configsettings['api_url'] = config.get('crawlapi', 'url')
except ConfigParser.NoOptionError:
configsettings['api_url'] = ""
try:
configsettings['api_user'] = config.get('crawlapi', 'user')
except ConfigParser.NoOptionError:
configsettings['api_user'] = ""
try:
configsettings['api_password'] = config.get('crawlapi', 'password')
except ConfigParser.NoOptionError:
configsettings['api_password'] = ""
try:
configsettings['api_pagesize'] = config.get('crawlapi', 'pagesize')
except ConfigParser.NoOptionError:
configsettings['api_pagesize'] = ""
except ConfigParser.NoSectionError as e:
print('Missing section from diskover.cfg, check diskover.cfg.sample and copy over, exiting. (%s)' % e)
sys.exit(1)
return configsettings, configfile
def get_plugins_info():
"""This is the get plugins info function.
It gets a list of python plugins info (modules) in
the plugins directory and returns the plugins information.
"""
plugin_dir = os.path.dirname(os.path.realpath(__file__)) + "/plugins"
main_module = "__init__"
plugins_info = []
possible_plugins = os.listdir(plugin_dir)
for i in possible_plugins:
location = os.path.join(plugin_dir, i)
if not os.path.isdir(location) or not main_module + ".py" \
in os.listdir(location):
continue
info = imp.find_module(main_module, [location])
plugins_info.append({"name": i, "info": info})
return plugins_info
def load_plugins():
"""This is the load plugins function.
It dynamically load the plugins and return them in a list
"""
loaded_plugins = []
plugins_info = get_plugins_info()
for plugin_info in plugins_info:
plugin_module = imp.load_module(plugin_info["name"], *plugin_info["info"])
loaded_plugins.append(plugin_module)
return loaded_plugins
def list_plugins():
"""This is the list plugins function.
It prints the name of all the available plugins
"""
plugins_info = get_plugins_info()
for plugin_info in plugins_info:
print(plugin_info["name"])
def user_prompt(question):
""" Prompt the yes/no-*question* to the user. """
from distutils.util import strtobool
while True:
try:
if IS_PY3:
user_input = input(question + " [y/n]: ").lower()
else:
user_input = raw_input(question + " [y/n]: ").lower()
result = strtobool(user_input)
return result
except ValueError:
print("Please use y/n or yes/no.\n")
except KeyboardInterrupt:
print("Ctrl-c keyboard interrupt, shutting down...")
sys.exit(0)
def index_create(indexname):
"""This is the es index create function.
It checks for existing index and deletes if
there is one with same name. It also creates
the new index and sets up mappings.
"""
logger.info('Checking es index: %s', indexname)
# check for existing es index
if es.indices.exists(index=indexname):
# check if crawlbot or reindex cli argument and don't delete existing index
if cliargs['reindex']:
logger.info('Reindexing (non-recursive, preserving tags)')
return
elif cliargs['reindexrecurs']:
logger.info('Reindexing (recursive, preserving tags)')
return
elif cliargs['crawlbot']:
return
# delete existing index
else:
if cliargs['forcedropexisting']:
logger.warning('es index exists, deleting')
es.indices.delete(index=indexname, ignore=[400, 404])
else:
if user_prompt("Drop existing index?"):
logger.warning('es index exists, deleting')
es.indices.delete(index=indexname, ignore=[400, 404])
else:
logger.info("Cannot continue with index. Exiting.")
sys.exit(1)
# set up es index mappings and create new index
if cliargs['s3']:
from diskover_s3 import get_s3_mappings
mappings = get_s3_mappings(config)
else:
mappings = {
"settings": {
"index" : {
"number_of_shards": config['index_shards'],
"number_of_replicas": config['index_replicas']
}
},
"mappings": {
"diskspace": {
"properties": {
"path": {
"type": "keyword"
},
"total": {
"type": "long"
},
"used": {
"type": "long"
},
"free": {
"type": "long"
},
"available": {
"type": "long"
},
"indexing_date": {
"type": "date"
}
}
},
"crawlstat": {
"properties": {
"path": {
"type": "keyword"
},
"state": {
"type": "text"
},
"crawl_time": {
"type": "float"
},
"indexing_date": {
"type": "date"
}
}
},
"worker": {
"properties": {
"worker_name": {
"type": "keyword"
},
"dir_count": {
"type": "integer"
},
"file_count": {
"type": "integer"
},
"bulk_time": {
"type": "float"
},
"crawl_time": {
"type": "float"
},
"indexing_date": {
"type": "date"
}
}
},
"directory": {
"properties": {
"filename": {
"type": "keyword"
},
"path_parent": {
"type": "keyword"
},
"filesize": {
"type": "long"
},
"items": {
"type": "long"
},
"items_files": {
"type": "long"
},
"items_subdirs": {
"type": "long"
},
"owner": {
"type": "keyword"
},
"group": {
"type": "keyword"
},
"last_modified": {
"type": "date"
},
"last_access": {
"type": "date"
},
"last_change": {
"type": "date"
},
"hardlinks": {
"type": "integer"
},
"inode": {
"type": "keyword"
},
"tag": {
"type": "keyword"
},
"tag_custom": {
"type": "keyword"
},
"crawl_time": {
"type": "float"
},
"change_percent_filesize": {
"type": "float"
},
"change_percent_items": {
"type": "float"
},
"change_percent_items_files": {
"type": "float"
},
"change_percent_items_subdirs": {
"type": "float"
},
"costpergb": {
"type": "scaled_float",
"scaling_factor": 100
},
"worker_name": {
"type": "keyword"
},
"indexing_date": {
"type": "date"
}
}
},
"file": {
"properties": {
"filename": {
"type": "keyword"
},
"extension": {
"type": "keyword"
},
"path_parent": {
"type": "keyword"
},
"filesize": {
"type": "long"
},
"owner": {
"type": "keyword"
},
"group": {
"type": "keyword"
},
"last_modified": {
"type": "date"
},
"last_access": {
"type": "date"
},
"last_change": {
"type": "date"
},
"hardlinks": {
"type": "integer"
},
"inode": {
"type": "keyword"
},
"filehash": {
"type": "keyword"
},
"tag": {
"type": "keyword"
},
"tag_custom": {
"type": "keyword"
},
"dupe_md5": {
"type": "keyword"
},
"costpergb": {
"type": "scaled_float",
"scaling_factor": 100
},
"worker_name": {
"type": "keyword"
},
"indexing_date": {
"type": "date"
}
}
}
}
}
# check plugins for additional mappings
for plugin in plugins:
mappings = (plugin.add_mappings(mappings))
logger.info('Creating es index')
es.indices.create(index=indexname, body=mappings)
time.sleep(.5)
def index_bulk_add(es, doclist, config, cliargs):
"""This is the es index bulk add function.
It bulk adds/updates/removes using file/directory
meta data lists from worker's crawl results.
"""
if config['es_wait_status_yellow'] == "true":
# wait for es health to be at least yellow
es.cluster.health(wait_for_status='yellow',
request_timeout=config['es_timeout'])
# bulk load data to Elasticsearch index
diskover_connections.helpers.bulk(es, doclist, index=cliargs['index'],
chunk_size=config['es_chunksize'], request_timeout=config['es_timeout'])
def index_delete_path(path, cliargs, logger, reindex_dict, recursive=False):
"""This is the es delete path bulk function.
It finds all file and directory docs in path and deletes them from es
including the directory (path).
Recursive will also find and delete all docs in subdirs of path.
Stores any existing tags in reindex_dict.
Returns reindex_dict.
"""
file_id_list = []
dir_id_list = []
file_delete_list = []
dir_delete_list = []
# refresh index
es.indices.refresh(index=cliargs['index'])
# escape special characters
newpath = escape_chars(path)
# create wildcard string and check for / (root) path
if newpath == '\/':
newpathwildcard = '\/*'
else:
newpathwildcard = newpath + '\/*'
# file doc search
if recursive:
data = {
"query": {
"query_string": {
"query": "path_parent: " + newpath + " OR "
"path_parent: " + newpathwildcard,
"analyze_wildcard": "true"
}
}
}
else:
data = {
"query": {
"query_string": {
"query": "path_parent: " + newpath
}
}
}
logger.info('Searching for all files in %s' % path)
# search es and start scroll
res = es.search(index=cliargs['index'], doc_type='file', scroll='1m',
size=config['es_scrollsize'], body=data,
request_timeout=config['es_timeout'])
while res['hits']['hits'] and len(res['hits']['hits']) > 0:
for hit in res['hits']['hits']:
# add doc id to file_id_list
file_id_list.append(hit['_id'])
# add file path info inc. tags to reindex_file_list
reindex_dict['file'].append((hit['_source']['path_parent'] +
'/' + hit['_source']['filename'],
hit['_source']['tag'],
hit['_source']['tag_custom']))
# get es scroll id
scroll_id = res['_scroll_id']
# use es scroll api
res = es.scroll(scroll_id=scroll_id, scroll='1m',
request_timeout=config['es_timeout'])
logger.info('Found %s files for %s' % (len(file_id_list), path))
# add file id's to delete_list
for i in file_id_list:
d = {
'_op_type': 'delete',
'_index': cliargs['index'],
'_type': 'file',
'_id': i
}
file_delete_list.append(d)
if len(file_delete_list) > 0:
# bulk delete files in es
logger.info('Bulk deleting files in es index')
index_bulk_add(es, file_delete_list, config, cliargs)
# directory doc search
if recursive:
data = {
'query': {
'query_string': {
'query': '(path_parent: ' + newpath + ') OR '
'(path_parent: ' + newpathwildcard + ') OR (filename: "'
+ os.path.basename(path) + '" AND path_parent: "'
+ os.path.abspath(os.path.join(path, os.pardir)) + '")',
'analyze_wildcard': 'true'
}
}
}
else:
data = {
'query': {
'query_string': {
'query': '(path_parent: ' + newpath + ') OR (filename: "'
+ os.path.basename(path) + '" AND path_parent: "'
+ os.path.abspath(os.path.join(path, os.pardir)) + '")'
}
}
}
logger.info('Searching for all directories in %s' % path)
# search es and start scroll
res = es.search(index=cliargs['index'], doc_type='directory', scroll='1m',
size=config['es_scrollsize'], body=data, request_timeout=config['es_timeout'])
while res['hits']['hits'] and len(res['hits']['hits']) > 0:
for hit in res['hits']['hits']:
# add directory doc id to dir_id_list
dir_id_list.append(hit['_id'])
# add directory path info inc. tags, filesize, items to reindex_dir_list
reindex_dict['directory'].append((hit['_source']['path_parent'] +
'/' + hit['_source']['filename'],
hit['_source']['tag'],
hit['_source']['tag_custom']))
# get es scroll id
scroll_id = res['_scroll_id']
# use es scroll api
res = es.scroll(scroll_id=scroll_id, scroll='1m',
request_timeout=config['es_timeout'])
logger.info('Found %s directories for %s' % (len(dir_id_list), path))
# add dir id's to delete_list
for i in dir_id_list:
d = {
'_op_type': 'delete',
'_index': cliargs['index'],
'_type': 'directory',
'_id': i
}
dir_delete_list.append(d)
if len(dir_delete_list) > 0:
# bulk delete directories in es
logger.info('Bulk deleting directories in es index')
index_bulk_add(es, dir_delete_list, config, cliargs)
return reindex_dict
def index_get_docs(cliargs, logger, doctype='directory', copytags=False, hotdirs=False,
index=None, path=None, sort=False, maxdepth=None, pathid=False):
"""This is the es get docs function.
It finds all docs (by doctype) in es and returns doclist
which contains doc id, fullpath and mtime for all docs.
If copytags is True will return tags from previous index.
If path is specified will return just documents in and under directory path.
If sort is True, will return paths in asc path order.
if pathid is True, will return dict with path and their id.
"""
data = _index_get_docs_data(index, cliargs, logger, doctype=doctype, path=path,
maxdepth=maxdepth, sort=sort)
# refresh index
es.indices.refresh(index)
# search es and start scroll
res = es.search(index=index, doc_type=doctype, scroll='1m',
size=config['es_scrollsize'], body=data, request_timeout=config['es_timeout'])
doclist = []
pathdict = {}
doccount = 0
while res['hits']['hits'] and len(res['hits']['hits']) > 0:
for hit in res['hits']['hits']:
fullpath = os.path.abspath(os.path.join(hit['_source']['path_parent'], hit['_source']['filename']))
if copytags:
doclist.append((fullpath, hit['_source']['tag'], hit['_source']['tag_custom'], doctype))
elif hotdirs:
doclist.append((hit['_id'], fullpath, hit['_source']['filesize'], hit['_source']['items'],
hit['_source']['items_files'], hit['_source']['items_subdirs']))
elif pathid:
rel_path = fullpath.replace(rootdir_path, ".")
pathdict[rel_path] = hit['_id']
else:
# convert es time to unix time format
mtime = calendar.timegm(datetime.strptime(
hit['_source']['last_modified'],
'%Y-%m-%dT%H:%M:%S').utctimetuple())
doclist.append((hit['_id'], fullpath, mtime, doctype))
doccount += 1
# use es scroll api
res = es.scroll(scroll_id=res['_scroll_id'], scroll='1m',
request_timeout=config['es_timeout'])
logger.info('Found %s %s docs' % (str(doccount), doctype))
if pathid:
return pathdict
else:
return doclist
def _index_get_docs_data(index, cliargs, logger, doctype='directory', path=None, maxdepth=None, sort=False):
if cliargs['copytags']:
logger.info('Searching for all %s docs with tags in %s...', doctype, index)
data = {
'_source': ['path_parent', 'filename', 'tag', 'tag_custom'],
'query': {
'query_string': {
'query': 'tag:(NOT "") OR tag_custom:(NOT "")'
}
}
}
elif cliargs['hotdirs']:
logger.info('Searching for all %s docs in %s...', doctype, index)
data = {