summaryrefslogtreecommitdiffstats
path: root/extras/snap_scheduler/snap_scheduler.py
blob: 1c5f9380dd8fbc61f06581cfd051c4e9c6e0478a (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
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
#!/usr/bin/env python
#
# Copyright (c) 2015 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.

from __future__ import print_function
import subprocess
import os
import os.path
import logging
import argparse
import fcntl
import logging.handlers
import sys
import shutil
from errno import EEXIST


SCRIPT_NAME = "snap_scheduler"
scheduler_enabled = False
log = logging.getLogger(SCRIPT_NAME)
SHARED_STORAGE_DIR="/var/run/gluster/shared_storage"
GCRON_DISABLED = SHARED_STORAGE_DIR+"/snaps/gcron_disabled"
GCRON_ENABLED = SHARED_STORAGE_DIR+"/snaps/gcron_enabled"
GCRON_TASKS = SHARED_STORAGE_DIR+"/snaps/glusterfs_snap_cron_tasks"
GCRON_CROND_TASK = "/etc/cron.d/glusterfs_snap_cron_tasks"
LOCK_FILE_DIR = SHARED_STORAGE_DIR+"/snaps/lock_files/"
LOCK_FILE = LOCK_FILE_DIR+"lock_file"
TMP_FILE = SHARED_STORAGE_DIR+"/snaps/tmp_file"
GCRON_UPDATE_TASK = "/etc/cron.d/gcron_update_task"
CURRENT_SCHEDULER = SHARED_STORAGE_DIR+"/snaps/current_scheduler"
tasks = {}
longest_field = 12
current_scheduler = ""

INTERNAL_ERROR = 2
SHARED_STORAGE_DIR_DOESNT_EXIST = 3
SHARED_STORAGE_NOT_MOUNTED = 4
ANOTHER_TRANSACTION_IN_PROGRESS = 5
INIT_FAILED = 6
SCHEDULING_ALREADY_DISABLED = 7
SCHEDULING_ALREADY_ENABLED = 8
NODE_NOT_INITIALISED = 9
ANOTHER_SCHEDULER_ACTIVE = 10
JOB_ALREADY_EXISTS = 11
JOB_NOT_FOUND = 12
INVALID_JOBNAME = 13
INVALID_VOLNAME = 14
INVALID_SCHEDULE = 15
INVALID_ARG = 16

def output(msg):
    print("%s: %s" % (SCRIPT_NAME, msg))


def initLogger():
    log.setLevel(logging.DEBUG)
    logFormat = "[%(asctime)s %(filename)s:%(lineno)s %(funcName)s] "\
        "%(levelname)s %(message)s"
    formatter = logging.Formatter(logFormat)

    sh = logging.handlers.SysLogHandler()
    sh.setLevel(logging.ERROR)
    sh.setFormatter(formatter)

    process = subprocess.Popen(["gluster", "--print-logdir"],
                               stdout=subprocess.PIPE)
    logfile = os.path.join(process.stdout.read()[:-1], SCRIPT_NAME + ".log")

    fh = logging.FileHandler(logfile)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)

    log.addHandler(sh)
    log.addHandler(fh)


def scheduler_status():
    ret = INTERNAL_ERROR
    global scheduler_enabled
    try:
        f = os.path.realpath(GCRON_TASKS)
        if f != os.path.realpath(GCRON_ENABLED) or not os.path.exists(GCRON_ENABLED):
            log.info("Snapshot scheduler is currently disabled.")
            scheduler_enabled = False
        else:
            log.info("Snapshot scheduler is currently enabled.")
            scheduler_enabled = True
        ret = 0
    except:
        log.error("Failed to enable snapshot scheduling. Error: "
                  "Failed to check the status of %s.", GCRON_DISABLED)

    return ret

