'Open the file and lock it.
Tries to create a .lock file next to the file we\'re trying to open.
Args:
timeout: float, How long to try to lock for.
delay: float, How long to wait between retries.
Raises:
AlreadyLockedException: if the lock is already acquired.
IOError: if the open fails.'

def open_and_lock(self, timeout, delay):

    if self._locked:
        raise AlreadyLockedException(('File    %s    is    already    locked' % self._filename))
    self._locked = False
    try:
        self._fh = open(self._filename, self._mode)
    except IOError as e:
        if (e.errno == errno.EACCES):
            self._fh = open(self._filename, self._fallback_mode)
            return
    lock_filename = self._posix_lockfile(self._filename)
    start_time = time.time()
    while True:
        try:
            self._lock_fd = os.open(lock_filename, ((os.O_CREAT | os.O_EXCL) | os.O_RDWR))
            self._locked = True
            break
        except OSError as e:
            if (e.errno != errno.EEXIST):
                raise
            if ((time.time() - start_time) >= timeout):
                logger.warn(('Could    not    acquire    lock    %s    in    %s    seconds' % (lock_filename, timeout)))
                if self._fh:
                    self._fh.close()
                self._fh = open(self._filename, self._fallback_mode)
                return
            time.sleep(delay)
