File: pidfile.go

package info (click to toggle)
golang-github-facebookgo-pidfile 0.0~git20150612.f242e29-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 80 kB
  • sloc: makefile: 2
file content (89 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Package pidfile manages pid files.
package pidfile

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"

	"github.com/facebookgo/atomicfile"
)

var (
	errNotConfigured = errors.New("pidfile not configured")
	pidfile          = flag.String("pidfile", "", "If specified, write pid to file.")
)

// IsNotConfigured returns true if the error indicates the pidfile location has
// not been configured.
func IsNotConfigured(err error) bool {
	if err == errNotConfigured {
		return true
	}
	return false
}

// GetPidfilePath returns the configured pidfile path.
func GetPidfilePath() string {
	return *pidfile
}

// SetPidfilePath sets the pidfile path.
func SetPidfilePath(p string) {
	*pidfile = p
}

// Write the pidfile based on the flag. It is an error if the pidfile hasn't
// been configured.
func Write() error {
	if *pidfile == "" {
		return errNotConfigured
	}

	if err := os.MkdirAll(filepath.Dir(*pidfile), os.FileMode(0755)); err != nil {
		return err
	}

	file, err := atomicfile.New(*pidfile, os.FileMode(0644))
	if err != nil {
		return fmt.Errorf("error opening pidfile %s: %s", *pidfile, err)
	}
	defer file.Close() // in case we fail before the explicit close

	_, err = fmt.Fprintf(file, "%d", os.Getpid())
	if err != nil {
		return err
	}

	err = file.Close()
	if err != nil {
		return err
	}

	return nil
}

// Read the pid from the configured file. It is an error if the pidfile hasn't
// been configured.
func Read() (int, error) {
	if *pidfile == "" {
		return 0, errNotConfigured
	}

	d, err := ioutil.ReadFile(*pidfile)
	if err != nil {
		return 0, err
	}

	pid, err := strconv.Atoi(string(bytes.TrimSpace(d)))
	if err != nil {
		return 0, fmt.Errorf("error parsing pid from %s: %s", *pidfile, err)
	}

	return pid, nil
}