def enable_scheduler():
    ret = scheduler_status()
    if ret == 0:
        if not scheduler_enabled:

            # Check if another scheduler is active.
            ret = get_current_scheduler()
            if ret == 0:
                if (current_scheduler != "none"):
                    print_str = "Failed to enable snapshot scheduling. " \
                                "Error: Another scheduler is active."
                    log.error(print_str)
                    output(print_str)
                    ret = ANOTHER_SCHEDULER_ACTIVE
                    return ret
            else:
                print_str = "Failed to get current scheduler info."
                log.error(print_str)
                output(print_str)
                return ret

            log.info("Enabling snapshot scheduler.")
            try:
                if os.path.exists(GCRON_DISABLED):
                    os.remove(GCRON_DISABLED)
                if os.path.lexists(GCRON_TASKS):
                    os.remove(GCRON_TASKS)
                try:
                    f = os.open(GCRON_ENABLED, os.O_CREAT | os.O_NONBLOCK,
                                0644)
                    os.close(f)
                except IOError as (errno, strerror):
                    log.error("Failed to open %s. Error: %s.",
                              GCRON_ENABLED, strerror)
                    ret = INTERNAL_ERROR
                    return ret
                os.symlink(GCRON_ENABLED, GCRON_TASKS)
                update_current_scheduler("cli")
                log.info("Snapshot scheduling is enabled")
                output("Snapshot scheduling is enabled")
                ret = 0
            except IOError as (errno, strerror):
                print_str = "Failed to enable snapshot scheduling. Error: "+strerror
                log.error(print_str)
                output(print_str)
                ret = INTERNAL_ERROR
        else:
            print_str = "Failed to enable snapshot scheduling. " \
                        "Error: Snapshot scheduling is already enabled."
            log.error(print_str)
            output(print_str)
            ret = SCHEDULING_ALREADY_ENABLED
    else:
        print_str = "Failed to enable snapshot scheduling. " \
                    "Error: Failed to check scheduler status."
        log.error(print_str)
        output(print_str)

    return ret


def disable_scheduler():
    ret = scheduler_status()
    if ret == 0:
        if scheduler_enabled:
            log.info("Disabling snapshot scheduler.")
            try:
                # Check if another scheduler is active. If not, then
                # update current scheduler to "none". Else do nothing.
                ret = get_current_scheduler()
                if ret == 0:
                    if (current_scheduler == "cli"):
                        update_current_scheduler("none")
                else:
                    print_str = "Failed to disable snapshot scheduling. " \
                                "Error: Failed to get current scheduler info."
                    log.error(print_str)
                    output(print_str)
                    return ret

                if os.path.exists(GCRON_DISABLED):
                    os.remove(GCRON_DISABLED)
                if os.path.lexists(GCRON_TASKS):
                    os.remove(GCRON_TASKS)
                f = os.open(GCRON_DISABLED, os.O_CREAT, 0644)
                os.close(f)
                os.symlink(GCRON_DISABLED, GCRON_TASKS)
                log.info("Snapshot scheduling is disabled")
                output("Snapshot scheduling is disabled")
                ret = 0
            except IOError as (errno, strerror):
                print_str = "Failed to disable snapshot scheduling. Error: "+strerror
                log.error(print_str)
                output(print_str)
                ret = INTERNAL_ERROR
        else:
            print_str = "Failed to disable scheduling. " \
                        "Error: Snapshot scheduling is already disabled."
            log.error(print_str)
            output(print_str)
            ret = SCHEDULING_ALREADY_DISABLED
    else:
        print_str = "Failed to disable snapshot scheduling. " \
                    "Error: Failed to check scheduler status."
        log.error(print_str)
        output(print_str)
        ret = INTERNAL_ERROR

    return ret


def load_tasks_from_file():
    global tasks
    global longest_field
    try:
        with open(GCRON_ENABLED, 'r') as f:
            for line in f:
                line = line.rstrip('\n')
                if not line:
                    break
                line = line.split("gcron.py")
                schedule = line[0].split("root")[0].rstrip(' ')
                line = line[1].split(" ")
                volname = line[1]
                jobname = line[2]
                longest_field = max(longest_field, len(jobname), len(volname),
                                    len(schedule))
                tasks[jobname] = schedule+":"+volname
            f.close()
        ret = 0
    except IOError as (errno, strerror):
        log.error("Failed to open %s. Error: %s.", GCRON_ENABLED, strerror)
        ret = INTERNAL_ERROR

    return ret


def get_current_scheduler():
    global current_scheduler
    try:
        with open(CURRENT_SCHEDULER, 'r') as f:
            current_scheduler = f.readline().rstrip('\n')
            f.close()
        ret = 0
    except IOError as (errno, strerror):
        log.error("Failed to open %s. Error: %s.", CURRENT_SCHEDULER, strerror)
        ret = INTERNAL_ERROR

    return ret


def list_schedules():
    log.info("Listing snapshot schedules.")
    ret = load_tasks_from_file()
    if ret == 0:
        if len(tasks) == 0:
            output("No snapshots scheduled")
        else:
            jobname = "JOB_NAME".ljust(longest_field+5)
            schedule = "SCHEDULE".ljust(longest_field+5)
            operation = "OPERATION".ljust(longest_field+5)
            volname = "VOLUME NAME".ljust(longest_field+5)
            hyphens = "".ljust((longest_field+5) * 4, '-')
            print(jobname+schedule+operation+volname)
            print(hyphens)
            for key in sorted(tasks):
                jobname = key.ljust(longest_field+5)
                schedule = tasks[key].split(":")[0].ljust(
                           longest_field + 5)
                volname = tasks[key].split(":")[1].ljust(
                          longest_field + 5)
                operation = "Snapshot Create".ljust(longest_field+5)
                print(jobname+schedule+operation+volname)
            ret = 0
    else:
        print_str = "Failed to list snapshot schedules. " \
                    "Error: Failed to load tasks from "+GCRON_ENABLED
        log.error(print_str)
        output(print_str)

    return ret


