load.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // INTECH Process Automation Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package conf
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "github.com/mitchellh/mapstructure"
  20. "gopkg.in/yaml.v3"
  21. "io/ioutil"
  22. "os"
  23. "path"
  24. "path/filepath"
  25. "strconv"
  26. "strings"
  27. )
  28. const Separator = "__"
  29. const Prefix = "KUIPER"
  30. func LoadConfig(c interface{}) error {
  31. return LoadConfigByName(ConfFileName, c)
  32. }
  33. func LoadConfigByName(name string, c interface{}) error {
  34. dir, err := GetConfLoc()
  35. if err != nil {
  36. return err
  37. }
  38. p := path.Join(dir, name)
  39. return LoadConfigFromPath(p, c)
  40. }
  41. func LoadConfigFromPath(path string, c interface{}) error {
  42. b, err := ioutil.ReadFile(path)
  43. if err != nil {
  44. return err
  45. }
  46. configMap := make(map[string]interface{})
  47. err = yaml.Unmarshal(b, &configMap)
  48. if err != nil {
  49. return err
  50. }
  51. configs := normalize(configMap)
  52. if _, success := c.(*map[string]interface{}); success {
  53. names, err := extractKeysFromJsonIfExists(path)
  54. if err != nil {
  55. return err
  56. }
  57. applyKeys(configs, names)
  58. }
  59. err = process(configs, os.Environ())
  60. if err != nil {
  61. return err
  62. }
  63. return mapstructure.Decode(configs, c)
  64. }
  65. func process(configMap map[string]interface{}, variables []string) error {
  66. for _, e := range variables {
  67. if !strings.HasPrefix(e, Prefix) {
  68. continue
  69. }
  70. pair := strings.SplitN(e, "=", 2)
  71. if len(pair) != 2 {
  72. return fmt.Errorf("wrong format of variable")
  73. }
  74. keys := nameToKeys(trimPrefix(pair[0]))
  75. handle(configMap, keys, pair[1])
  76. printableK := strings.Join(keys, ".")
  77. printableV := pair[1]
  78. if strings.Contains(strings.ToLower(printableK), "password") {
  79. printableV = "*"
  80. }
  81. Log.Infof("Set config '%s.%s' to '%s' by environment variable", Prefix, printableK, printableV)
  82. }
  83. return nil
  84. }
  85. func handle(conf map[string]interface{}, keysLeft []string, val string) {
  86. key := getConfigKey(keysLeft[0])
  87. if len(keysLeft) == 1 {
  88. conf[key] = getValueType(val)
  89. } else if len(keysLeft) >= 2 {
  90. if v, ok := conf[key]; ok {
  91. if casted, castSuccess := v.(map[string]interface{}); castSuccess {
  92. handle(casted, keysLeft[1:], val)
  93. } else {
  94. panic("not expected type")
  95. }
  96. } else {
  97. next := make(map[string]interface{})
  98. conf[key] = next
  99. handle(next, keysLeft[1:], val)
  100. }
  101. }
  102. }
  103. func trimPrefix(key string) string {
  104. p := fmt.Sprintf("%s%s", Prefix, Separator)
  105. return strings.TrimPrefix(key, p)
  106. }
  107. func nameToKeys(key string) []string {
  108. return strings.Split(strings.ToLower(key), Separator)
  109. }
  110. func getConfigKey(key string) string {
  111. return strings.ToLower(key)
  112. }
  113. func getValueType(val string) interface{} {
  114. val = strings.Trim(val, " ")
  115. if strings.HasPrefix(val, "[") && strings.HasSuffix(val, "]") {
  116. val = strings.ReplaceAll(val, "[", "")
  117. val = strings.ReplaceAll(val, "]", "")
  118. vals := strings.Split(val, ",")
  119. var ret []interface{}
  120. for _, v := range vals {
  121. if i, err := strconv.ParseInt(v, 10, 64); err == nil {
  122. ret = append(ret, i)
  123. } else if b, err := strconv.ParseBool(v); err == nil {
  124. ret = append(ret, b)
  125. } else if f, err := strconv.ParseFloat(v, 64); err == nil {
  126. ret = append(ret, f)
  127. } else {
  128. ret = append(ret, v)
  129. }
  130. }
  131. return ret
  132. } else if i, err := strconv.ParseInt(val, 10, 64); err == nil {
  133. return i
  134. } else if b, err := strconv.ParseBool(val); err == nil {
  135. return b
  136. } else if f, err := strconv.ParseFloat(val, 64); err == nil {
  137. return f
  138. }
  139. return val
  140. }
  141. func normalize(m map[string]interface{}) map[string]interface{} {
  142. res := make(map[string]interface{})
  143. for k, v := range m {
  144. lowered := strings.ToLower(k)
  145. if casted, success := v.(map[string]interface{}); success {
  146. node := normalize(casted)
  147. res[lowered] = node
  148. } else {
  149. res[lowered] = v
  150. }
  151. }
  152. return res
  153. }
  154. func applyKeys(m map[string]interface{}, list []string) {
  155. for _, k := range list {
  156. applyKey(m, k)
  157. }
  158. }
  159. func applyKey(m map[string]interface{}, key string) {
  160. for k, v := range m {
  161. if casted, ok := v.(map[string]interface{}); ok {
  162. applyKey(casted, key)
  163. }
  164. if key != k && strings.ToLower(key) == k {
  165. m[key] = v
  166. delete(m, k)
  167. }
  168. }
  169. }
  170. func extractKeysFromJsonIfExists(yamlPath string) ([]string, error) {
  171. jsonFilePath := jsonPathForFile(yamlPath)
  172. _, err := os.Stat(jsonFilePath)
  173. if err != nil {
  174. if errors.Is(err, os.ErrNotExist) {
  175. return make([]string, 0), nil
  176. } else {
  177. return nil, err
  178. }
  179. }
  180. m, err := loadJsonForYaml(jsonFilePath)
  181. if err != nil {
  182. return nil, err
  183. }
  184. return extractNamesFromProperties(m)
  185. }
  186. func loadJsonForYaml(filePath string) (map[string]interface{}, error) {
  187. data, err := ioutil.ReadFile(filePath)
  188. if err != nil {
  189. return nil, err
  190. }
  191. m := make(map[string]interface{})
  192. err = json.Unmarshal(data, &m)
  193. if err != nil {
  194. return nil, err
  195. }
  196. return m, nil
  197. }
  198. func jsonPathForFile(yamlPath string) string {
  199. p := strings.TrimSuffix(yamlPath, filepath.Ext(yamlPath))
  200. return fmt.Sprintf("%s.json", p)
  201. }
  202. func extractNamesFromProperties(jsonMap map[string]interface{}) ([]string, error) {
  203. result := make([]string, 0)
  204. properties, contains := jsonMap["properties"]
  205. if !contains {
  206. return nil, fmt.Errorf("json map does not have properties value")
  207. }
  208. if propertiesAsMap, success := properties.(map[string]interface{}); success {
  209. list := propertiesAsMap["default"]
  210. if interfaceList, isList := list.([]interface{}); isList {
  211. for _, element := range interfaceList {
  212. if m, isMap := element.(map[string]interface{}); isMap {
  213. n := m["name"]
  214. if s, isString := n.(string); isString {
  215. result = append(result, s)
  216. }
  217. }
  218. }
  219. }
  220. } else {
  221. return nil, fmt.Errorf("failed to cast to list of properties")
  222. }
  223. return result, nil
  224. }