summaryrefslogtreecommitdiff
path: root/tct/resource_locking.py
blob: 7c94e30727d662f3adec584eb5ff4bcb4d16ee7d (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

##
# @author Aleksander Mistewicz <a.mistewicz@samsung.com>

import os
import time
import subprocess
import argparse
import logging

__version__ = "0.0.1"
__license__ = "APACHE-2.0"
__author__ = "Aleksander Mistewicz"
__author_email__ = "a.mistewicz@samsung.com"

USAGE = "%prog <opts>"

UUID_DIR = "/var/tmp/"
UUID_PREFIX="uuid-"
LOCK_SUFFIX=".lock"
CNT_SUFFIX=".cnt"

class Lockfile(object):
    @classmethod
    def lock(self, filename):
        logging.debug("Lock: %s", filename)
        return subprocess.call(["lockfile-create", "--retry", "0", "--use-pid", filename])

    @classmethod
    def unlock(self, filename):
        logging.debug("Unlock: %s", filename)
        return subprocess.call(["lockfile-remove", filename])

    @classmethod
    def check(self, filename):
        logging.debug("Check: %s", filename)
        return subprocess.call(["lockfile-check", "--use-pid", filename])

class UUIDlist(object):
    @classmethod
    def all(self):
        return os.listdir(UUID_DIR)

    @classmethod
    def uuid(self):
        ret = set()
        for f in self.all():
            if f.startswith(UUID_PREFIX) \
                and not f.endswith(LOCK_SUFFIX) \
                and not f.endswith(CNT_SUFFIX):
                ret.add(f)
        return ret

    @classmethod
    def target(self, target):
        ret = set()
        for f in self.uuid():
            if f.startswith(UUID_PREFIX + target):
                ret.add(f)
        return ret

    @classmethod
    def not_locked(self, target_list):
        ret = set()
        for f in target_list:
            if Lockfile.check(UUID_DIR + f):
                ret.add(f)
        return ret

    @classmethod
    def get_cnt(self, uuid):
        fname = UUID_DIR + uuid + CNT_SUFFIX
        logging.debug("Get counter from: %s", fname)
        if os.path.isfile(fname):
            with open(fname, 'r') as f:
                return int(f.read())
        return 0

    @classmethod
    def set_cnt(self, uuid, value):
        fname = UUID_DIR + uuid + CNT_SUFFIX
        logging.debug("Set counter (%d) for: %s", value, fname)
        with open(fname, 'w') as f:
            f.write(str(value))

    @classmethod
    def sort_cnt(self, targets):
        cnt = dict()
        ret = list(targets)
        for u in ret:
            cnt[u]=self.get_cnt(u)
        logging.debug("UUID files with counters: %s", cnt)
        ret.sort(key=cnt.__getitem__)
        logging.debug("Sorted list of UUIDs: %s", ret)
        return ret

class UUIDmanager:
    def __init__(self, target, inc, holdoff):
        self.target = target
        self.inc = inc
        self.holdoff = holdoff

    def lock(self):
        # go through the list of not locked uuid files and stop on the first successfully locked
        # returns False if none of the uuid files was locked
        # otherwise it returns True and prints filename on stdout
        for uuid in UUIDlist.sort_cnt(UUIDlist.not_locked(UUIDlist.target(self.target))):
            if Lockfile.lock(UUID_DIR + uuid) == 0:
                logging.info("Locked: %s", uuid)
                with open(UUID_DIR + uuid + LOCK_SUFFIX, 'w') as f:
                    f.write(str(os.getppid()))
                UUIDlist.set_cnt(uuid, UUIDlist.get_cnt(uuid)+1)
                print uuid[len(UUID_PREFIX):]
                return True
        logging.info("Failed to lock")
        return False

    def target_list_is_empty(self):
        # return True if there are no files available for target (including locked)
        # False otherwise
        target_list = UUIDlist.target(self.target)
        if len(target_list) == 0:
            logging.error("Target list for \"%s\" is empty", self.target)
            return True
        return False

    def unlock(self):
        # remove lock on specified target
        # returns True if operation was successful (no lock is present)
        # False otherwise
        logging.info("Unlocking: %s", self.target)
        return Lockfile.unlock(UUID_DIR + UUID_PREFIX + self.target) == 0

    def retrylock(self):
        # try to lock a target every self.holdoff seconds
        # returns False if there are no available targets
        # True otherwise
        while not self.lock():
            if self.target_list_is_empty():
                return False
            time.sleep(self.holdoff)
        return True

    def unlockfailed(self):
        # unlock target as usual and increase its counter by self.inc
        if not self.unlock():
            logging.warn("Unlock failed: %s", self.target)
        uuid = UUID_PREFIX + self.target
        UUIDlist.set_cnt(uuid, UUIDlist.get_cnt(uuid) + self.inc)

def parse_arguments():
    parser = argparse.ArgumentParser(description="Manager of locks on UUID files")

    group = parser.add_mutually_exclusive_group()

    parser.add_argument("target",
            help="Choose type of a target device to lock/unlock")

    group.add_argument("-l", "--lock",
            action="store_true", default=False, dest="lock",
            help="Lock a device")

    group.add_argument("-r", "--retrylock",
            action="store_true", default=False, dest="retrylock",
            help="Try to lock a device every HOLDOFF seconds until successful")

    parser.add_argument("--holdoff", type=int,
            action="store", default=60, dest="holdoff",
            help="Set HOLDOFF value (default: 60)")

    group.add_argument("-u", "--unlock",
            action="store_true", default=False, dest="unlock",
            help="Unlock a device")

    group.add_argument("-f", "--unlockfailed",
            action="store_true", default=False, dest="unlockfailed",
            help="Unlock a device and increment counter by INC")

    parser.add_argument("--inc", type=int,
            action="store", default=10, dest="inc",
            help="Set INC value (default: 10)")

    parser.add_argument("-L", "--log",
            action="store", dest="loglevel",
            help="Verbosity level")

    args = parser.parse_args()

    return args

def main():
    args = parse_arguments()
    if args.loglevel:
        numeric_level = getattr(logging, args.loglevel.upper(), None)
        if not isinstance(numeric_level, int):
            raise ValueError('Invalid log level: %s' % args.loglevel)
        logging.basicConfig(format='%(asctime)s %(message)s',level=numeric_level)
    logging.debug("Begin")
    uuid_man = UUIDmanager(args.target, args.inc, args.holdoff)
    if args.lock:
        if not uuid_man.lock():
            logging.warn("File locking unsuccessful!")
    elif args.unlock:
        if not uuid_man.unlock():
            logging.warn("File unlocking unsuccessful!")
    elif args.retrylock:
        if not uuid_man.retrylock():
            logging.warn("Retrylock unsuccessful!")
    elif args.unlockfailed:
        uuid_man.unlockfailed()
    logging.debug("End")

if __name__ == '__main__':
    main()