load.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. }
  77. return nil
  78. }
  79. func handle(conf map[string]interface{}, keysLeft []string, val string) {
  80. key := getConfigKey(keysLeft[0])
  81. if len(keysLeft) == 1 {
  82. conf[key] = getValueType(val)
  83. } else if len(keysLeft) >= 2 {
  84. if v, ok := conf[key]; ok {
  85. if casted, castSuccess := v.(map[string]interface{}); castSuccess {
  86. handle(casted, keysLeft[1:], val)
  87. } else {
  88. panic("not expected type")
  89. }
  90. } else {
  91. next := make(map[string]interface{})
  92. conf[key] = next
  93. handle(next, keysLeft[1:], val)
  94. }
  95. }
  96. }
  97. func trimPrefix(key string) string {
  98. p := fmt.Sprintf("%s%s", Prefix, Separator)
  99. return strings.TrimPrefix(key, p)
  100. }
  101. func nameToKeys(key string) []string {
  102. return strings.Split(strings.ToLower(key), Separator)
  103. }
  104. func getConfigKey(key string) string {
  105. return strings.ToLower(key)
  106. }
  107. func getValueType(val string) interface{} {
  108. val = strings.Trim(val, " ")
  109. if strings.HasPrefix(val, "[") && strings.HasSuffix(val, "]") {
  110. val = strings.ReplaceAll(val, "[", "")
  111. val = strings.ReplaceAll(val, "]", "")
  112. vals := strings.Split(val, ",")
  113. var ret []interface{}
  114. for _, v := range vals {
  115. if i, err := strconv.ParseInt(v, 10, 64); err == nil {
  116. ret = append(ret, i)
  117. } else if b, err := strconv.ParseBool(v); err == nil {
  118. ret = append(ret, b)
  119. } else if f, err := strconv.ParseFloat(v, 64); err == nil {
  120. ret = append(ret, f)
  121. } else {
  122. ret = append(ret, v)
  123. }
  124. }
  125. return ret
  126. } else if i, err := strconv.ParseInt(val, 10, 64); err == nil {
  127. return i
  128. } else if b, err := strconv.ParseBool(val); err == nil {
  129. return b
  130. } else if f, err := strconv.ParseFloat(val, 64); err == nil {
  131. return f
  132. }
  133. return val
  134. }
  135. func normalize(m map[string]interface{}) map[string]interface{} {
  136. res := make(map[string]interface{})
  137. for k, v := range m {
  138. lowered := strings.ToLower(k)
  139. if casted, success := v.(map[string]interface{}); success {
  140. node := normalize(casted)
  141. res[lowered] = node
  142. } else {
  143. res[lowered] = v
  144. }
  145. }
  146. return res
  147. }
  148. func applyKeys(m map[string]interface{}, list []string) {
  149. for _, k := range list {
  150. applyKey(m, k)
  151. }
  152. }
  153. func applyKey(m map[string]interface{}, key string) {
  154. for k, v := range m {
  155. if casted, ok := v.(map[string]interface{}); ok {
  156. applyKey(casted, key)
  157. }
  158. if key != k && strings.ToLower(key) == k {
  159. m[key] = v
  160. delete(m, k)
  161. }
  162. }
  163. }
  164. func extractKeysFromJsonIfExists(yamlPath string) ([]string, error) {
  165. jsonFilePath := jsonPathForFile(yamlPath)
  166. _, err := os.Stat(jsonFilePath)
  167. if err != nil {
  168. if errors.Is(err, os.ErrNotExist) {
  169. return make([]string, 0), nil
  170. } else {
  171. return nil, err
  172. }
  173. }
  174. m, err := loadJsonForYaml(jsonFilePath)
  175. if err != nil {
  176. return nil, err
  177. }
  178. return extractNamesFromProperties(m)
  179. }
  180. func loadJsonForYaml(filePath string) (map[string]interface{}, error) {
  181. data, err := ioutil.ReadFile(filePath)
  182. if err != nil {
  183. return nil, err
  184. }
  185. m := make(map[string]interface{})
  186. err = json.Unmarshal(data, &m)
  187. if err != nil {
  188. return nil, err
  189. }
  190. return m, nil
  191. }
  192. func jsonPathForFile(yamlPath string) string {
  193. p := strings.TrimSuffix(yamlPath, filepath.Ext(yamlPath))
  194. return fmt.Sprintf("%s.json", p)
  195. }
  196. func extractNamesFromProperties(jsonMap map[string]interface{}) ([]string, error) {
  197. result := make([]string, 0)
  198. properties, contains := jsonMap["properties"]
  199. if !contains {
  200. return nil, fmt.Errorf("json map does not have properties value")
  201. }
  202. if propertiesAsMap, success := properties.(map[string]interface{}); success {
  203. list := propertiesAsMap["default"]
  204. if interfaceList, isList := list.([]interface{}); isList {
  205. for _, element := range interfaceList {
  206. if m, isMap := element.(map[string]interface{}); isMap {
  207. n := m["name"]
  208. if s, isString := n.(string); isString {
  209. result = append(result, s)
  210. }
  211. }
  212. }
  213. }
  214. } else {
  215. return nil, fmt.Errorf("failed to cast to list of properties")
  216. }
  217. return result, nil
  218. }