/
utils.py
1910 lines (1767 loc) · 74 KB
/
utils.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 elasticsearch
import time
import logging
import yaml, os, random, re, string, sys
from datetime import timedelta, datetime, date
from voluptuous import Schema
from curator import exceptions
from curator.defaults import settings
from curator.validators import SchemaCheck, actions, filters, options
from curator._version import __version__
logger = logging.getLogger(__name__)
def read_file(myfile):
"""
Read a file and return the resulting data.
:arg myfile: A file to read.
:rtype: str
"""
try:
with open(myfile, 'r') as f:
data = f.read()
return data
except IOError:
raise exceptions.FailedExecution(
'Unable to read file {0}'.format(myfile)
)
def get_yaml(path):
"""
Read the file identified by `path` and import its YAML contents.
:arg path: The path to a YAML configuration file.
:rtype: dict
"""
# Set the stage here to parse single scalar value environment vars from
# the YAML file being read
single = re.compile( r'^\$\{(.*)\}$' )
yaml.add_implicit_resolver ( "!single", single )
def single_constructor(loader,node):
value = loader.construct_scalar(node)
proto = single.match(value).group(1)
default = None
if len(proto.split(':')) > 1:
envvar, default = proto.split(':')
else:
envvar = proto
return os.environ[envvar] if envvar in os.environ else default
yaml.add_constructor('!single', single_constructor)
raw = read_file(path)
try:
cfg = yaml.load(raw)
except yaml.scanner.ScannerError as e:
raise exceptions.ConfigurationError(
'Unable to parse YAML file. Error: {0}'.format(e))
return cfg
def test_client_options(config):
"""
Test whether a SSL/TLS files exist. Will raise an exception if the files
cannot be read.
:arg config: A client configuration file data dictionary
:rtype: None
"""
if config['use_ssl']:
# Test whether certificate is a valid file path
if 'certificate' in config and config['certificate']:
read_file(config['certificate'])
# Test whether client_cert is a valid file path
if 'client_cert' in config and config['client_cert']:
read_file(config['client_cert'])
# Test whether client_key is a valid file path
if 'client_key' in config and config['client_key']:
read_file(config['client_key'])
def rollable_alias(client, alias):
"""
Ensure that `alias` is an alias, and points to an index that can use the
_rollover API.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg alias: An Elasticsearch alias
"""
try:
response = client.indices.get_alias(name=alias)
except elasticsearch.exceptions.NotFoundError:
logger.error('alias "{0}" not found.'.format(alias))
return False
# Response should be like:
# {'there_should_be_only_one': {u'aliases': {'value of "alias" here': {}}}}
# Where 'there_should_be_only_one' is a single index name that ends in a
# number, and 'value of "alias" here' reflects the value of the passed
# parameter.
if len(response) > 1:
logger.error(
'"alias" must only reference one index: {0}'.format(response))
# elif len(response) < 1:
# logger.error(
# '"alias" must reference at least one index: {0}'.format(response))
else:
index = list(response.keys())[0]
rollable = False
# In order for `rollable` to be True, the last 2 digits of the index
# must be digits, or a hyphen followed by a digit.
# NOTE: This is not a guarantee that the rest of the index name is
# necessarily correctly formatted.
if index[-2:][1].isdigit():
if index[-2:][0].isdigit():
rollable = True
elif index[-2:][0] == '-':
rollable = True
return rollable
def verify_client_object(test):
"""
Test if `test` is a proper :class:`elasticsearch.Elasticsearch` client
object and raise an exception if it is not.
:arg test: The variable or object to test
:rtype: None
"""
# Ignore mock type for testing
if str(type(test)) == "<class 'mock.Mock'>" or \
str(type(test)) == "<class 'mock.mock.Mock'>":
pass
elif not isinstance(test, elasticsearch.Elasticsearch):
raise TypeError(
'Not a client object. Type: {0}'.format(type(test))
)
def verify_index_list(test):
"""
Test if `test` is a proper :class:`curator.indexlist.IndexList` object and
raise an exception if it is not.
:arg test: The variable or object to test
:rtype: None
"""
# It breaks if this import isn't local to this function
from .indexlist import IndexList
if not isinstance(test, IndexList):
raise TypeError(
'Not an IndexList object. Type: {0}.'.format(type(test))
)
def verify_snapshot_list(test):
"""
Test if `test` is a proper :class:`curator.snapshotlist.SnapshotList`
object and raise an exception if it is not.
:arg test: The variable or object to test
:rtype: None
"""
# It breaks if this import isn't local to this function
from .snapshotlist import SnapshotList
if not isinstance(test, SnapshotList):
raise TypeError(
'Not an SnapshotList object. Type: {0}.'.format(type(test))
)
def report_failure(exception):
"""
Raise a `exceptions.FailedExecution` exception and include the original error message.
:arg exception: The upstream exception.
:rtype: None
"""
raise exceptions.FailedExecution(
'Exception encountered. Rerun with loglevel DEBUG and/or check '
'Elasticsearch logs for more information. '
'Exception: {0}'.format(exception)
)
def get_date_regex(timestring):
"""
Return a regex string based on a provided strftime timestring.
:arg timestring: An strftime pattern
:rtype: str
"""
prev = ''; curr = ''; regex = ''
for s in range(0, len(timestring)):
curr = timestring[s]
if curr == '%':
pass
elif curr in settings.date_regex() and prev == '%':
regex += r'\d{' + settings.date_regex()[curr] + '}'
elif curr in ['.', '-']:
regex += "\\" + curr
else:
regex += curr
prev = curr
logger.debug("regex = {0}".format(regex))
return regex
def get_datetime(index_timestamp, timestring):
"""
Return the datetime extracted from the index name, which is the index
creation time.
:arg index_timestamp: The timestamp extracted from an index name
:arg timestring: An strftime pattern
:rtype: :py:class:`datetime.datetime`
"""
# Compensate for week of year by appending '%w' to the timestring
# and '1' (Monday) to index_timestamp
iso_week_number = False
if '%W' in timestring or '%U' in timestring or '%V' in timestring:
timestring += '%w'
index_timestamp += '1'
if '%V' in timestring and '%G' in timestring:
iso_week_number = True
# Fake as so we read Greg format instead. We will process it later
timestring = timestring.replace("%G", "%Y").replace("%V", "%W")
elif '%m' in timestring:
if not '%d' in timestring:
timestring += '%d'
index_timestamp += '1'
date = datetime.strptime(index_timestamp, timestring)
# Handle ISO time string
if iso_week_number:
date = _handle_iso_week_number(date, timestring, index_timestamp)
return date
def fix_epoch(epoch):
"""
Fix value of `epoch` to be epoch, which should be 10 or fewer digits long.
:arg epoch: An epoch timestamp, in epoch + milliseconds, or microsecond, or
even nanoseconds.
:rtype: int
"""
# No decimals allowed
epoch = int(epoch)
# If we're still using this script past January, 2038, we have bigger
# problems than my hacky math here...
if len(str(epoch)) <= 10:
return epoch
elif len(str(epoch)) == 13:
return int(epoch/1000)
elif len(str(epoch)) > 10 and len(str(epoch)) < 13:
raise ValueError(
'Unusually formatted epoch timestamp. '
'Should be 10, 13, or more digits'
)
else:
orders_of_magnitude = len(str(epoch)) - 10
powers_of_ten = 10**orders_of_magnitude
epoch = int(epoch/powers_of_ten)
return epoch
def _handle_iso_week_number(date, timestring, index_timestamp):
date_iso = date.isocalendar()
iso_week_str = "{Y:04d}{W:02d}".format(Y=date_iso[0], W=date_iso[1])
greg_week_str = datetime.strftime(date, "%Y%W")
# Edge case 1: ISO week number is bigger than Greg week number.
# Ex: year 2014, all ISO week numbers were 1 more than in Greg.
if (iso_week_str > greg_week_str or
# Edge case 2: 2010-01-01 in ISO: 2009.W53, in Greg: 2010.W00
# For Greg converting 2009.W53 gives 2010-01-04, converting back
# to same timestring gives: 2010.W01.
datetime.strftime(date, timestring) != index_timestamp):
# Remove one week in this case
date = date - timedelta(days=7)
return date
def datetime_to_epoch(mydate):
# I would have used `total_seconds`, but apparently that's new
# to Python 2.7+, and due to so many people still using
# RHEL/CentOS 6, I need this to support Python 2.6.
tdelta = (mydate - datetime(1970,1,1))
return tdelta.seconds + tdelta.days * 24 * 3600
class TimestringSearch(object):
"""
An object to allow repetitive search against a string, `searchme`, without
having to repeatedly recreate the regex.
:arg timestring: An strftime pattern
"""
def __init__(self, timestring):
regex = r'(?P<date>{0})'.format(get_date_regex(timestring))
self.pattern = re.compile(regex)
self.timestring = timestring
def get_epoch(self, searchme):
"""
Return the epoch timestamp extracted from the `timestring` appearing in
`searchme`.
:arg searchme: A string to be searched for a date pattern that matches
`timestring`
:rtype: int
"""
match = self.pattern.search(searchme)
if match:
if match.group("date"):
timestamp = match.group("date")
return datetime_to_epoch(
get_datetime(timestamp, self.timestring)
)
# # I would have used `total_seconds`, but apparently that's new
# # to Python 2.7+, and due to so many people still using
# # RHEL/CentOS 6, I need this to support Python 2.6.
# tdelta = (
# get_datetime(timestamp, self.timestring) -
# datetime(1970,1,1)
# )
# return tdelta.seconds + tdelta.days * 24 * 3600
def get_point_of_reference(unit, count, epoch=None):
"""
Get a point-of-reference timestamp in epoch + milliseconds by deriving
from a `unit` and a `count`, and an optional reference timestamp, `epoch`
:arg unit: One of ``seconds``, ``minutes``, ``hours``, ``days``, ``weeks``,
``months``, or ``years``.
:arg unit_count: The number of ``units``. ``unit_count`` * ``unit`` will
be calculated out to the relative number of seconds.
:arg epoch: An epoch timestamp used in conjunction with ``unit`` and
``unit_count`` to establish a point of reference for calculations.
:rtype: int
"""
if unit == 'seconds':
multiplier = 1
elif unit == 'minutes':
multiplier = 60
elif unit == 'hours':
multiplier = 3600
elif unit == 'days':
multiplier = 3600*24
elif unit == 'weeks':
multiplier = 3600*24*7
elif unit == 'months':
multiplier = 3600*24*30
elif unit == 'years':
multiplier = 3600*24*365
else:
raise ValueError('Invalid unit: {0}.'.format(unit))
# Use this moment as a reference point, if one is not provided.
if not epoch:
epoch = time.time()
epoch = fix_epoch(epoch)
return epoch - multiplier * count
def get_unit_count_from_name(index_name, pattern):
if (pattern == None):
return None
match = pattern.search(index_name)
if match:
try:
return int(match.group(1))
except Exception:
return None
else:
return None
def date_range(unit, range_from, range_to, epoch=None, week_starts_on='sunday'):
"""
Get the epoch start time and end time of a range of ``unit``s, reckoning the
start of the week (if that's the selected unit) based on ``week_starts_on``,
which can be either ``sunday`` or ``monday``.
:arg unit: One of ``hours``, ``days``, ``weeks``, ``months``, or ``years``.
:arg range_from: How many ``unit`` (s) in the past/future is the origin?
:arg range_to: How many ``unit`` (s) in the past/future is the end point?
:arg epoch: An epoch timestamp used to establish a point of reference for
calculations.
:arg week_starts_on: Either ``sunday`` or ``monday``. Default is ``sunday``
:rtype: tuple
"""
acceptable_units = ['hours', 'days', 'weeks', 'months', 'years']
if unit not in acceptable_units:
raise exceptions.ConfigurationError(
'"unit" must be one of: {0}'.format(acceptable_units))
if not range_to >= range_from:
raise exceptions.ConfigurationError(
'"range_to" must be greater than or equal to "range_from"')
if not epoch:
epoch = time.time()
epoch = fix_epoch(epoch)
rawPoR = datetime.utcfromtimestamp(epoch)
logger.debug('Raw point of Reference = {0}'.format(rawPoR))
# Reverse the polarity, because -1 as last week makes sense when read by
# humans, but datetime timedelta math makes -1 in the future.
origin = range_from * -1
# These if statements help get the start date or start_delta
if unit == 'hours':
PoR = datetime(rawPoR.year, rawPoR.month, rawPoR.day, rawPoR.hour, 0, 0)
start_delta = timedelta(hours=origin)
if unit == 'days':
PoR = datetime(rawPoR.year, rawPoR.month, rawPoR.day, 0, 0, 0)
start_delta = timedelta(days=origin)
if unit == 'weeks':
PoR = datetime(rawPoR.year, rawPoR.month, rawPoR.day, 0, 0, 0)
sunday = False
if week_starts_on.lower() == 'sunday':
sunday = True
weekday = PoR.weekday()
# Compensate for ISO week starting on Monday by default
if sunday:
weekday += 1
logger.debug('Weekday = {0}'.format(weekday))
start_delta = timedelta(days=weekday, weeks=origin)
if unit == 'months':
PoR = datetime(rawPoR.year, rawPoR.month, 1, 0, 0, 0)
year = rawPoR.year
month = rawPoR.month
if origin > 0:
for _ in range(0, origin):
if month == 1:
year -= 1
month = 12
else:
month -= 1
else:
for _ in range(origin, 0):
if month == 12:
year += 1
month = 1
else:
month += 1
start_date = datetime(year, month, 1, 0, 0, 0)
if unit == 'years':
PoR = datetime(rawPoR.year, 1, 1, 0, 0, 0)
start_date = datetime(rawPoR.year - origin, 1, 1, 0, 0, 0)
if unit not in ['months','years']:
start_date = PoR - start_delta
# By this point, we know our start date and can convert it to epoch time
start_epoch = datetime_to_epoch(start_date)
logger.debug('Start ISO8601 = {0}'.format(
datetime.utcfromtimestamp(start_epoch).isoformat()))
# This is the number of units we need to consider.
count = (range_to - range_from) + 1
# We have to iterate to one more month, and then subtract a second to get
# the last day of the correct month
if unit == 'months':
month = start_date.month
year = start_date.year
for _ in range(0, count):
if month == 12:
year += 1
month = 1
else:
month += 1
end_date = datetime(year, month, 1, 0, 0, 0)
end_epoch = datetime_to_epoch(end_date) - 1
# Similarly, with years, we need to get the last moment of the year
elif unit == 'years':
end_date = datetime((rawPoR.year - origin) + count, 1, 1, 0, 0, 0)
end_epoch = datetime_to_epoch(end_date) - 1
# It's not months or years, which have inconsistent reckoning...
else:
# This lets us use an existing method to simply add unit * count seconds
# to get hours, days, or weeks, as they don't change
end_epoch = get_point_of_reference(
unit, count * -1, epoch=start_epoch) -1
logger.debug('End ISO8601 = {0}'.format(
datetime.utcfromtimestamp(end_epoch).isoformat()))
return (start_epoch, end_epoch)
def absolute_date_range(
unit, date_from, date_to,
date_from_format=None, date_to_format=None
):
"""
Get the epoch start time and end time of a range of ``unit``s, reckoning the
start of the week (if that's the selected unit) based on ``week_starts_on``,
which can be either ``sunday`` or ``monday``.
:arg unit: One of ``hours``, ``days``, ``weeks``, ``months``, or ``years``.
:arg date_from: The simplified date for the start of the range
:arg date_to: The simplified date for the end of the range. If this value
is the same as ``date_from``, the full value of ``unit`` will be
extrapolated for the range. For example, if ``unit`` is ``months``,
and ``date_from`` and ``date_to`` are both ``2017.01``, then the entire
month of January 2017 will be the absolute date range.
:arg date_from_format: The strftime string used to parse ``date_from``
:arg date_to_format: The strftime string used to parse ``date_to``
:rtype: tuple
"""
acceptable_units = ['seconds', 'minutes', 'hours', 'days', 'weeks', 'months', 'years']
if unit not in acceptable_units:
raise exceptions.ConfigurationError(
'"unit" must be one of: {0}'.format(acceptable_units))
if not date_from_format or not date_to_format:
raise exceptions.ConfigurationError('Must provide "date_from_format" and "date_to_format"')
try:
start_epoch = datetime_to_epoch(get_datetime(date_from, date_from_format))
logger.debug('Start ISO8601 = {0}'.format(datetime.utcfromtimestamp(start_epoch).isoformat()))
except Exception as e:
raise exceptions.ConfigurationError(
'Unable to parse "date_from" {0} and "date_from_format" {1}. '
'Error: {2}'.format(date_from, date_from_format, e)
)
try:
end_date = get_datetime(date_to, date_to_format)
except Exception as e:
raise exceptions.ConfigurationError(
'Unable to parse "date_to" {0} and "date_to_format" {1}. '
'Error: {2}'.format(date_to, date_to_format, e)
)
# We have to iterate to one more month, and then subtract a second to get
# the last day of the correct month
if unit == 'months':
month = end_date.month
year = end_date.year
if month == 12:
year += 1
month = 1
else:
month += 1
new_end_date = datetime(year, month, 1, 0, 0, 0)
end_epoch = datetime_to_epoch(new_end_date) - 1
# Similarly, with years, we need to get the last moment of the year
elif unit == 'years':
new_end_date = datetime(end_date.year + 1, 1, 1, 0, 0, 0)
end_epoch = datetime_to_epoch(new_end_date) - 1
# It's not months or years, which have inconsistent reckoning...
else:
# This lets us use an existing method to simply add 1 more unit's worth
# of seconds to get hours, days, or weeks, as they don't change
# We use -1 as point of reference normally subtracts from the epoch
# and we need to add to it, so we'll make it subtract a negative value.
# Then, as before, subtract 1 to get the end of the period
end_epoch = get_point_of_reference(
unit, -1, epoch=datetime_to_epoch(end_date)) -1
logger.debug('End ISO8601 = {0}'.format(
datetime.utcfromtimestamp(end_epoch).isoformat()))
return (start_epoch, end_epoch)
def byte_size(num, suffix='B'):
"""
Return a formatted string indicating the size in bytes, with the proper
unit, e.g. KB, MB, GB, TB, etc.
:arg num: The number of byte
:arg suffix: An arbitrary suffix, like `Bytes`
:rtype: float
"""
for unit in ['','K','M','G','T','P','E','Z']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Y', suffix)
def ensure_list(indices):
"""
Return a list, even if indices is a single value
:arg indices: A list of indices to act upon
:rtype: list
"""
if not isinstance(indices, list): # in case of a single value passed
indices = [indices]
return indices
def to_csv(indices):
"""
Return a csv string from a list of indices, or a single value if only one
value is present
:arg indices: A list of indices to act on, or a single value, which could be
in the format of a csv string already.
:rtype: str
"""
indices = ensure_list(indices) # in case of a single value passed
if indices:
return ','.join(sorted(indices))
else:
return None
def check_csv(value):
"""
Some of the curator methods should not operate against multiple indices at
once. This method can be used to check if a list or csv has been sent.
:arg value: The value to test, if list or csv string
:rtype: bool
"""
if isinstance(value, list):
return True
# Python3 hack because it doesn't recognize unicode as a type anymore
if sys.version_info < (3, 0):
# pylint: disable=E0602
if isinstance(value, unicode):
value = str(value)
if isinstance(value, str):
if len(value.split(',')) > 1: # It's a csv string.
return True
else: # There's only one value here, so it's not a csv string
return False
else:
raise TypeError(
'Passed value: {0} is not a list or a string '
'but is of type {1}'.format(value, type(value))
)
def chunk_index_list(indices):
"""
This utility chunks very large index lists into 3KB chunks
It measures the size as a csv string, then converts back into a list
for the return value.
:arg indices: A list of indices to act on.
:rtype: list
"""
chunks = []
chunk = ""
for index in indices:
if len(chunk) < 3072:
if not chunk:
chunk = index
else:
chunk += "," + index
else:
chunks.append(chunk.split(','))
chunk = index
chunks.append(chunk.split(','))
return chunks
def get_indices(client):
"""
Get the current list of indices from the cluster.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:rtype: list
"""
try:
indices = list(
client.indices.get_settings(
index='_all', params={'expand_wildcards': 'open,closed'})
)
version_number = get_version(client)
logger.debug(
'Detected Elasticsearch version '
'{0}'.format(".".join(map(str,version_number)))
)
logger.debug("All indices: {0}".format(indices))
return indices
except Exception as e:
raise exceptions.FailedExecution('Failed to get indices. Error: {0}'.format(e))
def get_version(client):
"""
Return the ES version number as a tuple.
Omits trailing tags like -dev, or Beta
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:rtype: tuple
"""
version = client.info()['version']['number']
version = version.split('-')[0]
if len(version.split('.')) > 3:
version = version.split('.')[:-1]
else:
version = version.split('.')
return tuple(map(int, version))
def is_master_node(client):
"""
Return `True` if the connected client node is the elected master node in
the Elasticsearch cluster, otherwise return `False`.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:rtype: bool
"""
my_node_id = list(client.nodes.info('_local')['nodes'])[0]
master_node_id = client.cluster.state(metric='master_node')['master_node']
return my_node_id == master_node_id
def check_version(client):
"""
Verify version is within acceptable range. Raise an exception if it is not.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:rtype: None
"""
version_number = get_version(client)
logger.debug(
'Detected Elasticsearch version '
'{0}'.format(".".join(map(str,version_number)))
)
if version_number >= settings.version_max() \
or version_number < settings.version_min():
logger.error(
'Elasticsearch version {0} incompatible '
'with this version of Curator '
'({1})'.format(".".join(map(str,version_number)), __version__)
)
raise exceptions.CuratorException(
'Elasticsearch version {0} incompatible '
'with this version of Curator '
'({1})'.format(".".join(map(str,version_number)), __version__)
)
def check_master(client, master_only=False):
"""
Check if connected client is the elected master node of the cluster.
If not, cleanly exit with a log message.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:rtype: None
"""
if master_only and not is_master_node(client):
logger.info(
'Master-only flag detected. '
'Connected to non-master node. Aborting.'
)
sys.exit(0)
def get_client(**kwargs):
"""
NOTE: AWS IAM parameters `aws_sign_request` and `aws_region` are
provided to facilitate request signing. The credentials will be
fetched from the local environment as per the AWS documentation:
http://amzn.to/2fRCGCt
AWS IAM parameters `aws_key`, `aws_secret_key`, and `aws_region` are
provided for users that still have their keys included in the Curator config file.
Return an :class:`elasticsearch.Elasticsearch` client object using the
provided parameters. Any of the keyword arguments the
:class:`elasticsearch.Elasticsearch` client object can receive are valid,
such as:
:arg hosts: A list of one or more Elasticsearch client hostnames or IP
addresses to connect to. Can send a single host.
:type hosts: list
:arg port: The Elasticsearch client port to connect to.
:type port: int
:arg url_prefix: `Optional` url prefix, if needed to reach the Elasticsearch
API (i.e., it's not at the root level)
:type url_prefix: str
:arg use_ssl: Whether to connect to the client via SSL/TLS
:type use_ssl: bool
:arg certificate: Path to SSL/TLS certificate
:arg client_cert: Path to SSL/TLS client certificate (public key)
:arg client_key: Path to SSL/TLS private key
:arg aws_key: AWS IAM Access Key (Only used if the :mod:`requests-aws4auth`
python module is installed)
:arg aws_secret_key: AWS IAM Secret Access Key (Only used if the
:mod:`requests-aws4auth` python module is installed)
:arg aws_region: AWS Region (Only used if the :mod:`requests-aws4auth`
python module is installed)
:arg aws_sign_request: Sign request to AWS (Only used if the :mod:`requests-aws4auth`
and :mod:`boto3` python modules are installed)
:arg aws_region: AWS Region where the cluster exists (Only used if the :mod:`requests-aws4auth`
and :mod:`boto3` python modules are installed)
:arg ssl_no_validate: If `True`, do not validate the certificate
chain. This is an insecure option and you will see warnings in the
log output.
:type ssl_no_validate: bool
:arg http_auth: Authentication credentials in `user:pass` format.
:type http_auth: str
:arg timeout: Number of seconds before the client will timeout.
:type timeout: int
:arg master_only: If `True`, the client will `only` connect if the
endpoint is the elected master node of the cluster. **This option does
not work if `hosts` has more than one value.** It will raise an
Exception in that case.
:type master_only: bool
:arg skip_version_test: If `True`, skip the version check as part of the
client connection.
:rtype: :class:`elasticsearch.Elasticsearch`
"""
if 'url_prefix' in kwargs:
if (
type(kwargs['url_prefix']) == type(None) or
kwargs['url_prefix'] == "None"
):
kwargs['url_prefix'] = ''
if 'host' in kwargs and 'hosts' in kwargs:
raise exceptions.ConfigurationError(
'Both "host" and "hosts" are defined. Pick only one.')
elif 'host' in kwargs and not 'hosts' in kwargs:
kwargs['hosts'] = kwargs['host']
del kwargs['host']
kwargs['hosts'] = '127.0.0.1' if not 'hosts' in kwargs else kwargs['hosts']
kwargs['master_only'] = False if not 'master_only' in kwargs \
else kwargs['master_only']
if 'skip_version_test' in kwargs:
skip_version_test = kwargs.pop('skip_version_test')
else:
skip_version_test = False
kwargs['use_ssl'] = False if not 'use_ssl' in kwargs else kwargs['use_ssl']
kwargs['ssl_no_validate'] = False if not 'ssl_no_validate' in kwargs \
else kwargs['ssl_no_validate']
kwargs['certificate'] = False if not 'certificate' in kwargs \
else kwargs['certificate']
kwargs['client_cert'] = False if not 'client_cert' in kwargs \
else kwargs['client_cert']
kwargs['client_key'] = False if not 'client_key' in kwargs \
else kwargs['client_key']
kwargs['hosts'] = ensure_list(kwargs['hosts'])
logger.debug("kwargs = {0}".format(kwargs))
master_only = kwargs.pop('master_only')
if kwargs['use_ssl']:
if kwargs['ssl_no_validate']:
kwargs['verify_certs'] = False # Not needed, but explicitly defined
else:
logger.debug('Attempting to verify SSL certificate.')
# If user provides a certificate:
if kwargs['certificate']:
kwargs['verify_certs'] = True
kwargs['ca_certs'] = kwargs['certificate']
else: # Try to use bundled certifi certificates
if getattr(sys, 'frozen', False):
# The application is frozen (compiled)
datadir = os.path.dirname(sys.executable)
kwargs['verify_certs'] = True
kwargs['ca_certs'] = os.path.join(datadir, 'cacert.pem')
else:
# Use certifi certificates via certifi.where():
import certifi
kwargs['verify_certs'] = True
kwargs['ca_certs'] = certifi.where()
kwargs['aws_key'] = False if not 'aws_key' in kwargs \
else kwargs['aws_key']
kwargs['aws_secret_key'] = False if not 'aws_secret_key' in kwargs \
else kwargs['aws_secret_key']
kwargs['aws_token='] = '' if not 'aws_token' in kwargs \
else kwargs['aws_token']
kwargs['aws_sign_request'] = False if not 'aws_sign_request' in kwargs \
else kwargs['aws_sign_request']
kwargs['aws_region'] = False if not 'aws_region' in kwargs \
else kwargs['aws_region']
if kwargs['aws_key'] or kwargs['aws_secret_key'] or kwargs['aws_sign_request']:
if not kwargs['aws_region']:
raise exceptions.MissingArgument(
'Missing "aws_region".'
)
if kwargs['aws_key'] or kwargs['aws_secret_key']:
if not (kwargs['aws_key'] and kwargs['aws_secret_key']):
raise exceptions.MissingArgument(
'Missing AWS Access Key or AWS Secret Key'
)
if kwargs['aws_sign_request']:
try:
from boto3 import session
from botocore import exceptions as botoex
# We cannot get credentials without the boto3 library, so we cannot continue
except ImportError as e:
logger.debug('Failed to import a module: %s' % e)
raise ImportError('Failed to import a module: %s' % e)
try:
session = session.Session()
credentials = session.get_credentials()
kwargs['aws_key'] = credentials.access_key
kwargs['aws_secret_key'] = credentials.secret_key
kwargs['aws_token'] = credentials.token
# If an attribute doesn't exist, we were not able to retrieve credentials as expected so we can't continue
except AttributeError:
logger.debug('Unable to locate AWS credentials')
raise botoex.NoCredentialsError
try:
from requests_aws4auth import AWS4Auth
if kwargs['aws_key']:
# Override these kwargs
kwargs['use_ssl'] = True
kwargs['verify_certs'] = True
if kwargs['ssl_no_validate']:
kwargs['verify_certs'] = False
kwargs['connection_class'] = elasticsearch.RequestsHttpConnection
kwargs['http_auth'] = (
AWS4Auth(
kwargs['aws_key'], kwargs['aws_secret_key'],
kwargs['aws_region'], 'es', session_token=kwargs['aws_token'])
)
else:
logger.debug('"requests_aws4auth" module present, but not used.')
except ImportError:
logger.debug('Not using "requests_aws4auth" python module to connect.')
if master_only:
if len(kwargs['hosts']) > 1:
logger.error(
'"master_only" cannot be true if more than one host is '
'specified. Hosts = {0}'.format(kwargs['hosts'])
)
raise exceptions.ConfigurationError(
'"master_only" cannot be true if more than one host is '
'specified. Hosts = {0}'.format(kwargs['hosts'])
)
try:
client = elasticsearch.Elasticsearch(**kwargs)
if skip_version_test:
logger.warn(
'Skipping Elasticsearch version verification. This is '
'acceptable for remote reindex operations.'
)
else:
# Verify the version is acceptable.
check_version(client)
# Verify "master_only" status, if applicable
check_master(client, master_only=master_only)
return client
except Exception as e:
raise elasticsearch.ElasticsearchException(
'Unable to create client connection to Elasticsearch. '
'Error: {0}'.format(e)
)
def show_dry_run(ilo, action, **kwargs):
"""
Log dry run output with the action which would have been executed.
:arg ilo: A :class:`curator.indexlist.IndexList`
:arg action: The `action` to be performed.
:arg kwargs: Any other args to show in the log output
"""
logger.info('DRY-RUN MODE. No changes will be made.')
logger.info(
'(CLOSED) indices may be shown that may not be acted on by '
'action "{0}".'.format(action)
)
indices = sorted(ilo.indices)
for idx in indices:
index_closed = ilo.index_info[idx]['state'] == 'close'
logger.info(
'DRY-RUN: {0}: {1}{2} with arguments: {3}'.format(
action, idx, ' (CLOSED)' if index_closed else '', kwargs
)
)
### SNAPSHOT STUFF ###
def get_repository(client, repository=''):
"""
Return configuration information for the indicated repository.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg repository: The Elasticsearch snapshot repository to use
:rtype: dict
"""
try:
return client.snapshot.get_repository(repository=repository)
except (elasticsearch.TransportError, elasticsearch.NotFoundError) as e:
raise exceptions.CuratorException(
'Unable to get repository {0}. Response Code: {1}. Error: {2}.'
'Check Elasticsearch logs for more information.'.format(
repository, e.status_code, e.error
)
)
def get_snapshot(client, repository=None, snapshot=''):
"""
Return information about a snapshot (or a comma-separated list of snapshots)
If no snapshot specified, it will return all snapshots. If none exist, an
empty dictionary will be returned.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg repository: The Elasticsearch snapshot repository to use
:arg snapshot: The snapshot name, or a comma-separated list of snapshots
:rtype: dict
"""
if not repository:
raise exceptions.MissingArgument('No value for "repository" provided')
snapname = '_all' if snapshot == '' else snapshot
try:
return client.snapshot.get(repository=repository, snapshot=snapshot)
except (elasticsearch.TransportError, elasticsearch.NotFoundError) as e:
raise exceptions.FailedExecution(
'Unable to get information about snapshot {0} from repository: '
'{1}. Error: {2}'.format(snapname, repository, e)
)
def get_snapshot_data(client, repository=None):
"""
Get ``_all`` snapshots from repository and return a list.
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg repository: The Elasticsearch snapshot repository to use
:rtype: list
"""
if not repository:
raise exceptions.MissingArgument('No value for "repository" provided')
try:
return client.snapshot.get(
repository=repository, snapshot="_all")['snapshots']
except (elasticsearch.TransportError, elasticsearch.NotFoundError) as e:
raise exceptions.FailedExecution(
'Unable to get snapshot information from repository: {0}. '
'Error: {1}'.format(repository, e)
)
def snapshot_in_progress(client, repository=None, snapshot=None):
"""
Determine whether the provided snapshot in `repository` is ``IN_PROGRESS``.
If no value is provided for `snapshot`, then check all of them.
Return `snapshot` if it is found to be in progress, or `False`
:arg client: An :class:`elasticsearch.Elasticsearch` client object
:arg repository: The Elasticsearch snapshot repository to use
:arg snapshot: The snapshot name