config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. package nebula
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "os/signal"
  9. "path/filepath"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "syscall"
  15. "time"
  16. "github.com/imdario/mergo"
  17. "github.com/sirupsen/logrus"
  18. "gopkg.in/yaml.v2"
  19. )
  20. type Config struct {
  21. path string
  22. files []string
  23. Settings map[interface{}]interface{}
  24. oldSettings map[interface{}]interface{}
  25. callbacks []func(*Config)
  26. }
  27. func NewConfig() *Config {
  28. return &Config{
  29. Settings: make(map[interface{}]interface{}),
  30. }
  31. }
  32. // Load will find all yaml files within path and load them in lexical order
  33. func (c *Config) Load(path string) error {
  34. c.path = path
  35. c.files = make([]string, 0)
  36. err := c.resolve(path, true)
  37. if err != nil {
  38. return err
  39. }
  40. if len(c.files) == 0 {
  41. return fmt.Errorf("no config files found at %s", path)
  42. }
  43. sort.Strings(c.files)
  44. err = c.parse()
  45. if err != nil {
  46. return err
  47. }
  48. return nil
  49. }
  50. func (c *Config) LoadString(raw string) error {
  51. if raw == "" {
  52. return errors.New("Empty configuration")
  53. }
  54. return c.parseRaw([]byte(raw))
  55. }
  56. // RegisterReloadCallback stores a function to be called when a config reload is triggered. The functions registered
  57. // here should decide if they need to make a change to the current process before making the change. HasChanged can be
  58. // used to help decide if a change is necessary.
  59. // These functions should return quickly or spawn their own go routine if they will take a while
  60. func (c *Config) RegisterReloadCallback(f func(*Config)) {
  61. c.callbacks = append(c.callbacks, f)
  62. }
  63. // HasChanged checks if the underlying structure of the provided key has changed after a config reload. The value of
  64. // k in both the old and new settings will be serialized, the result of the string comparison is returned.
  65. // If k is an empty string the entire config is tested.
  66. // It's important to note that this is very rudimentary and susceptible to configuration ordering issues indicating
  67. // there is change when there actually wasn't any.
  68. func (c *Config) HasChanged(k string) bool {
  69. if c.oldSettings == nil {
  70. return false
  71. }
  72. var (
  73. nv interface{}
  74. ov interface{}
  75. )
  76. if k == "" {
  77. nv = c.Settings
  78. ov = c.oldSettings
  79. k = "all settings"
  80. } else {
  81. nv = c.get(k, c.Settings)
  82. ov = c.get(k, c.oldSettings)
  83. }
  84. newVals, err := yaml.Marshal(nv)
  85. if err != nil {
  86. l.WithField("config_path", k).WithError(err).Error("Error while marshaling new config")
  87. }
  88. oldVals, err := yaml.Marshal(ov)
  89. if err != nil {
  90. l.WithField("config_path", k).WithError(err).Error("Error while marshaling old config")
  91. }
  92. return string(newVals) != string(oldVals)
  93. }
  94. // CatchHUP will listen for the HUP signal in a go routine and reload all configs found in the
  95. // original path provided to Load. The old settings are shallow copied for change detection after the reload.
  96. func (c *Config) CatchHUP() {
  97. ch := make(chan os.Signal, 1)
  98. signal.Notify(ch, syscall.SIGHUP)
  99. go func() {
  100. for range ch {
  101. l.Info("Caught HUP, reloading config")
  102. c.ReloadConfig()
  103. }
  104. }()
  105. }
  106. func (c *Config) ReloadConfig() {
  107. c.oldSettings = make(map[interface{}]interface{})
  108. for k, v := range c.Settings {
  109. c.oldSettings[k] = v
  110. }
  111. err := c.Load(c.path)
  112. if err != nil {
  113. l.WithField("config_path", c.path).WithError(err).Error("Error occurred while reloading config")
  114. return
  115. }
  116. for _, v := range c.callbacks {
  117. v(c)
  118. }
  119. }
  120. // GetString will get the string for k or return the default d if not found or invalid
  121. func (c *Config) GetString(k, d string) string {
  122. r := c.Get(k)
  123. if r == nil {
  124. return d
  125. }
  126. return fmt.Sprintf("%v", r)
  127. }
  128. // GetStringSlice will get the slice of strings for k or return the default d if not found or invalid
  129. func (c *Config) GetStringSlice(k string, d []string) []string {
  130. r := c.Get(k)
  131. if r == nil {
  132. return d
  133. }
  134. rv, ok := r.([]interface{})
  135. if !ok {
  136. return d
  137. }
  138. v := make([]string, len(rv))
  139. for i := 0; i < len(v); i++ {
  140. v[i] = fmt.Sprintf("%v", rv[i])
  141. }
  142. return v
  143. }
  144. // GetMap will get the map for k or return the default d if not found or invalid
  145. func (c *Config) GetMap(k string, d map[interface{}]interface{}) map[interface{}]interface{} {
  146. r := c.Get(k)
  147. if r == nil {
  148. return d
  149. }
  150. v, ok := r.(map[interface{}]interface{})
  151. if !ok {
  152. return d
  153. }
  154. return v
  155. }
  156. // GetInt will get the int for k or return the default d if not found or invalid
  157. func (c *Config) GetInt(k string, d int) int {
  158. r := c.GetString(k, strconv.Itoa(d))
  159. v, err := strconv.Atoi(r)
  160. if err != nil {
  161. return d
  162. }
  163. return v
  164. }
  165. // GetBool will get the bool for k or return the default d if not found or invalid
  166. func (c *Config) GetBool(k string, d bool) bool {
  167. r := strings.ToLower(c.GetString(k, fmt.Sprintf("%v", d)))
  168. v, err := strconv.ParseBool(r)
  169. if err != nil {
  170. switch r {
  171. case "y", "yes":
  172. return true
  173. case "n", "no":
  174. return false
  175. }
  176. return d
  177. }
  178. return v
  179. }
  180. // GetDuration will get the duration for k or return the default d if not found or invalid
  181. func (c *Config) GetDuration(k string, d time.Duration) time.Duration {
  182. r := c.GetString(k, "")
  183. v, err := time.ParseDuration(r)
  184. if err != nil {
  185. return d
  186. }
  187. return v
  188. }
  189. func (c *Config) GetAllowList(k string, allowInterfaces bool) (*AllowList, error) {
  190. r := c.Get(k)
  191. if r == nil {
  192. return nil, nil
  193. }
  194. rawMap, ok := r.(map[interface{}]interface{})
  195. if !ok {
  196. return nil, fmt.Errorf("config `%s` has invalid type: %T", k, r)
  197. }
  198. tree := NewCIDRTree()
  199. var nameRules []AllowListNameRule
  200. firstValue := true
  201. allValuesMatch := true
  202. defaultSet := false
  203. var allValues bool
  204. for rawKey, rawValue := range rawMap {
  205. rawCIDR, ok := rawKey.(string)
  206. if !ok {
  207. return nil, fmt.Errorf("config `%s` has invalid key (type %T): %v", k, rawKey, rawKey)
  208. }
  209. // Special rule for interface names
  210. if rawCIDR == "interfaces" {
  211. if !allowInterfaces {
  212. return nil, fmt.Errorf("config `%s` does not support `interfaces`", k)
  213. }
  214. var err error
  215. nameRules, err = c.getAllowListInterfaces(k, rawValue)
  216. if err != nil {
  217. return nil, err
  218. }
  219. continue
  220. }
  221. value, ok := rawValue.(bool)
  222. if !ok {
  223. return nil, fmt.Errorf("config `%s` has invalid value (type %T): %v", k, rawValue, rawValue)
  224. }
  225. _, cidr, err := net.ParseCIDR(rawCIDR)
  226. if err != nil {
  227. return nil, fmt.Errorf("config `%s` has invalid CIDR: %s", k, rawCIDR)
  228. }
  229. // TODO: should we error on duplicate CIDRs in the config?
  230. tree.AddCIDR(cidr, value)
  231. if firstValue {
  232. allValues = value
  233. firstValue = false
  234. } else {
  235. if value != allValues {
  236. allValuesMatch = false
  237. }
  238. }
  239. // Check if this is 0.0.0.0/0
  240. bits, size := cidr.Mask.Size()
  241. if bits == 0 && size == 32 {
  242. defaultSet = true
  243. }
  244. }
  245. if !defaultSet {
  246. if allValuesMatch {
  247. _, zeroCIDR, _ := net.ParseCIDR("0.0.0.0/0")
  248. tree.AddCIDR(zeroCIDR, !allValues)
  249. } else {
  250. return nil, fmt.Errorf("config `%s` contains both true and false rules, but no default set for 0.0.0.0/0", k)
  251. }
  252. }
  253. return &AllowList{cidrTree: tree, nameRules: nameRules}, nil
  254. }
  255. func (c *Config) getAllowListInterfaces(k string, v interface{}) ([]AllowListNameRule, error) {
  256. var nameRules []AllowListNameRule
  257. rawRules, ok := v.(map[interface{}]interface{})
  258. if !ok {
  259. return nil, fmt.Errorf("config `%s.interfaces` is invalid (type %T): %v", k, v, v)
  260. }
  261. firstEntry := true
  262. var allValues bool
  263. for rawName, rawAllow := range rawRules {
  264. name, ok := rawName.(string)
  265. if !ok {
  266. return nil, fmt.Errorf("config `%s.interfaces` has invalid key (type %T): %v", k, rawName, rawName)
  267. }
  268. allow, ok := rawAllow.(bool)
  269. if !ok {
  270. return nil, fmt.Errorf("config `%s.interfaces` has invalid value (type %T): %v", k, rawAllow, rawAllow)
  271. }
  272. nameRE, err := regexp.Compile("^" + name + "$")
  273. if err != nil {
  274. return nil, fmt.Errorf("config `%s.interfaces` has invalid key: %s: %v", k, name, err)
  275. }
  276. nameRules = append(nameRules, AllowListNameRule{
  277. Name: nameRE,
  278. Allow: allow,
  279. })
  280. if firstEntry {
  281. allValues = allow
  282. firstEntry = false
  283. } else {
  284. if allow != allValues {
  285. return nil, fmt.Errorf("config `%s.interfaces` values must all be the same true/false value", k)
  286. }
  287. }
  288. }
  289. return nameRules, nil
  290. }
  291. func (c *Config) Get(k string) interface{} {
  292. return c.get(k, c.Settings)
  293. }
  294. func (c *Config) IsSet(k string) bool {
  295. return c.get(k, c.Settings) != nil
  296. }
  297. func (c *Config) get(k string, v interface{}) interface{} {
  298. parts := strings.Split(k, ".")
  299. for _, p := range parts {
  300. m, ok := v.(map[interface{}]interface{})
  301. if !ok {
  302. return nil
  303. }
  304. v, ok = m[p]
  305. if !ok {
  306. return nil
  307. }
  308. }
  309. return v
  310. }
  311. // direct signifies if this is the config path directly specified by the user,
  312. // versus a file/dir found by recursing into that path
  313. func (c *Config) resolve(path string, direct bool) error {
  314. i, err := os.Stat(path)
  315. if err != nil {
  316. return nil
  317. }
  318. if !i.IsDir() {
  319. c.addFile(path, direct)
  320. return nil
  321. }
  322. paths, err := readDirNames(path)
  323. if err != nil {
  324. return fmt.Errorf("problem while reading directory %s: %s", path, err)
  325. }
  326. for _, p := range paths {
  327. err := c.resolve(filepath.Join(path, p), false)
  328. if err != nil {
  329. return err
  330. }
  331. }
  332. return nil
  333. }
  334. func (c *Config) addFile(path string, direct bool) error {
  335. ext := filepath.Ext(path)
  336. if !direct && ext != ".yaml" && ext != ".yml" {
  337. return nil
  338. }
  339. ap, err := filepath.Abs(path)
  340. if err != nil {
  341. return err
  342. }
  343. c.files = append(c.files, ap)
  344. return nil
  345. }
  346. func (c *Config) parseRaw(b []byte) error {
  347. var m map[interface{}]interface{}
  348. err := yaml.Unmarshal(b, &m)
  349. if err != nil {
  350. return err
  351. }
  352. c.Settings = m
  353. return nil
  354. }
  355. func (c *Config) parse() error {
  356. var m map[interface{}]interface{}
  357. for _, path := range c.files {
  358. b, err := ioutil.ReadFile(path)
  359. if err != nil {
  360. return err
  361. }
  362. var nm map[interface{}]interface{}
  363. err = yaml.Unmarshal(b, &nm)
  364. if err != nil {
  365. return err
  366. }
  367. // We need to use WithAppendSlice so that firewall rules in separate
  368. // files are appended together
  369. err = mergo.Merge(&nm, m, mergo.WithAppendSlice)
  370. m = nm
  371. if err != nil {
  372. return err
  373. }
  374. }
  375. c.Settings = m
  376. return nil
  377. }
  378. func readDirNames(path string) ([]string, error) {
  379. f, err := os.Open(path)
  380. if err != nil {
  381. return nil, err
  382. }
  383. paths, err := f.Readdirnames(-1)
  384. f.Close()
  385. if err != nil {
  386. return nil, err
  387. }
  388. sort.Strings(paths)
  389. return paths, nil
  390. }
  391. func configLogger(c *Config) error {
  392. // set up our logging level
  393. logLevel, err := logrus.ParseLevel(strings.ToLower(c.GetString("logging.level", "info")))
  394. if err != nil {
  395. return fmt.Errorf("%s; possible levels: %s", err, logrus.AllLevels)
  396. }
  397. l.SetLevel(logLevel)
  398. disableTimestamp := c.GetBool("logging.disable_timestamp", false)
  399. timestampFormat := c.GetString("logging.timestamp_format", "")
  400. fullTimestamp := (timestampFormat != "")
  401. if timestampFormat == "" {
  402. timestampFormat = time.RFC3339
  403. }
  404. logFormat := strings.ToLower(c.GetString("logging.format", "text"))
  405. switch logFormat {
  406. case "text":
  407. l.Formatter = &logrus.TextFormatter{
  408. TimestampFormat: timestampFormat,
  409. FullTimestamp: fullTimestamp,
  410. DisableTimestamp: disableTimestamp,
  411. }
  412. case "json":
  413. l.Formatter = &logrus.JSONFormatter{
  414. TimestampFormat: timestampFormat,
  415. DisableTimestamp: disableTimestamp,
  416. }
  417. default:
  418. return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
  419. }
  420. return nil
  421. }