in internal/beatcmd/beat.go [202:261]
func (b *Beat) loadMeta(metaPath string) error {
type meta struct {
UUID uuid.UUID `json:"uuid"`
FirstStart time.Time `json:"first_start"`
}
b.Info.Logger.Debugf("beat", "Beat metadata path: %v", metaPath)
f, err := openRegular(metaPath)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("meta file failed to open: %w", err)
}
if err == nil {
var m meta
if err := json.NewDecoder(f).Decode(&m); err != nil && err != io.EOF {
f.Close()
return fmt.Errorf("Beat meta file reading error: %w", err)
}
f.Close()
b.Info.FirstStart = m.FirstStart
b.Info.ID = m.UUID
}
rewrite := false
if b.Info.FirstStart.IsZero() {
b.Info.FirstStart = b.Info.StartTime
rewrite = true
}
if b.Info.ID == uuid.Nil {
id, err := uuid.NewV4()
if err != nil {
return err
}
b.Info.ID = id
rewrite = true
}
if !rewrite {
return nil
}
// meta.json does not exist, or the contents are invalid: write a new file.
//
// Write a temporary file, and then atomically move it into place in case
// of errors occurring half way through.
encodedMeta, err := json.Marshal(meta{
UUID: b.Info.ID,
FirstStart: b.Info.FirstStart,
})
if err != nil {
return fmt.Errorf("failed to encode metadata: %w", err)
}
tempFile := metaPath + ".new"
if err := os.WriteFile(tempFile, encodedMeta, 0600); err != nil {
return fmt.Errorf("failed to write metadata: %w", err)
}
// move temporary file into final location
return file.SafeFileRotate(metaPath, tempFile)
}