Merge pull request #11 from dcbw/dhcp-pidfile

dhcp: add --pidfile option to DHCP client daemon
This commit is contained in:
Gabe Rosenhouse 2017-06-15 22:48:42 -07:00 committed by GitHub
commit 494053dd98
3 changed files with 28 additions and 5 deletions

View File

@ -16,6 +16,9 @@ $ rm -f /run/cni/dhcp.sock
$ ./dhcp daemon $ ./dhcp daemon
``` ```
If given `-pidfile <path>` arguments after 'daemon', the dhcp plugin will write
its PID to the given file.
Alternatively, you can use systemd socket activation protocol. Alternatively, you can use systemd socket activation protocol.
Be sure that the .socket file uses /run/cni/dhcp.sock as the socket path. Be sure that the .socket file uses /run/cni/dhcp.sock as the socket path.

View File

@ -18,7 +18,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"log" "io/ioutil"
"net" "net"
"net/http" "net/http"
"net/rpc" "net/rpc"
@ -141,19 +141,29 @@ func getListener() (net.Listener, error) {
} }
} }
func runDaemon() { func runDaemon(pidfilePath string) error {
// since other goroutines (on separate threads) will change namespaces, // since other goroutines (on separate threads) will change namespaces,
// ensure the RPC server does not get scheduled onto those // ensure the RPC server does not get scheduled onto those
runtime.LockOSThread() runtime.LockOSThread()
// Write the pidfile
if pidfilePath != "" {
if !filepath.IsAbs(pidfilePath) {
return fmt.Errorf("Error writing pidfile %q: path not absolute", pidfilePath)
}
if err := ioutil.WriteFile(pidfilePath, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
return fmt.Errorf("Error writing pidfile %q: %v", pidfilePath, err)
}
}
l, err := getListener() l, err := getListener()
if err != nil { if err != nil {
log.Printf("Error getting listener: %v", err) return fmt.Errorf("Error getting listener: %v", err)
return
} }
dhcp := newDHCP() dhcp := newDHCP()
rpc.Register(dhcp) rpc.Register(dhcp)
rpc.HandleHTTP() rpc.HandleHTTP()
http.Serve(l, nil) http.Serve(l, nil)
return nil
} }

View File

@ -15,7 +15,9 @@
package main package main
import ( import (
"flag"
"fmt" "fmt"
"log"
"net/rpc" "net/rpc"
"os" "os"
"path/filepath" "path/filepath"
@ -30,7 +32,15 @@ const socketPath = "/run/cni/dhcp.sock"
func main() { func main() {
if len(os.Args) > 1 && os.Args[1] == "daemon" { if len(os.Args) > 1 && os.Args[1] == "daemon" {
runDaemon() var pidfilePath string
daemonFlags := flag.NewFlagSet("daemon", flag.ExitOnError)
daemonFlags.StringVar(&pidfilePath, "pidfile", "", "optional path to write daemon PID to")
daemonFlags.Parse(os.Args[2:])
if err := runDaemon(pidfilePath); err != nil {
log.Printf(err.Error())
os.Exit(1)
}
} else { } else {
skel.PluginMain(cmdAdd, cmdDel, version.All) skel.PluginMain(cmdAdd, cmdDel, version.All)
} }