def write_tasks_to_file():
    try:
        with open(TMP_FILE, "w", 0644) as f:
            # If tasks is empty, just create an empty tmp file
            if len(tasks) != 0:
                for key in sorted(tasks):
                    jobname = key
                    schedule = tasks[key].split(":")[0]
                    volname = tasks[key].split(":")[1]
                    f.write("%s root PATH=$PATH:/usr/local/sbin:/usr/sbin "
                            "gcron.py %s %s\n" % (schedule, volname, jobname))
                f.write("\n")
                f.flush()
                os.fsync(f.fileno())
            f.close()
    except IOError as (errno, strerror):
        log.error("Failed to open %s. Error: %s.", TMP_FILE, strerror)
        ret = INTERNAL_ERROR
        return ret

    shutil.move(TMP_FILE, GCRON_ENABLED)
    ret = 0

    return ret

def update_current_scheduler(data):
    try:
        with open(TMP_FILE, "w", 0644) as f:
            f.write("%s" % data)
            f.flush()
            os.fsync(f.fileno())
            f.close()
    except IOError as (errno, strerror):
        log.error("Failed to open %s. Error: %s.", TMP_FILE, strerror)
        ret = INTERNAL_ERROR
        return ret

    shutil.move(TMP_FILE, CURRENT_SCHEDULER)
    ret = 0

    return ret


def add_schedules(jobname, schedule, volname):
    log.info("Adding snapshot schedules.")
    ret = load_tasks_from_file()
    if ret == 0:
        if jobname in tasks:
            print_str = ("%s already exists in schedule. Use "
                         "'edit' to modify %s" % (jobname, jobname))
            log.error(print_str)
            output(print_str)
            ret = JOB_ALREADY_EXISTS
        else:
            tasks[jobname] = schedule + ":" + volname
            ret = write_tasks_to_file()
            if ret == 0:
                # Create a LOCK_FILE for the job
                job_lockfile = LOCK_FILE_DIR + jobname
                try:
                    f = os.open(job_lockfile, os.O_CREAT | os.O_NONBLOCK, 0644)
                    os.close(f)
                except IOError as (errno, strerror):
                    log.error("Failed to open %s. Error: %s.",
                              job_lockfile, strerror)
                    ret = INTERNAL_ERROR
                    return ret
                log.info("Successfully added snapshot schedule %s" % jobname)
                output("Successfully added snapshot schedule")
                ret = 0
    else:
        print_str = "Failed to add snapshot schedule. " \
                    "Error: Failed to load tasks from "+GCRON_ENABLED
        log.error(print_str)
        output(print_str)

    return ret


def delete_schedules(jobname):
    log.info("Delete snapshot schedules.")
    ret = load_tasks_from_file()
    if ret == 0:
        if jobname in tasks:
            del tasks[jobname]
            ret = write_tasks_to_file()
            if ret == 0:
                # Delete the LOCK_FILE for the job
                job_lockfile = LOCK_FILE_DIR+jobname
                try:
                    os.remove(job_lockfile)
                except IOError as (errno, strerror):
                    log.error("Failed to open %s. Error: %s.",
                              job_lockfile, strerror)
                    ret = INTERNAL_ERROR
                    return ret
                log.info("Successfully deleted snapshot schedule %s"
                         % jobname)
                output("Successfully deleted snapshot schedule")
                ret = 0
        else:
            print_str = ("Failed to delete %s. Error: No such "
                         "job scheduled" % jobname)
            log.error(print_str)
            output(print_str)
            ret = JOB_NOT_FOUND
    else:
        print_str = "Failed to delete snapshot schedule. " \
                    "Error: Failed to load tasks from "+GCRON_ENABLED
        log.error(print_str)
        output(print_str)

    return ret


