summaryrefslogtreecommitdiffstats
path: root/glustolibs-gluster/glustolibs/gluster/bitrot_ops.py
blob: 5112dfb15de0f6c6b88320f51220493c08513ffa (plain)
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
#!/usr/bin/env python
#  Copyright (C) 2015-2016  Red Hat, Inc. <http://www.redhat.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""
    Description: Library for gluster bitrot operations.
"""

from glusto.core import Glusto as g
from glustolibs.gluster.volume_ops import get_volume_options, get_volume_status
from glustolibs.gluster.lib_utils import (get_pathinfo,
                                          calculate_checksum,
                                          get_extended_attributes_info)
import time
import re


# Global variables
SCRUBBER_TIMEOUT = 100


def enable_bitrot(mnode, volname):
    """Enables bitrot for given volume

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        tuple: Tuple containing three elements (ret, out, err).
            The first element 'ret' is of type 'int' and is the return value
            of command execution.

            The second element 'out' is of type 'str' and is the stdout value
            of the command execution.

            The third element 'err' is of type 'str' and is the stderr value
            of the command execution.

    Example:
        enable_bitrot("abc.com", testvol)
    """

    cmd = "gluster volume bitrot %s enable" % volname
    return g.run(mnode, cmd)


def disable_bitrot(mnode, volname):
    """Disables bitrot for given volume

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        tuple: Tuple containing three elements (ret, out, err).
            The first element 'ret' is of type 'int' and is the return value
            of command execution.

            The second element 'out' is of type 'str' and is the stdout value
            of the command execution.

            The third element 'err' is of type 'str' and is the stderr value
            of the command execution.

    Example:
        disable_bitrot("abc.com", testvol)
    """

    cmd = "gluster volume bitrot %s disable" % volname
    return g.run(mnode, cmd)


def is_bitrot_enabled(mnode, volname):
    """Checks if bitrot is enabled on given volume

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        True on success, False otherwise

    Example:
        is_bitrot_enabled("abc.com", testvol)
    """

    output = get_volume_options(mnode, volname, "features.bitrot")
    if output is None:
        return False

    g.log.info("Bitrot Status in volume %s: %s"
               % (volname, output["features.bitrot"]))
    if output["features.bitrot"] != 'on':
        return False

    return True


def is_file_signed(mnode, filename, volname, expected_file_version=None):
    """Verifies if the given file is signed

    Args:
        mnode (str): Node on which cmd has to be executed.
        filename (str): relative path of filename to be verified
        volname (str): volume name

    Kwargs:
        expected_file_version (str): file version to check with getfattr output
            If this option is set, this function
            will check file versioning as part of signing verification.
            If this option is set to None, function will not check
            for file versioning. Defaults to None.

    Returns:
        True on success, False otherwise

    Example:
        is_file_signed("abc.com", 'file1', "testvol",
                       expected_file_version='2')
    """

    # Getting file path in the rhs node
    file_location = get_pathinfo(mnode, filename, volname)
    if file_location is None:
        g.log.error("Failed to get backend file path in is_file_signed()")
        return False

    path_info = file_location[0].split(':')

    expected_file_signature = (calculate_checksum(path_info[0],
                                                  [path_info[1]])
                               [path_info[1]])

    attr_info = get_extended_attributes_info(path_info[0],
                                             [path_info[1]])
    if attr_info is None:
        g.log.error("Failed to get attribute info in is_file_signed()")
        return False

    if 'trusted.bit-rot.signature' in attr_info[path_info[1]]:
        file_signature = attr_info[path_info[1]]['trusted.bit-rot.signature']
    else:
        g.log.error("trusted.bit-rot.signature attribute not present "
                    " for file %s" % filename)
        return False

    if expected_file_version is not None:
        expected_file_version = ('{0:02d}'.format(int(
                                 expected_file_version))).ljust(16, '0')
        actual_signature_file_version = re.findall('.{16}',
                                                   file_signature[4:]).pop(0)

        # Verifying file version after signing
        if actual_signature_file_version != expected_file_version:
            g.log.error("File version mismatch in signature.Filename: %s ."
                        "Expected file version: %s.Actual file version: %s"
                        % (filename, expected_file_version,
                           actual_signature_file_version))
            return False

    actual_file_signature = ''.join(re.findall('.{16}',
                                               file_signature[4:])[1:])

    # Verifying file signature
    if actual_file_signature != expected_file_signature:
        g.log.error("File signature mismatch. File name: %s . Expected "
                    "file signature: %s. Actual file signature: %s"
                    % (filename, expected_file_signature,
                       actual_file_signature))
        return False
    return True


def is_file_bad(mnode, filename):
    """Verifies if scrubber identifies bad file
    Args:
        filename (str): absolute path of the file in mnode
        mnode (str): Node on which cmd has to be executed.

    Returns:
        True on success, False otherwise

    Example:
        is_file_bad("abc.xyz.com", "/bricks/file1")
    """
    ret = True
    count = 0
    flag = 0
    while (count < SCRUBBER_TIMEOUT):
        attr_info = get_extended_attributes_info(mnode, [filename])
        if attr_info is None:
            ret = False

        if 'trusted.bit-rot.bad-file' in attr_info[filename]:
            flag = 1
            break

        time.sleep(10)
        count = count + 10
    if not flag:
        g.log.error("Scrubber failed to identify bad file")
        ret = False

    return ret


def bring_down_bitd(mnode):
    """Brings down bitd process
    Args:
        mnode (str): Node on which cmd has to be executed.

    Returns:
        True on success, False otherwise

    Example:
        bring_down_bitd("abc.xyz.com")
    """

    kill_cmd = ("pid=`cat /var/lib/glusterd/bitd/run/bitd.pid` && "
                "kill -15 $pid || kill -9 $pid")
    ret, _, _ = g.run(mnode, kill_cmd)
    if ret != 0:
        g.log.error("Unable to kill the bitd for %s"
                    % mnode)
        return False
    else:
        return True


def bring_down_scrub_process(mnode):
    """Brings down scrub process
    Args:
        mnode (str): Node on which cmd has to be executed.

    Returns:
        True on success, False otherwise

    Example:
        bring_down_scrub_process("abc.xyz.com")
    """

    kill_cmd = ("pid=`cat /var/lib/glusterd/scrub/run/scrub.pid` && "
                "kill -15 $pid || kill -9 $pid")

    ret, _, _ = g.run(mnode, kill_cmd)
    if ret != 0:
        g.log.error("Unable to kill the scrub process for %s"
                    % mnode)
        return False
    else:
        return True


def set_scrub_throttle(mnode, volname, throttle_type='lazy'):
    """Sets scrub throttle

    Args:
        volname (str): volume name
        mnode (str): Node on which cmd has to be executed.

    Kwargs:
        throttle_type (str): throttling type (lazy|normal|aggressive)
            Defaults to 'lazy'

    Returns:
        tuple: Tuple containing three elements (ret, out, err).
            The first element 'ret' is of type 'int' and is the return value
            of command execution.

            The second element 'out' is of type 'str' and is the stdout value
            of the command execution.

            The third element 'err' is of type 'str' and is the stderr value
            of the command execution.

    Example:
        set_scrub_throttle(mnode, testvol)
    """

    cmd = ("gluster volume bitrot %s scrub-throttle %s"
           % (volname, throttle_type))
    return g.run(mnode, cmd)


def set_scrub_frequency(mnode, volname, frequency_type='biweekly'):
    """Sets scrub frequency

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Kwargs:
        frequency_type (str): frequency type (hourly|daily|weekly|biweekly|
            monthly). Defaults to 'biweekly'

    Returns:
        tuple: Tuple containing three elements (ret, out, err).
            The first element 'ret' is of type 'int' and is the return value
            of command execution.

            The second element 'out' is of type 'str' and is the stdout value
            of the command execution.

            The third element 'err' is of type 'str' and is the stderr value
            of the command execution.

    Example:
        set_scrub_frequency("abc.com", testvol)
    """

    cmd = ("gluster volume bitrot %s scrub-frequency %s"
           % (volname, frequency_type))
    return g.run(mnode, cmd)


def pause_scrub(mnode, volname):
    """Pauses scrub

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        tuple: Tuple containing three elements (ret, out, err).
            The first element 'ret' is of type 'int' and is the return value
            of command execution.

            The second element 'out' is of type 'str' and is the stdout value
            of the command execution.

            The third element 'err' is of type 'str' and is the stderr value
            of the command execution.

    Example:
        pause_scrub("abc.com", testvol)
    """

    cmd = "gluster volume bitrot %s scrub pause" % volname
    return g.run(mnode, cmd)


def resume_scrub(mnode, volname):
    """Resumes scrub

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        tuple: Tuple containing three elements (ret, out, err).
            The first element 'ret' is of type 'int' and is the return value
            of command execution.

            The second element 'out' is of type 'str' and is the stdout value
            of the command execution.

            The third element 'err' is of type 'str' and is the stderr value
            of the command execution.

    Example:
        resume_scrub("abc.com", testvol)
    """

    cmd = "gluster volume bitrot %s scrub resume" % volname
    return g.run(mnode, cmd)


def get_bitd_pid(mnode):
    """Gets bitd process id for the given node
    Args:
        mnode (str): Node on which cmd has to be executed.

    Returns:
        str: pid of the bitd process on success
        NoneType: None if command execution fails, errors.

    Example:
        get_bitd_pid("abc.com")
    """

    cmd = ("cat /var/lib/glusterd/bitd/run/bitd.pid")
    ret, out, _ = g.run(mnode, cmd)
    if ret != 0:
        g.log.error("Unable to get bitd pid for %s"
                    % mnode)
        return None

    return out.strip("\n")


def get_scrub_process_pid(mnode):
    """Gets scrub process id for the given node
    Args:
        mnode (str): Node on which cmd has to be executed.

    Returns:
        str: pid of the scrub process on success
        NoneType: None if command execution fails, errors.

    Example:
        get_scrub_process_pid("abc.com")
    """

    cmd = ("cat /var/lib/glusterd/scrub/run/scrub.pid")
    ret, out, _ = g.run(mnode, cmd)
    if ret != 0:
        g.log.error("Unable to get scrub pid for %s"
                    % mnode)
        return None

    return out.strip("\n")


def is_bitd_running(mnode, volname):
    """Checks if bitd is running on the given node

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        True on success, False otherwise

    Example:
        is_bitd_running("abc.com", "testvol")
    """

    vol_status = get_volume_status(mnode, volname=volname)
    if vol_status is None:
        g.log.error("Failed to get volume status in is_bitd_running()")
        return False

    if 'Bitrot Daemon' not in vol_status[volname][mnode]:
        g.log.error("Bitrot is not enabled in volume %s"
                    % volname)
        return False

    bitd_status = vol_status[volname][mnode]['Bitrot Daemon']['status']
    if bitd_status != '1':
        g.log.error("Bitrot Daemon is not running in node %s"
                    % mnode)
        return False
    return True


def is_scrub_process_running(mnode, volname):
    """Checks if scrub process is running on the given node

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        True on success, False otherwise

    Example:
        is_scrub_process_running("abc.com", "testvol")
    """

    vol_status = get_volume_status(mnode, volname=volname)
    if vol_status is None:
        g.log.error("Failed to get volume status in "
                    "is_scrub_process_running()")
        return False

    if 'Scrubber Daemon' not in vol_status[volname][mnode]:
        g.log.error("Bitrot is not enabled in volume %s"
                    % volname)
        return False

    bitd_status = vol_status[volname][mnode]['Scrubber Daemon']['status']
    if bitd_status != '1':
        g.log.error("Scrubber Daemon is not running in node %s"
                    % mnode)
        return False
    return True


def scrub_status(mnode, volname):
    """Executes gluster bitrot scrub status command

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        tuple: Tuple containing three elements (ret, out, err).
            The first element 'ret' is of type 'int' and is the return value
            of command execution.

            The second element 'out' is of type 'str' and is the stdout value
            of the command execution.

            The third element 'err' is of type 'str' and is the stderr value
            of the command execution.

    Example:
        scrub_status("abc.com", testvol)
    """

    cmd = "gluster volume bitrot %s scrub status" % volname
    return g.run(mnode, cmd)


def get_scrub_status(mnode, volname):
    """Parse the output of gluster bitrot scrub status command

    Args:
        mnode (str): Node on which cmd has to be executed.
        volname (str): volume name

    Returns:
        dict: scrub status in dict format
        NoneType: None if command execution fails, errors.

    Example:
        >>>get_scrub_status("abc.com", testvol)
        {'State of scrub': 'Active', 'Bitrot error log location':
        '/var/log/glusterfs/bitd.log', 'Scrub impact': 'aggressive',
        'Scrub frequency': 'hourly', 'status_info': {'localhost':
        {'Duration of last scrub (D:M:H:M:S)': '0:0:0:0', 'corrupted_gfid':
        ['475ca13f-577f-460c-a5d7-ea18bb0e7779'], 'Error count': '1',
        'Last completed scrub time': '2016-06-21 12:46:19',
        'Number of Skipped files': '0', 'Number of Scrubbed files': '0'},
        '10.70.47.118': {'Duration of last scrub (D:M:H:M:S)': '0:0:0:1',
        'corrupted_gfid': ['19e62b26-5942-4867-a2f6-e354cd166da9',
        'fab55c36-0580-4d11-9ac0-d8e4e51f39a0'], 'Error count': '2',
        'Last completed scrub time': '2016-06-21 12:46:03',
        'Number of Skipped files': '0', 'Number of Scrubbed files': '2'}},
        'Volume name': 'testvol', 'Scrubber error log location':
        '/var/log/glusterfs/scrub.log'}
    """

    cmd = "gluster volume bitrot %s scrub status" % volname
    ret, out, err = g.run(mnode, cmd)
    if ret != 0:
        g.log.error("Unable to get scrub status for volume %s"
                    % volname)
        return None

    match = re.search('(.*?)(==.*==.*)', out, re.S)
    if match is None:
        g.log.error("Mismatch in regex. Scrub status raw output is not"
                    " in expected format")
        return None
    info = match.group(2).replace('\n\n', '\n')

    if "Corrupted object's [GFID]" in info:
        info = info.replace("Corrupted object's [GFID]:\n",
                            "Corrupted object's [GFID]:")
        regex = 'Node(?:(?!Node).)*?Corrupted object.*?:.*?\n+='
        temp_list = re.findall(regex, info, re.S)
        corrupt_list = []
        for node in temp_list:
            tmp_reg = (r'Node: (\S+)\n.*Error count.*'
                       'Corrupted object.*?:(.*)\n=.*')
            m = re.search(tmp_reg, node, re.S)
            if m is None:
                g.log.error("Mismatch in cli output when bad file"
                            "is identified")
                return None
            corrupt_list.append(m.groups())
    else:
        corrupt_list = []
    info_list = re.findall('Node:.*?\n.*:.*\n.*:.*\n.*:.*\n.*:.*\n.*:.*\n+',
                           info)
    temp_list = []
    for item in info_list:
        item = item.replace('\n\n', '')
        temp_list.append(item)

    tmp_dict1 = {}
    for item in temp_list:
        tmp = item.split('\n')
        tmp_0 = tmp[0].split(':')
        tmp.pop(0)
        tmp_dict = {}
        for tmp_item in tmp[:-1]:
            tmp_1 = tmp_item.split(': ')
            tmp_dict[tmp_1[0].strip(' ')] = tmp_1[1].strip(' ')
        tmp_dict1[tmp_0[1].strip(' ')] = tmp_dict
    status_dict = {}
    for item in match.group(1).split('\n\n')[:-1]:
        elmt = item.split(':')
        tmp_elmt = elmt[1].strip(' ').strip('\n')
        status_dict[elmt[0].strip(' ').strip('\n')] = tmp_elmt

    status_dict['status_info'] = tmp_dict1
    for elmt in corrupt_list:
        if elmt[0].strip(' ') in list(status_dict['status_info'].keys()):
            val = elmt[1].split('\n')
            val = [_f for _f in val if _f is not None]
            gfid = "corrupted_gfid"
            status_dict['status_info'][elmt[0].strip(' ')][gfid] = val
    return status_dict