Skip to content

Commit

Permalink
Log error if node-id file can not be written
Browse files Browse the repository at this point in the history
  • Loading branch information
thll committed Apr 5, 2022
1 parent ffa05b3 commit 40a88e1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 11 deletions.
31 changes: 20 additions & 11 deletions common/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,17 +80,7 @@ func GetCollectorId(collectorId string) string {
id := collectorId
if strings.HasPrefix(collectorId, "file:") {
filePath := strings.SplitAfterN(collectorId, ":", 2)[1]
err := FileExists(filePath)
if err != nil {
log.Info("node-id file doesn't exist, generating a new one")
CreatePathToFile(filePath)
ioutil.WriteFile(filePath, []byte(RandomUuid()), 0644)
}
file, err := ioutil.ReadFile(filePath)
if err != nil {
log.Fatal("Can not read node-id file: ", err)
}
id = strings.Trim(string(file), " \n")
id = idFromFile(filePath)
}

if id != "" && !cfgfile.ValidateConfig() {
Expand All @@ -99,6 +89,25 @@ func GetCollectorId(collectorId string) string {
return id
}

func idFromFile(filePath string) string {
err := FileExists(filePath)
if err != nil {
log.Info("node-id file doesn't exist, generating a new one")
err = CreatePathToFile(filePath)
if err == nil {
err = ioutil.WriteFile(filePath, []byte(RandomUuid()), 0644)
log.Error("Can not write node-id file: ", err)
}
}

file, err := ioutil.ReadFile(filePath)
if err != nil {
log.Error("Can not read node-id file: ", err)
return ""
}
return strings.Trim(string(file), " \n")
}

func RandomUuid() string {
return uuid.NewRandom().String()
}
Expand Down
21 changes: 21 additions & 0 deletions common/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,27 @@ func TestGetCollectorIdFromNonExistingFile(t *testing.T) {
}
}

func TestCollectorIdFileNotWritable(t *testing.T) {
dir, err := ioutil.TempDir("", "test-node-id")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)

nodeIdDir := filepath.Join(dir, "non-writable")

err = os.MkdirAll(nodeIdDir, 0500)
if err != nil {
t.Fatal(err)
}

tmpfile := filepath.Join(nodeIdDir, "node-id")
result := GetCollectorId("file:/" + tmpfile)
if result != "" {
t.Fatalf("Unwritable node-id file should result in empty node-id")
}
}

func TestEncloseWithWithoutAction(t *testing.T) {
content := "/some regex/"
result := EncloseWith(content, "/")
Expand Down

0 comments on commit 40a88e1

Please sign in to comment.