a command line interface for elastic (work in progress)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.0 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package main
  2. import (
  3. "fmt"
  4. elastic "github.com/olivere/elastic/v7"
  5. toml "github.com/pelletier/go-toml"
  6. "io/ioutil"
  7. "os"
  8. )
  9. type ElasticConfig struct {
  10. Elastic ElasticSettings
  11. Servers map[string]ElasticServer
  12. }
  13. type ElasticSettings struct {
  14. DefaultServer string
  15. }
  16. type ElasticServer struct {
  17. URL string
  18. User string
  19. Pass string
  20. }
  21. func (ec *ElasticConfig) GetClient(name string) *elastic.Client {
  22. if name == "" {
  23. if ec.Elastic.DefaultServer == "" {
  24. fmt.Fprintf(os.Stderr, "no server name provided\n")
  25. os.Exit(1)
  26. }
  27. name = ec.Elastic.DefaultServer
  28. }
  29. if _, ok := ec.Servers[name]; !ok {
  30. fmt.Fprintf(os.Stderr, "no configuration found for server \"%s\"\n", name)
  31. os.Exit(1)
  32. }
  33. server := ec.Servers[name]
  34. opts := []elastic.ClientOptionFunc{
  35. elastic.SetURL(server.URL),
  36. elastic.SetSniff(false),
  37. elastic.SetGzip(true),
  38. }
  39. if server.User != "" && server.Pass != "" {
  40. opts = append(opts, elastic.SetBasicAuth(
  41. server.User, server.Pass,
  42. ))
  43. }
  44. es, err := elastic.NewClient(opts...)
  45. if err != nil {
  46. fmt.Fprintf(os.Stderr, "elastic connection error: %s\n", err.Error())
  47. os.Exit(1)
  48. }
  49. return es
  50. }
  51. func LoadConfig(cfgpath string) *ElasticConfig {
  52. cfg := ElasticConfig{}
  53. if cfgpath != "" {
  54. cfgfile, err := ioutil.ReadFile(cfgpath)
  55. if err != nil {
  56. fmt.Fprintf(os.Stderr, "read error: %s\n", err.Error())
  57. os.Exit(1)
  58. }
  59. err = toml.Unmarshal(cfgfile, &cfg)
  60. if err != nil {
  61. fmt.Fprintf(os.Stderr, "parse error: %s\n", err.Error())
  62. os.Exit(1)
  63. }
  64. return &cfg
  65. }
  66. paths := []string{}
  67. homedir, _ := os.UserHomeDir()
  68. if homedir != "" {
  69. paths = append(paths, homedir+"/.es.toml")
  70. }
  71. paths = append(paths, "/etc/es.toml")
  72. for _, path := range paths {
  73. cfgfile, err := ioutil.ReadFile(path)
  74. if err != nil {
  75. continue
  76. }
  77. err = toml.Unmarshal(cfgfile, &cfg)
  78. if err != nil {
  79. continue
  80. }
  81. return &cfg
  82. }
  83. fmt.Fprintf(os.Stderr, "no valid configuration found in:\n")
  84. for _, path := range paths {
  85. fmt.Fprintf(os.Stderr, " %s\n", path)
  86. }
  87. os.Exit(1)
  88. return nil
  89. }