config.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. )
  8. func parseInfo(path string) *Info {
  9. file, err := os.Open(path)
  10. if err != nil {
  11. return nil
  12. }
  13. defer file.Close()
  14. info := &Info{}
  15. content, err := ioutil.ReadAll(file)
  16. if err != nil {
  17. fatalf("Unable to read info: %v", err)
  18. return nil
  19. }
  20. if err = json.Unmarshal(content, &info); err != nil {
  21. fatalf("Unable to parse info: %v", err)
  22. return nil
  23. }
  24. return info
  25. }
  26. // Get the server info from previous conf file
  27. // or from the user
  28. func getInfo(path string) *Info {
  29. // Read in the server info if available.
  30. infoPath := filepath.Join(path, "info")
  31. // Delete the old configuration if exist
  32. if force {
  33. logPath := filepath.Join(path, "log")
  34. confPath := filepath.Join(path, "conf")
  35. snapshotPath := filepath.Join(path, "snapshot")
  36. os.Remove(infoPath)
  37. os.Remove(logPath)
  38. os.Remove(confPath)
  39. os.RemoveAll(snapshotPath)
  40. }
  41. info := parseInfo(infoPath)
  42. if info != nil {
  43. infof("Found node configuration in '%s'. Ignoring flags", infoPath)
  44. return info
  45. }
  46. info = &argInfo
  47. // Write to file.
  48. content, _ := json.MarshalIndent(info, "", " ")
  49. content = []byte(string(content) + "\n")
  50. if err := ioutil.WriteFile(infoPath, content, 0644); err != nil {
  51. fatalf("Unable to write info to file: %v", err)
  52. }
  53. infof("Wrote node configuration to '%s'", infoPath)
  54. return info
  55. }