def edit_schedules(jobname, schedule, volname):
    log.info("Editing snapshot schedules.")
    ret = load_tasks_from_file()
    if ret == 0:
        if jobname in tasks:
            tasks[jobname] = schedule+":"+volname
            ret = write_tasks_to_file()
            if ret == 0:
                log.info("Successfully edited snapshot schedule %s" % jobname)
                output("Successfully edited snapshot schedule")
        else:
            print_str = ("Failed to edit %s. Error: No such "
                         "job scheduled" % jobname)
            log.error(print_str)
            output(print_str)
            ret = JOB_NOT_FOUND
    else:
        print_str = "Failed to edit snapshot schedule. " \
                    "Error: Failed to load tasks from "+GCRON_ENABLED
        log.error(print_str)
        output(print_str)

    return ret


def initialise_scheduler():
    try:
        with open("/tmp/crontab", "w+", 0644) as f:
            updater = ("* * * * * root PATH=$PATH:/usr/local/sbin:"
                       "/usr/sbin gcron.py --update\n")
            f.write("%s\n" % updater)
            f.flush()
            os.fsync(f.fileno())
            f.close()
    except IOError as (errno, strerror):
        log.error("Failed to open /tmp/crontab. Error: %s.", strerror)
        ret = INIT_FAILED
        return ret

    shutil.move("/tmp/crontab", GCRON_UPDATE_TASK)

    if not os.path.lexists(GCRON_TASKS):
        try:
            f = open(GCRON_TASKS, "w", 0644)
            f.close()
        except IOError as (errno, strerror):
            log.error("Failed to open %s. Error: %s.", GCRON_TASKS, strerror)
            ret = INIT_FAILED
            return ret

    if os.path.lexists(GCRON_CROND_TASK):
        os.remove(GCRON_CROND_TASK)

    os.symlink(GCRON_TASKS, GCRON_CROND_TASK)

    log.info("Successfully inited snapshot scheduler for this node")
    output("Successfully inited snapshot scheduler for this node")

    ret = 0
    return ret


def syntax_checker(args):
    if hasattr(args, 'jobname'):
        if (len(args.jobname.split()) != 1):
            output("Invalid Jobname. Jobname should not be empty and should not contain \" \" character.")
            ret = INVALID_JOBNAME
            return ret
        args.jobname=args.jobname.strip()

    if hasattr(args, 'volname'):
        if (len(args.volname.split()) != 1):
            output("Invalid Volname. Volname should not be empty and should not contain \" \" character.")
            ret = INVALID_VOLNAME
            return ret
        args.volname=args.volname.strip()

    if hasattr(args, 'schedule'):
        if (len(args.schedule.split()) != 5):
            output("Invalid Schedule. Please refer to the following for adding a valid cron schedule")
            print ("* * * * *")
            print ("| | | | |")
            print ("| | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)")
            print ("| | | +------ Month of the Year (range: 1-12)")
            print ("| | +-------- Day of the Month  (range: 1-31)")
            print ("| +---------- Hour              (range: 0-23)")
            print ("+------------ Minute            (range: 0-59)")
            ret = INVALID_SCHEDULE
            return ret

    ret = 0
    return ret


def perform_operation(args):
    # Initialise snapshot scheduler on local node
    if args.action == "init":
        ret = initialise_scheduler()
        if ret != 0:
            output("Failed to initialise snapshot scheduling")
        return ret

    # Disable snapshot scheduler
    if args.action == "disable_force":
        ret = disable_scheduler()
        if ret == 0:
            subprocess.Popen(["touch", "-h", GCRON_TASKS])
        return ret

    # Check if the symlink to GCRON_TASKS is properly set in the shared storage
    if (not os.path.lexists(GCRON_UPDATE_TASK) or
        not os.path.lexists(GCRON_CROND_TASK) or
        os.readlink(GCRON_CROND_TASK) != GCRON_TASKS):
        print_str = ("Please run 'snap_scheduler.py' init to initialise "
                     "the snap scheduler for the local node.")
        log.error(print_str)
        output(print_str)
        ret = NODE_NOT_INITIALISED
        return ret

    # Check status of snapshot scheduler.
    if args.action == "status":
        ret = scheduler_status()
        if ret == 0:
            if scheduler_enabled:
                output("Snapshot scheduling status: Enabled")
            else:
                output("Snapshot scheduling status: Disabled")
        else:
            output("Failed to check status of snapshot scheduler")
        return ret

    # Enable snapshot scheduler
    if args.action == "enable":
        ret = enable_scheduler()
        if ret == 0:
            subprocess.Popen(["touch", "-h", GCRON_TASKS])
        return ret

    # Disable snapshot scheduler
    if args.action == "disable":
        ret = disable_scheduler()
        if ret == 0:
            subprocess.Popen(["touch", "-h", GCRON_TASKS])
        return ret

    # List snapshot schedules
    if args.action == "list":
        ret = list_schedules()
        return ret

    # Add snapshot schedules
    if args.action == "add":
        ret = syntax_checker(args)
        if ret != 0:
            return ret
        ret = add_schedules(args.jobname, args.schedule, args.volname)
        if ret == 0:
            subprocess.Popen(["touch", "-h", GCRON_TASKS])
        return ret

    # Delete snapshot schedules
    if args.action == "delete":
        ret = syntax_checker(args)
        if ret != 0:
            return ret
        ret = delete_schedules(args.jobname)
        if ret == 0:
            subprocess.Popen(["touch", "-h", GCRON_TASKS])
        return ret

    # Edit snapshot schedules
    if args.action == "edit":
        ret = syntax_checker(args)
        if ret != 0:
            return ret
        ret = edit_schedules(args.jobname, args.schedule, args.volname)
        if ret == 0:
            subprocess.Popen(["touch", "-h", GCRON_TASKS])
        return ret

    ret = INVALID_ARG
    return ret


