Skip to content

Commit

Permalink
Moved hostid related methods under config.Config
Browse files Browse the repository at this point in the history
  • Loading branch information
motemen committed Nov 26, 2015
1 parent 0ce0115 commit 2dc5489
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 52 deletions.
56 changes: 7 additions & 49 deletions command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ import (
"crypto/sha1"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
"strings"
"time"

"github.com/Songmu/retry"
Expand All @@ -25,52 +22,12 @@ import (
var logger = logging.GetLogger("command")
var metricsInterval = 60 * time.Second

const idFileName = "id"

func idFilePath(root string) string {
return filepath.Join(root, idFileName)
}

// LoadHostID loads hostID
func LoadHostID(root string) (string, error) {
content, err := ioutil.ReadFile(idFilePath(root))
if err != nil {
return "", err
}
return strings.TrimRight(string(content), "\r\n"), nil
}

// RemoveIDFile removes idfile
func RemoveIDFile(root string) error {
return os.Remove(idFilePath(root))
}

func saveHostID(root string, id string) error {
err := os.MkdirAll(root, 0755)
if err != nil {
return err
}

file, err := os.Create(idFilePath(root))
if err != nil {
return err
}
defer file.Close()

_, err = file.Write([]byte(id))
if err != nil {
return err
}

return nil
}

var retryNum uint = 20
var retryInterval = 3 * time.Second

// prepareHost collects specs of the host and sends them to Mackerel server.
// A unique host-id is returned by the server if one is not specified.
func prepareHost(root string, api *mackerel.API, roleFullnames []string, checks []string, displayName string, hostSt string) (*mackerel.Host, error) {
func prepareHost(conf *config.Config, api *mackerel.API) (*mackerel.Host, error) {
// XXX this configuration should be moved to under spec/linux
os.Setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin:"+os.Getenv("PATH"))
os.Setenv("LANG", "C") // prevent changing outputs of some command, e.g. ifconfig.
Expand All @@ -96,11 +53,11 @@ func prepareHost(root string, api *mackerel.API, roleFullnames []string, checks
}

var result *mackerel.Host
if hostID, err := LoadHostID(root); err != nil { // create
if hostID, err := conf.LoadHostID(); err != nil { // create
logger.Debugf("Registering new host on mackerel...")

doRetry(func() error {
hostID, lastErr = api.CreateHost(hostname, meta, interfaces, roleFullnames, displayName)
hostID, lastErr = api.CreateHost(hostname, meta, interfaces, conf.Roles, conf.DisplayName)
return filterErrorForRetry(lastErr)
})

Expand All @@ -121,10 +78,11 @@ func prepareHost(root string, api *mackerel.API, roleFullnames []string, checks
return filterErrorForRetry(lastErr)
})
if lastErr != nil {
return nil, fmt.Errorf("Failed to find this host on mackerel (You may want to delete file \"%s\" to register this host to an another organization): %s", idFilePath(root), lastErr.Error())
return nil, fmt.Errorf("Failed to find this host on mackerel (You may want to delete file \"%s\" to register this host to an another organization): %s", conf.HostIDFile(), lastErr.Error())
}
}

hostSt := conf.HostStatus.OnStart
if hostSt != "" && hostSt != result.Status {
doRetry(func() error {
lastErr = api.UpdateHostStatus(result.ID, hostSt)
Expand All @@ -135,7 +93,7 @@ func prepareHost(root string, api *mackerel.API, roleFullnames []string, checks
}
}

lastErr = saveHostID(root, result.ID)
lastErr = conf.SaveHostID(result.ID)
if lastErr != nil {
return nil, fmt.Errorf("Failed to save host ID: %s", lastErr.Error())
}
Expand Down Expand Up @@ -520,7 +478,7 @@ func Prepare(conf *config.Config) (*Context, error) {
return nil, fmt.Errorf("Failed to prepare an api: %s", err.Error())
}

host, err := prepareHost(conf.Root, api, conf.Roles, conf.CheckNames(), conf.DisplayName, conf.HostStatus.OnStart)
host, err := prepareHost(conf, api)
if err != nil {
return nil, fmt.Errorf("Failed to prepare host: %s", err.Error())
}
Expand Down
2 changes: 1 addition & 1 deletion command/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func TestPrepareWithUpdate(t *testing.T) {
defer ts.Close()
tempDir, _ := ioutil.TempDir("", "")
conf.Root = tempDir
saveHostID(tempDir, "xxx12345678901")
conf.SaveHostID("xxx12345678901")

mockHandlers["PUT /api/v0/hosts/xxx12345678901"] = func(req *http.Request) (int, jsonObject) {
return 200, jsonObject{
Expand Down
43 changes: 43 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package config

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

"github.com/BurntSushi/toml"
Expand Down Expand Up @@ -209,3 +212,43 @@ func includeConfigFile(config *Config, include string) error {

return nil
}

const idFileName = "id"

func (c Config) HostIDFile() string {
return filepath.Join(c.Root, idFileName)
}

// LoadHostID loads the HostID of the host where the agent is running on.
// The HostID is chosen and given by Mackerel on host registration.
func (c Config) LoadHostID() (string, error) {
content, err := ioutil.ReadFile(c.HostIDFile())
if err != nil {
return "", err
}
return strings.TrimRight(string(content), "\r\n"), nil
}

func (c Config) SaveHostID(id string) error {
err := os.MkdirAll(c.Root, 0755)
if err != nil {
return err
}

file, err := os.Create(c.HostIDFile())
if err != nil {
return err
}
defer file.Close()

_, err = file.Write([]byte(id))
if err != nil {
return err
}

return nil
}

func (c Config) DeleteSavedHostID() error {
return os.Remove(c.HostIDFile())
}
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func doRetire(argv []string) int {
return exitStatusError
}

hostID, err := command.LoadHostID(conf.Root)
hostID, err := conf.LoadHostID()
if err != nil {
logger.Warningf("HostID file is not found")
return exitStatusError
Expand All @@ -130,7 +130,7 @@ func doRetire(argv []string) int {
}
logger.Infof("This host (hostID: %s) has been retired.", hostID)
// just to try to remove hostID file.
err = command.RemoveIDFile(conf.Root)
err = conf.DeleteSavedHostID()
if err != nil {
logger.Warningf("Failed to remove HostID file: %s", err)
}
Expand Down

0 comments on commit 2dc5489

Please sign in to comment.