Skip to content

Commit

Permalink
introduced pidfile
Browse files Browse the repository at this point in the history
  • Loading branch information
kazeburo committed Feb 22, 2019
1 parent 4dd9df3 commit dc92e56
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
9 changes: 9 additions & 0 deletions chocon.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/fukata/golang-stats-api-handler"
"github.com/jessevdk/go-flags"
"github.com/kazeburo/chocon/accesslog"
"github.com/kazeburo/chocon/pidfile"
"github.com/kazeburo/chocon/proxy"
"github.com/kazeburo/chocon/upstream"
"github.com/lestrrat/go-server-starter-listener"
Expand All @@ -32,6 +33,7 @@ type cmdOpts struct {
LogDir string `long:"access-log-dir" default:"" description:"directory to store logfiles"`
LogRotate int64 `long:"access-log-rotate" default:"30" description:"Number of day before remove logs"`
Version bool `short:"v" long:"version" description:"Show version"`
PidFile string `long:"pid-file" default:"" description:"filename to store pid. disabled by default"`
KeepaliveConns int `short:"c" default:"2" long:"keepalive-conns" description:"maximum keepalive connections for upstream"`
MaxConnsPerHost int `long:"max-conns-per-host" default:"0" description:"maximum connections per host"`
ReadTimeout int `long:"read-timeout" default:"30" description:"timeout of reading request"`
Expand Down Expand Up @@ -118,6 +120,13 @@ func main() {
log.Fatal(err)
}

if opts.PidFile != "" {
err = pidfile.WritePid(opts.PidFile)
if err != nil {
log.Fatal(err)
}
}

transport := makeTransport(opts.KeepaliveConns, opts.MaxConnsPerHost, opts.ProxyReadTimeout)
var handler http.Handler = proxy.New(&transport, Version, upstream, logger)

Expand Down
30 changes: 30 additions & 0 deletions pidfile/pidfile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package pidfile

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"

"github.com/pkg/errors"
)

// WritePid : write pid to given file
func WritePid(pidfile string) error {
dir, filename := filepath.Split(pidfile)
tmpfile, err := ioutil.TempFile(dir, filename+".*")
if err != nil {
return errors.Wrap(err, "Cloud not create tempfile")
}
_, err = tmpfile.WriteString(fmt.Sprintf("%d", os.Getpid()))
if err != nil {
tmpfile.Close()
return errors.Wrap(err, "Cloud not write pid to tempfile")
}
tmpfile.Close()
err = os.Rename(tmpfile.Name(), pidfile)
if err != nil {
return errors.Wrap(err, "Cloud not rename pidfile")
}
return nil
}

0 comments on commit dc92e56

Please sign in to comment.