File locking on NFS : deadlocks : proposed solution with code

Hi,

Please find below a proposed solution to the file locking issue experience by Thomas from Bouncing Orange (message links below)

The main cause of the locks found (in my opinion) is the fact that the files are stored on an NFS mounted file system. NFS and the locks don't play nicely.

My code creates 'hard links' to the file that is being cached, and the lock is placed on the hard link.
The 'main' file is thus never locked.
This code has not been tested in a production environment.
Posted here to get opinions, and potential improvements.

diff attached.

Proposed routines:

function spip_fopen_lock($fichier,$mode,$verrou){
    global $lockArray;
    $fp = false;
    if (file_exists($fichier) and !strpos($fichier,'session')) {
        // do we already have a lockfile for this file?
        if (is_array($lockArray) && in_array($ficher,$lockArray)) {
            $fichier = $hardlinkfile;
        } else {
            // create unique hard link filename
            $UUID = time()."_".$_SERVER['REMOTE_ADDR'];
            $hardlinkfile = dirname($fichier)."/".basename($fichier).$UUID."_lock";
            try {
                $lock=link($fichier,$hardlinkfile);
            } catch (Exception $e) {
                return false; }
        }
        $fp = @fopen($hardlinkfile,$mode);
        if ($fp){
            $lockArray[$fp]=array('hardlinkfile'=>$hardlinkfile,'originalfile'=>$fichier);
            //session_set('filelocks',serialize($lockArray)); }
    } else {
        $fp = @fopen($fichier,$mode);
    }
    return ($fp)?$fp:False;
}

function spip_fclose_unlock($handle){
    // remove old lock file
    global $lockArray;
    @fclose($handle);
    $result = @unlink($lockArray[$handle]['hardlinkfile']);
    if ($result){
        $lockArray[$handle] = ''; // just because I am paranoid.
        unset($lockArray[$handle]);
    }
}

Messages refer:
http://www.mail-archive.com/spip-en@rezo.net/msg00435.html
http://www.mail-archive.com/spip-en@rezo.net/msg00514.html

--
Regards
Lucas van Staden

Contractor: Bouncing Orange

flock_hardlink_diff.php (1.98 KB)