load.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. func LoadConfig(c interface{}) error {
  30. return LoadConfigByName(ConfFileName, c)
  31. }
  32. func LoadConfigByName(name string, c interface{}) error {
  33. dir, err := GetConfLoc()
  34. if err != nil {
  35. return err
  36. }
  37. p := path.Join(dir, name)
  38. return LoadConfigFromPath(p, c)
  39. }
  40. func LoadConfigFromPath(p string, c interface{}) error {
  41. prefix := getPrefix(p)
  42. b, err := ioutil.ReadFile(p)
  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. err = process(configs, os.Environ(), prefix)
  53. if err != nil {
  54. return err
  55. }
  56. if _, success := c.(*map[string]interface{}); success {
  57. names, err := extractKeysFromJsonIfExists(p)
  58. if err != nil {
  59. return err
  60. }
  61. applyKeys(configs, names)
  62. }
  63. return mapstructure.Decode(configs, c)
  64. }
  65. func getPrefix(p string) string {
  66. _, file := path.Split(p)
  67. return strings.ToUpper(strings.TrimSuffix(file, filepath.Ext(file)))
  68. }
  69. func process(configMap map[string]interface{}, variables []string, prefix string) error {
  70. for _, e := range variables {
  71. if !strings.HasPrefix(e, prefix) {
  72. continue
  73. }
  74. pair := strings.SplitN(e, "=", 2)
  75. if len(pair) != 2 {
  76. return fmt.Errorf("wrong format of variable")
  77. }
  78. keys := nameToKeys(trimPrefix(pair[0], prefix))
  79. handle(configMap, keys, pair[1])
  80. printableK := strings.Join(keys, ".")
  81. printableV := pair[1]
  82. if strings.Contains(strings.ToLower(printableK), "password") {
  83. printableV = "*"
  84. }
  85. Log.Infof("Set config '%s.%s' to '%s' by environment variable", strings.ToLower(prefix), printableK, printableV)
  86. }
  87. return nil
  88. }
  89. func handle(conf map[string]interface{}, keysLeft []string, val string) {
  90. key := getConfigKey(keysLeft[0])
  91. if len(keysLeft) == 1 {
  92. conf[key] = getValueType(val)
  93. } else if len(keysLeft) >= 2 {
  94. if v, ok := conf[key]; ok {
  95. if casted, castSuccess := v.(map[string]interface{}); castSuccess {
  96. handle(casted, keysLeft[1:], val)
  97. } else {
  98. panic("not expected type")
  99. }
  100. } else {
  101. next := make(map[string]interface{})
  102. conf[key] = next
  103. handle(next, keysLeft[1:], val)
  104. }
  105. }
  106. }
  107. func trimPrefix(key string, prefix string) string {
  108. p := fmt.Sprintf("%s%s", prefix, Separator)
  109. return strings.TrimPrefix(key, p)
  110. }
  111. func nameToKeys(key string) []string {
  112. return strings.Split(strings.ToLower(key), Separator)
  113. }
  114. func getConfigKey(key string) string {
  115. return strings.ToLower(key)
  116. }
  117. func getValueType(val string) interface{} {
  118. val = strings.Trim(val, " ")
  119. if strings.HasPrefix(val, "[") && strings.HasSuffix(val, "]") {
  120. val = strings.ReplaceAll(val, "[", "")
  121. val = strings.ReplaceAll(val, "]", "")
  122. vals := strings.Split(val, ",")
  123. var ret []interface{}
  124. for _, v := range vals {
  125. if i, err := strconv.ParseInt(v, 10, 64); err == nil {
  126. ret = append(ret, i)
  127. } else if b, err := strconv.ParseBool(v); err == nil {
  128. ret = append(ret, b)
  129. } else if f, err := strconv.ParseFloat(v, 64); err == nil {
  130. ret = append(ret, f)
  131. } else {
  132. ret = append(ret, v)
  133. }
  134. }
  135. return ret
  136. } else if i, err := strconv.ParseInt(val, 10, 64); err == nil {
  137. return i
  138. } else if b, err := strconv.ParseBool(val); err == nil {
  139. return b
  140. } else if f, err := strconv.ParseFloat(val, 64); err == nil {
  141. return f
  142. }
  143. return val
  144. }
  145. func normalize(m map[string]interface{}) map[string]interface{} {
  146. res := make(map[string]interface{})
  147. for k, v := range m {
  148. lowered := strings.ToLower(k)
  149. if casted, success := v.(map[string]interface{}); success {
  150. node := normalize(casted)
  151. res[lowered] = node
  152. } else {
  153. res[lowered] = v
  154. }
  155. }
  156. return res
  157. }
  158. func applyKeys(m map[string]interface{}, list []string) {
  159. for _, k := range list {
  160. applyKey(m, k)
  161. }
  162. }
  163. func applyKey(m map[string]interface{}, key string) {
  164. for k, v := range m {
  165. if casted, ok := v.(map[string]interface{}); ok {
  166. applyKey(casted, key)
  167. }
  168. if key != k && strings.ToLower(key) == k {
  169. m[key] = v
  170. delete(m, k)
  171. }
  172. }
  173. }
  174. func extractKeysFromJsonIfExists(yamlPath string) ([]string, error) {
  175. jsonFilePath := jsonPathForFile(yamlPath)
  176. _, err := os.Stat(jsonFilePath)
  177. if err != nil {
  178. if errors.Is(err, os.ErrNotExist) {
  179. return make([]string, 0), nil
  180. } else {
  181. return nil, err
  182. }
  183. }
  184. m, err := loadJsonForYaml(jsonFilePath)
  185. if err != nil {
  186. return nil, err
  187. }
  188. return extractNamesFromProperties(m)
  189. }
  190. func loadJsonForYaml(filePath string) (map[string]interface{}, error) {
  191. data, err := ioutil.ReadFile(filePath)
  192. if err != nil {
  193. return nil, err
  194. }
  195. m := make(map[string]interface{})
  196. err = json.Unmarshal(data, &m)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return m, nil
  201. }
  202. func jsonPathForFile(yamlPath string) string {
  203. p := strings.TrimSuffix(yamlPath, filepath.Ext(yamlPath))
  204. return fmt.Sprintf("%s.json", p)
  205. }
  206. func extractNamesFromProperties(jsonMap map[string]interface{}) ([]string, error) {
  207. result := make([]string, 0)
  208. properties, contains := jsonMap["properties"]
  209. if !contains {
  210. return nil, fmt.Errorf("json map does not have properties value")
  211. }
  212. if propertiesAsMap, success := properties.(map[string]interface{}); success {
  213. list := propertiesAsMap["default"]
  214. if interfaceList, isList := list.([]interface{}); isList {
  215. for _, element := range interfaceList {
  216. if m, isMap := element.(map[string]interface{}); isMap {
  217. n := m["name"]
  218. if s, isString := n.(string); isString {
  219. result = append(result, s)
  220. }
  221. }
  222. }
  223. }
  224. } else {
  225. return nil, fmt.Errorf("failed to cast to list of properties")
  226. }
  227. return result, nil
  228. }