def main():
    initLogger()
    ret = -1
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest="action",
                                       metavar=('{init, status, enable,'
                                               ' disable, list, add,'
                                               ' delete, edit}'))
    subparsers.add_parser('init',
                          help="Initialise the node for snapshot scheduling")

    subparsers.add_parser("status",
                          help="Check if snapshot scheduling is "
                          "enabled or disabled")
    subparsers.add_parser("enable",
                          help="Enable snapshot scheduling")
    subparsers.add_parser("disable",
                          help="Disable snapshot scheduling")
    subparsers.add_parser("disable_force")
    subparsers.add_parser("list",
                          help="List snapshot schedules")
    parser_add = subparsers.add_parser("add",
                                       help="Add snapshot schedules")
    parser_add.add_argument("jobname", help="Job Name")
    parser_add.add_argument("schedule", help="Schedule")
    parser_add.add_argument("volname", help="Volume Name")

    parser_delete = subparsers.add_parser("delete",
                                          help="Delete snapshot schedules")
    parser_delete.add_argument("jobname", help="Job Name")
    parser_edit = subparsers.add_parser("edit",
                                        help="Edit snapshot schedules")
    parser_edit.add_argument("jobname", help="Job Name")
    parser_edit.add_argument("schedule", help="Schedule")
    parser_edit.add_argument("volname", help="Volume Name")

    args = parser.parse_args()

    if not os.path.exists(SHARED_STORAGE_DIR):
        output("Failed: "+SHARED_STORAGE_DIR+" does not exist.")
        return SHARED_STORAGE_DIR_DOESNT_EXIST

    if not os.path.ismount(SHARED_STORAGE_DIR):
        output("Failed: Shared storage is not mounted at "+SHARED_STORAGE_DIR)
        return SHARED_STORAGE_NOT_MOUNTED

    if not os.path.exists(SHARED_STORAGE_DIR+"/snaps/"):
        try:
            os.makedirs(SHARED_STORAGE_DIR+"/snaps/")
        except IOError as (errno, strerror):
            if errno != EEXIST:
                log.error("Failed to create %s : %s", SHARED_STORAGE_DIR+"/snaps/", strerror)
                output("Failed to create %s. Error: %s"
                       % (SHARED_STORAGE_DIR+"/snaps/", strerror))
                return INTERNAL_ERROR

    if not os.path.exists(GCRON_ENABLED):
        f = os.open(GCRON_ENABLED, os.O_CREAT | os.O_NONBLOCK, 0644)
        os.close(f)

    if not os.path.exists(LOCK_FILE_DIR):
        try:
            os.makedirs(LOCK_FILE_DIR)
        except IOError as (errno, strerror):
            if errno != EEXIST:
                log.error("Failed to create %s : %s", LOCK_FILE_DIR, strerror)
                output("Failed to create %s. Error: %s"
                       % (LOCK_FILE_DIR, strerror))
                return INTERNAL_ERROR

    if not os.path.exists(CURRENT_SCHEDULER):
        update_current_scheduler("none")

    try:
        f = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR | os.O_NONBLOCK, 0644)
        try:
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            ret = perform_operation(args)
            fcntl.flock(f, fcntl.LOCK_UN)
        except IOError as (errno, strerror):
            log.info("%s is being processed by another agent.", LOCK_FILE)
            output("Another snap_scheduler command is running. "
                   "Please try again after some time.")
            return ANOTHER_TRANSACTION_IN_PROGRESS
        os.close(f)
    except IOError as (errno, strerror):
        log.error("Failed to open %s : %s", LOCK_FILE, strerror)
        output("Failed to open %s. Error: %s" % (LOCK_FILE, strerror))
        return INTERNAL_ERROR

    return ret


if __name__ == "__main__":
    sys.exit(main())