From 1256bf37f092becc9592e66b9b7fec12f16c3a16 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Tue, 6 May 2014 12:43:33 -0700 Subject: [PATCH] agent: Minor cleanups --- command/agent/agent.go | 68 ++++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/command/agent/agent.go b/command/agent/agent.go index bd6b741c3c..51580c28c2 100644 --- a/command/agent/agent.go +++ b/command/agent/agent.go @@ -107,6 +107,7 @@ func Create(config *Config, logOutput io.Writer) (*Agent, error) { return nil, err } + // Write out the PID file if necessary err = agent.storePid() if err != nil { return nil, err @@ -507,49 +508,50 @@ func (a *Agent) Stats() map[string]map[string]string { return stats } +// storePid is used to write out our PID to a file if necessary func (a *Agent) storePid() error { + // Quit fast if no pidfile pidPath := a.config.PidFile - - if pidPath != "" { - pid := os.Getpid() - pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) - - if err != nil { - return fmt.Errorf("Could not open pid file: %v", err) - } - - defer pidFile.Close() - - _, err = pidFile.WriteString(fmt.Sprintf("%d", pid)) - - if err != nil { - return fmt.Errorf("Could not write to pid file: %s", err) - } + if pidPath == "" { + return nil } + // Open the PID file + pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) + if err != nil { + return fmt.Errorf("Could not open pid file: %v", err) + } + defer pidFile.Close() + + // Write out the PID + pid := os.Getpid() + _, err = pidFile.WriteString(fmt.Sprintf("%d", pid)) + if err != nil { + return fmt.Errorf("Could not write to pid file: %s", err) + } return nil } +// deletePid is used to delete our PID on exit func (a *Agent) deletePid() error { + // Quit fast if no pidfile pidPath := a.config.PidFile - - if pidPath != "" { - stat, err := os.Stat(pidPath) - - if err != nil { - return fmt.Errorf("Could not remove pid file: %s", err) - } - - if stat.IsDir() { - return fmt.Errorf("Specified pid file path is directory") - } - - err = os.Remove(pidPath) - - if err != nil { - return fmt.Errorf("Could not remove pid file: %s", err) - } + if pidPath == "" { + return nil } + stat, err := os.Stat(pidPath) + if err != nil { + return fmt.Errorf("Could not remove pid file: %s", err) + } + + if stat.IsDir() { + return fmt.Errorf("Specified pid file path is directory") + } + + err = os.Remove(pidPath) + if err != nil { + return fmt.Errorf("Could not remove pid file: %s", err) + } return nil }