mirror of
https://github.com/adnanh/webhook.git
synced 2025-06-03 03:02:29 +00:00
Add pidfile support
Copy a simple implementation from the Moby project, since importing their package would pull in too many dependencies. Fixes #320
This commit is contained in:
parent
569921cd72
commit
876c853073
35 changed files with 7198 additions and 2 deletions
51
internal/pidfile/pidfile.go
Normal file
51
internal/pidfile/pidfile.go
Normal file
|
@ -0,0 +1,51 @@
|
|||
// Package pidfile provides structure and helper functions to create and remove
|
||||
// PID file. A PID file is usually a file used to store the process ID of a
|
||||
// running process.
|
||||
package pidfile
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PIDFile is a file used to store the process ID of a running process.
|
||||
type PIDFile struct {
|
||||
path string
|
||||
}
|
||||
|
||||
func checkPIDFileAlreadyExists(path string) error {
|
||||
if pidByte, err := ioutil.ReadFile(path); err == nil {
|
||||
pidString := strings.TrimSpace(string(pidByte))
|
||||
if pid, err := strconv.Atoi(pidString); err == nil {
|
||||
if processExists(pid) {
|
||||
return fmt.Errorf("pid file found, ensure webhook is not running or delete %s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// New creates a PIDfile using the specified path.
|
||||
func New(path string) (*PIDFile, error) {
|
||||
if err := checkPIDFileAlreadyExists(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Note MkdirAll returns nil if a directory already exists
|
||||
if err := MkdirAll(filepath.Dir(path), os.FileMode(0755)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &PIDFile{path: path}, nil
|
||||
}
|
||||
|
||||
// Remove removes the PIDFile.
|
||||
func (file PIDFile) Remove() error {
|
||||
return os.Remove(file.path)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue