lock.go 873 Bytes
Newer Older
Sebastian Stark's avatar
Sebastian Stark committed
1
/* See the file "LICENSE.txt" for the full license governing this code. */
2 3 4

// Simple lock file mechanism to prevent multiple instances to run

5 6 7
package main

import (
Sebastian Stark's avatar
gofmt  
Sebastian Stark committed
8 9 10 11
	"io/ioutil"
	"log"
	"os"
	"strconv"
12 13
)

Sebastian Stark's avatar
Sebastian Stark committed
14
type pidLocker struct {
Sebastian Stark's avatar
gofmt  
Sebastian Stark committed
15 16
	pid int
	f   string
17 18
}

Sebastian Stark's avatar
Sebastian Stark committed
19 20
func newPidLocker(lockfile string) *pidLocker {
	return &pidLocker{
Sebastian Stark's avatar
gofmt  
Sebastian Stark committed
21 22 23
		pid: os.Getpid(),
		f:   lockfile,
	}
24 25
}

Sebastian Stark's avatar
Sebastian Stark committed
26
func (pl *pidLocker) Lock() {
Sebastian Stark's avatar
gofmt  
Sebastian Stark committed
27 28 29 30
	_, err := os.Stat(pl.f)
	if err == nil {
		log.Fatalf("pid file %s already exists. Is snaprd running already?", pl.f)
	}
Sebastian Stark's avatar
Sebastian Stark committed
31
	debugf("write pid %d to pidfile %s", pl.pid, pl.f)
Sebastian Stark's avatar
gofmt  
Sebastian Stark committed
32 33 34 35
	err = ioutil.WriteFile(pl.f, []byte(strconv.Itoa(pl.pid)), 0666)
	if err != nil {
		log.Fatalf("could not write pid file %s", pl.f)
	}
36 37
}

Sebastian Stark's avatar
Sebastian Stark committed
38 39
func (pl *pidLocker) Unlock() {
	debugf("delete pidfile %s", pl.f)
Sebastian Stark's avatar
gofmt  
Sebastian Stark committed
40 41 42 43
	err := os.Remove(pl.f)
	if err != nil {
		log.Fatalf("could not remove pid file %s", pl.f)
	}
44
}