__author__ = 'hzp'

import fcntl
import os.path
import time

fp = {}


def get_lock(lock_path, force=False, timeout=30, filename="easyops.lock"):
    global fp
    if not os.path.exists(lock_path):
        os.makedirs(lock_path, 0755)
    lock_file = os.path.join(lock_path, filename)
    if os.path.isfile(lock_file):
        try:
            os.chmod(lock_file, 0o777)
        except OSError:
            pass

    fp[lock_file] = open(lock_file, 'w')
    count = 0
    while count < timeout:
        count += 1
        try:
            fcntl.flock(fp[lock_file], fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            if force:
                return True
            time.sleep(1)
        else:
            return True
    return False


def release_lock(lock_path, filename="easyops.lock"):
    global fp
    lock_file = os.path.join(lock_path, filename)
    fp[lock_file].close()
    if os.path.isfile(lock_file):
        try:
            os.chmod(lock_file, 0o777)
        except OSError:
            pass
