summaryrefslogtreecommitdiffstats
path: root/geo-replication/syncdaemon/syncdutils.py
blob: 2187ecd226b5c0704462c02332009493c8ac0534 (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
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
#
# Copyright (c) 2011-2014 Red Hat, Inc. <http://www.redhat.com>
# This file is part of GlusterFS.

# This file is licensed to you under your choice of the GNU Lesser
# General Public License, version 3 or any later version (LGPLv3 or
# later), or the GNU General Public License, version 2 (GPLv2), in all
# cases as published by the Free Software Foundation.
#

import os
import sys
import pwd
import time
import fcntl
import shutil
import logging
import socket
import subprocess
from threading import Lock, Thread as baseThread
from errno import EACCES, EAGAIN, EPIPE, ENOTCONN, ECONNABORTED
from errno import EINTR, ENOENT, EPERM, ESTALE, EBUSY, errorcode
from signal import signal, SIGTERM
import select as oselect
from os import waitpid as owaitpid
import subprocess

from conf import GLUSTERFS_LIBEXECDIR, UUID_FILE
sys.path.insert(1, GLUSTERFS_LIBEXECDIR)
EVENTS_ENABLED = True
try:
    from events.eventtypes import GEOREP_FAULTY as EVENT_GEOREP_FAULTY
    from events.eventtypes import GEOREP_ACTIVE as EVENT_GEOREP_ACTIVE
    from events.eventtypes import GEOREP_PASSIVE as EVENT_GEOREP_PASSIVE
    from events.eventtypes import GEOREP_CHECKPOINT_COMPLETED \
        as EVENT_GEOREP_CHECKPOINT_COMPLETED
except ImportError:
    # Events APIs not installed, dummy eventtypes with None
    EVENTS_ENABLED = False
    EVENT_GEOREP_FAULTY = None
    EVENT_GEOREP_ACTIVE = None
    EVENT_GEOREP_PASSIVE = None
    EVENT_GEOREP_CHECKPOINT_COMPLETED = None

try:
    from cPickle import PickleError
except ImportError:
    # py 3
    from pickle import PickleError

from gconf import gconf

try:
    # py 3
    from urllib import parse as urllib
except ImportError:
    import urllib

try:
    from hashlib import md5 as md5
except ImportError:
    # py 2.4
    from md5 import new as md5

# auxiliary gfid based access prefix
_CL_AUX_GFID_PFX = ".gfid/"
GF_OP_RETRIES = 10

GX_GFID_CANONICAL_LEN = 37  # canonical gfid len + '\0'

CHANGELOG_AGENT_SERVER_VERSION = 1.0
CHANGELOG_AGENT_CLIENT_VERSION = 1.0
NodeID = None
rsync_version = None
SPACE_ESCAPE_CHAR = "%20"
NEWLINE_ESCAPE_CHAR = "%0A"
PERCENTAGE_ESCAPE_CHAR = "%25"


def escape(s):
    """the chosen flavor of string escaping, used all over
       to turn whatever data to creatable representation"""
    return urllib.quote_plus(s)


def unescape(s):
    """inverse of .escape"""
    return urllib.unquote_plus(s)


def escape_space_newline(s):
    return s.replace("%", PERCENTAGE_ESCAPE_CHAR)\
            .replace(" ", SPACE_ESCAPE_CHAR)\
            .replace("\n", NEWLINE_ESCAPE_CHAR)


def unescape_space_newline(s):
    return s.replace(SPACE_ESCAPE_CHAR, " ")\
            .replace(NEWLINE_ESCAPE_CHAR, "\n")\
            .replace(PERCENTAGE_ESCAPE_CHAR, "%")


def norm(s):
    if s:
        return s.replace('-', '_')


def update_file(path, updater, merger=lambda f: True):
    """update a file in a transaction-like manner"""

    fr = fw = None
    try:
        fd = os.open(path, os.O_CREAT | os.O_RDWR)
        try:
            fr = os.fdopen(fd, 'r+b')
        except:
            os.close(fd)
            raise
        fcntl.lockf(fr, fcntl.LOCK_EX)
        if not merger(fr):
            return

        tmpp = path + '.tmp.' + str(os.getpid())
        fd = os.open(tmpp, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
        try:
            fw = os.fdopen(fd, 'wb', 0)
        except:
            os.close(fd)
            raise
        updater(fw)
        os.fsync(fd)
        os.rename(tmpp, path)
    finally:
        for fx in (fr, fw):
            if fx:
                fx.close()


def create_manifest(fname, content):
    """
    Create manifest file for SSH Control Path
    """
    fd = None
    try:
        fd = os.open(fname, os.O_CREAT | os.O_RDWR)
        try:
            os.write(fd, content)
        except:
            os.close(fd)
            raise
    finally:
        if fd is not None:
            os.close(fd)


def setup_ssh_ctl(ctld, remote_addr, resource_url):
    """
    Setup GConf ssh control path parameters
    """
    gconf.ssh_ctl_dir = ctld
    content = "SLAVE_HOST=%s\nSLAVE_RESOURCE_URL=%s" % (remote_addr,
                                                        resource_url)
    content_md5 = md5hex(content)
    fname = os.path.join(gconf.ssh_ctl_dir,
                         "%s.mft" % content_md5)

    create_manifest(fname, content)
    ssh_ctl_path = os.path.join(gconf.ssh_ctl_dir,
                                "%s.sock" % content_md5)
    gconf.ssh_ctl_args = ["-oControlMaster=auto", "-S", ssh_ctl_path]


def grabfile(fname, content=None):
    """open @fname + contest for its fcntl lock

    @content: if given, set the file content to it
    """
    # damn those messy open() mode codes
    fd = os.open(fname, os.O_CREAT | os.O_RDWR)
    f = os.fdopen(fd, 'r+b', 0)
    try:
        fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except:
        ex = sys.exc_info()[1]
        f.close()
        if isinstance(ex, IOError) and ex.errno in (EACCES, EAGAIN):
            # cannot grab, it's taken
            return
        raise
    if content:
        try:
            f.truncate()
            f.write(content)
        except:
            f.close()
            raise
    gconf.permanent_handles.append(f)
    return f


def grabpidfile(fname=None, setpid=True):
    """.grabfile customization for pid files"""
    if not fname:
        fname = gconf.pid_file
    content = None
    if setpid:
        content = str(os.getpid()) + '\n'
    return grabfile(fname, content=content)

final_lock = Lock()

mntpt_list = []
def finalize(*a, **kw):
    """all those messy final steps we go trough upon termination

    Do away with pidfile, ssh control dir and logging.
    """

    final_lock.acquire()
    if getattr(gconf, 'pid_file', None):
        rm_pidf = gconf.pid_file_owned
        if gconf.cpid:
            # exit path from parent branch of daemonization
            rm_pidf = False
            while True:
                f = grabpidfile(setpid=False)
                if not f:
                    # child has already taken over pidfile
                    break
                if os.waitpid(gconf.cpid, os.WNOHANG)[0] == gconf.cpid:
                    # child has terminated
                    rm_pidf = True
                    break
                time.sleep(0.1)
        if rm_pidf:
            try:
                os.unlink(gconf.pid_file)
            except:
                ex = sys.exc_info()[1]
                if ex.errno == ENOENT:
                    pass
                else:
                    raise
    if gconf.ssh_ctl_dir and not gconf.cpid:
        def handle_rm_error(func, path, exc_info):
            if exc_info[1].errno == ENOENT:
                return
            raise exc_info[1]

        shutil.rmtree(gconf.ssh_ctl_dir, onerror=handle_rm_error)
    if getattr(gconf, 'state_socket', None):
        try:
            os.unlink(gconf.state_socket)
        except:
            if sys.exc_info()[0] == OSError:
                pass

    """ Unmount if not done """
    for mnt in mntpt_list:
        p0 = subprocess.Popen (["umount", "-l", mnt], stderr=subprocess.PIPE)
        _, errdata = p0.communicate()
        if p0.returncode == 0:
            try:
                os.rmdir(mnt)
            except OSError:
                pass
        else:
            pass

    if gconf.log_exit:
        logging.info("exiting.")
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(kw.get('exval', 0))



def log_raise_exception(excont):
    """top-level exception handler

    Try to some fancy things to cover up we face with an error.
    Translate some weird sounding but well understood exceptions
    into human-friendly lingo
    """
    is_filelog = False
    for h in logging.getLogger().handlers:
        fno = getattr(getattr(h, 'stream', None), 'fileno', None)
        if fno and not os.isatty(fno()):
            is_filelog = True

    exc = sys.exc_info()[1]
    if isinstance(exc, SystemExit):
        excont.exval = exc.code or 0
        raise
    else:
        logtag = None
        if isinstance(exc, GsyncdError):
            if is_filelog:
                logging.error(exc.args[0])
            sys.stderr.write('failure: ' + exc.args[0] + '\n')
        elif isinstance(exc, PickleError) or isinstance(exc, EOFError) or \
            ((isinstance(exc, OSError) or isinstance(exc, IOError)) and
             exc.errno == EPIPE):
            logging.error('connection to peer is broken')
            if hasattr(gconf, 'transport'):
                gconf.transport.wait()
                if gconf.transport.returncode == 127:
                    logging.error("getting \"No such file or directory\""
                                  "errors is most likely due to "
                                  "MISCONFIGURATION, please remove all "
                                  "the public keys added by geo-replication "
                                  "from authorized_keys file in slave nodes "
                                  "and run Geo-replication create "
                                  "command again.")
                    logging.error("If `gsec_create container` was used, then "
                                  "run `gluster volume geo-replication "
                                  "<MASTERVOL> [<SLAVEUSER>@]<SLAVEHOST>::"
                                  "<SLAVEVOL> config remote-gsyncd "
                                  "<GSYNCD_PATH> (Example GSYNCD_PATH: "
                                  "`/usr/libexec/glusterfs/gsyncd`)")
                gconf.transport.terminate_geterr()
        elif isinstance(exc, OSError) and exc.errno in (ENOTCONN,
                                                        ECONNABORTED):
            logging.error(lf('glusterfs session went down',
                             error=errorcode[exc.errno]))
        else:
            logtag = "FAIL"
        if not logtag and logging.getLogger().isEnabledFor(logging.DEBUG):
            logtag = "FULL EXCEPTION TRACE"
        if logtag:
            logging.exception(logtag + ": ")
            sys.stderr.write("failed with %s.\n" % type(exc).__name__)
        excont.exval = 1
        sys.exit(excont.exval)


class FreeObject(object):

    """wildcard class for which any attribute can be set"""

    def __init__(self, **kw):
        for k, v in kw.items():
            setattr(self, k, v)


class Thread(baseThread):

    """thread class flavor for gsyncd

    - always a daemon thread
    - force exit for whole program if thread
      function coughs up an exception
    """

    def __init__(self, *a, **kw):
        tf = kw.get('target')
        if tf:
            def twrap(*aa):
                excont = FreeObject(exval=0)
                try:
                    tf(*aa)
                except:
                    try:
                        log_raise_exception(excont)
                    finally:
                        finalize(exval=excont.exval)
            kw['target'] = twrap
        baseThread.__init__(self, *a, **kw)
        self.setDaemon(True)


class GsyncdError(Exception):
    pass


class _MetaXattr(object):

    """singleton class, a lazy wrapper around the
    libcxattr module

    libcxattr (a heavy import due to ctypes) is
    loaded only when when the single
    instance is tried to be used.

    This reduces runtime for those invocations
    which do not need filesystem manipulation
    (eg. for config, url parsing)
    """

    def __getattr__(self, meth):
        from libcxattr import Xattr as LXattr
        xmeth = [m for m in dir(LXattr) if m[0] != '_']
        if meth not in xmeth:
            return
        for m in xmeth:
            setattr(self, m, getattr(LXattr, m))
        return getattr(self, meth)


Xattr = _MetaXattr()


def getusername(uid=None):
    if uid is None:
        uid = os.geteuid()
    return pwd.getpwuid(uid).pw_name


def privileged():
    return os.geteuid() == 0


def boolify(s):
    """
    Generic string to boolean converter

    return
    - Quick return if string 's' is of type bool
    - True if it's in true_list
    - False if it's in false_list
    - Warn if it's not present in either and return False
    """
    true_list = ['true', 'yes', '1', 'on']
    false_list = ['false', 'no', '0', 'off']

    if isinstance(s, bool):
        return s

    rv = False
    lstr = s.lower()
    if lstr in true_list:
        rv = True
    elif not lstr in false_list:
        logging.warn(lf("Unknown string in \"string to boolean\" conversion, "
                        "defaulting to False",
                        str=s))

    return rv


def eintr_wrap(func, exc, *a):
    """
    wrapper around syscalls resilient to interrupt caused
    by signals
    """
    while True:
        try:
            return func(*a)
        except exc:
            ex = sys.exc_info()[1]
            if not ex.args[0] == EINTR:
                raise


def select(*a):
    return eintr_wrap(oselect.select, oselect.error, *a)


def waitpid(*a):
    return eintr_wrap(owaitpid, OSError, *a)


def set_term_handler(hook=lambda *a: finalize(*a, **{'exval': 1})):
    signal(SIGTERM, hook)


def get_node_uuid():
    global NodeID
    if NodeID is not None:
        return NodeID

    NodeID = ""
    with open(UUID_FILE) as f:
        for line in f:
            if line.startswith("UUID="):
                NodeID = line.strip().split("=")[-1]
                break

    if NodeID == "":
        raise GsyncdError("Failed to get Host UUID from %s" % UUID_FILE)
    return NodeID


def is_host_local(host_id):
    return host_id == get_node_uuid()


def funcode(f):
    fc = getattr(f, 'func_code', None)
    if not fc:
        # python 3
        fc = f.__code__
    return fc


def memoize(f):
    fc = funcode(f)
    fn = fc.co_name

    def ff(self, *a, **kw):
        rv = getattr(self, '_' + fn, None)
        if rv is None:
            rv = f(self, *a, **kw)
            setattr(self, '_' + fn, rv)
        return rv
    return ff


def umask():
    return os.umask(0)


def entry2pb(e):
    return e.rsplit('/', 1)


def gauxpfx():
    return _CL_AUX_GFID_PFX


def md5hex(s):
    return md5(s).hexdigest()


def selfkill(sig=SIGTERM):
    os.kill(os.getpid(), sig)


def errno_wrap(call, arg=[], errnos=[], retry_errnos=[]):
    """ wrapper around calls resilient to errnos.
    """
    nr_tries = 0
    while True:
        try:
            return call(*arg)
        except OSError:
            ex = sys.exc_info()[1]
            if ex.errno in errnos:
                return ex.errno
            if not ex.errno in retry_errnos:
                raise
            nr_tries += 1
            if nr_tries == GF_OP_RETRIES:
                # probably a screwed state, cannot do much...
                logging.warn(lf('reached maximum retries',
                                args=repr(arg),
                                error=ex))
                raise
            time.sleep(0.250)  # retry the call


def lstat(e):
    return errno_wrap(os.lstat, [e], [ENOENT], [ESTALE, EBUSY])


def get_gfid_from_mnt(gfidpath):
    return errno_wrap(Xattr.lgetxattr,
                      [gfidpath, 'glusterfs.gfid.string',
                       GX_GFID_CANONICAL_LEN], [ENOENT], [ESTALE])


def matching_disk_gfid(gfid, entry):
    disk_gfid = get_gfid_from_mnt(entry)
    if isinstance(disk_gfid, int):
        return False

    if not gfid == disk_gfid:
        return False

    return True


class NoStimeAvailable(Exception):
    pass


class PartialHistoryAvailable(Exception):
    pass


class ChangelogHistoryNotAvailable(Exception):
    pass


class ChangelogException(OSError):
    pass


def gf_event(event_type, **kwargs):
    if EVENTS_ENABLED:
        from events.gf_event import gf_event as gfevent
        gfevent(event_type, **kwargs)


class GlusterLogLevel(object):
        NONE = 0
        EMERG = 1
        ALERT = 2
        CRITICAL = 3
        ERROR = 4
        WARNING = 5
        NOTICE = 6
        INFO = 7
        DEBUG = 8
        TRACE = 9


def get_changelog_log_level(lvl):
    return getattr(GlusterLogLevel, lvl, GlusterLogLevel.INFO)


def get_master_and_slave_data_from_args(args):
    master_name = None
    slave_data = None
    for arg in args:
        if arg.startswith(":"):
            master_name = arg.replace(":", "")
        if "::" in arg:
            slave_data = arg.replace("ssh://", "")

    return (master_name, slave_data)


def get_rsync_version(rsync_cmd):
    global rsync_version
    if rsync_version is not None:
        return rsync_version

    rsync_version = "0"
    p = subprocess.Popen([rsync_cmd, "--version"],
                         stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE)
    out, err = p.communicate()
    if p.returncode == 0:
        rsync_version = out.split(" ", 4)[3]

    return rsync_version


def lf(event, **kwargs):
    """
    Log Format helper function, log messages can be
    easily modified to structured log format.
    lf("Config Change", sync_jobs=4, brick=/bricks/b1) will be
    converted as "Config Change<TAB>brick=/bricks/b1<TAB>sync_jobs=4"
    """
    msg = event
    for k, v in kwargs.items():
        msg += "\t{0}={1}".format(k, v)
    return msg