client.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. package conf
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/hex"
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "io/ioutil"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "path"
  15. "strings"
  16. "sync/atomic"
  17. "time"
  18. "go-common/library/conf/env"
  19. "go-common/library/log"
  20. )
  21. const (
  22. // code
  23. _codeOk = 0
  24. _codeNotModified = -304
  25. // api
  26. _apiGet = "http://%s/v1/config/get2?%s"
  27. _apiCheck = "http://%s/v1/config/check?%s"
  28. // timeout
  29. _retryInterval = 1 * time.Second
  30. _httpTimeout = 60 * time.Second
  31. _unknownVersion = -1
  32. commonKey = "common.toml"
  33. )
  34. var (
  35. conf config
  36. )
  37. type version struct {
  38. Code int `json:"code"`
  39. Message string `json:"message"`
  40. Data *struct {
  41. Version int64 `json:"version"`
  42. } `json:"data"`
  43. }
  44. type result struct {
  45. Code int `json:"code"`
  46. Message string `json:"message"`
  47. Data *data `json:"data"`
  48. }
  49. type data struct {
  50. Version int64 `json:"version"`
  51. Content string `json:"content"`
  52. Md5 string `json:"md5"`
  53. }
  54. // Namespace the key-value config object.
  55. type Namespace struct {
  56. Name string `json:"name"`
  57. Data map[string]string `json:"data"`
  58. }
  59. type config struct {
  60. Svr string
  61. Ver string
  62. Path string
  63. Filename string
  64. Host string
  65. Addr string
  66. Env string
  67. Token string
  68. Appoint string
  69. // NOTE: new caster
  70. Region string
  71. Zone string
  72. AppID string
  73. DeployEnv string
  74. TreeID string
  75. }
  76. // Client is config client.
  77. type Client struct {
  78. ver int64 // NOTE: for config v1
  79. diff *ver // NOTE: for config v2
  80. customize string
  81. httpCli *http.Client
  82. data atomic.Value
  83. event chan string
  84. useV2 bool
  85. watchFile map[string]struct{}
  86. watchAll bool
  87. }
  88. func init() {
  89. // env
  90. conf.Svr = os.Getenv("CONF_APPID")
  91. conf.Ver = os.Getenv("CONF_VERSION")
  92. conf.Addr = os.Getenv("CONF_HOST")
  93. conf.Host = os.Getenv("CONF_HOSTNAME")
  94. conf.Path = os.Getenv("CONF_PATH")
  95. conf.Env = os.Getenv("CONF_ENV")
  96. conf.Token = os.Getenv("CONF_TOKEN")
  97. conf.Appoint = os.Getenv("CONF_APPOINT")
  98. conf.Region = os.Getenv("REGION")
  99. conf.Zone = os.Getenv("ZONE")
  100. conf.AppID = os.Getenv("APP_ID")
  101. conf.DeployEnv = os.Getenv("DEPLOY_ENV")
  102. conf.TreeID = os.Getenv("TREE_ID")
  103. // flags
  104. hostname, _ := os.Hostname()
  105. flag.StringVar(&conf.Svr, "conf_appid", conf.Svr, `app name.`)
  106. flag.StringVar(&conf.Ver, "conf_version", conf.Ver, `app version.`)
  107. flag.StringVar(&conf.Addr, "conf_host", conf.Addr, `config center api host.`)
  108. flag.StringVar(&conf.Host, "conf_hostname", hostname, `hostname.`)
  109. flag.StringVar(&conf.Path, "conf_path", conf.Path, `config file path.`)
  110. flag.StringVar(&conf.Env, "conf_env", conf.Env, `config Env.`)
  111. flag.StringVar(&conf.Token, "conf_token", conf.Token, `config Token.`)
  112. flag.StringVar(&conf.Appoint, "conf_appoint", conf.Appoint, `config Appoint.`)
  113. /*
  114. flag.StringVar(&conf.Region, "region", conf.Region, `region.`)
  115. flag.StringVar(&conf.Zone, "zone", conf.Zone, `zone.`)
  116. flag.StringVar(&conf.AppID, "app_id", conf.AppID, `app id.`)
  117. flag.StringVar(&conf.DeployEnv, "deploy_env", conf.DeployEnv, `deploy env.`)
  118. */
  119. conf.Region = env.Region
  120. conf.Zone = env.Zone
  121. conf.AppID = env.AppID
  122. conf.DeployEnv = env.DeployEnv
  123. // FIXME(linli) remove treeid
  124. flag.StringVar(&conf.TreeID, "tree_id", conf.TreeID, `tree id.`)
  125. }
  126. // New new a ugc config center client.
  127. func New() (cli *Client, err error) {
  128. cli = &Client{
  129. httpCli: &http.Client{Timeout: _httpTimeout},
  130. event: make(chan string, 10),
  131. }
  132. if conf.Svr != "" && conf.Host != "" && conf.Path != "" && conf.Addr != "" && conf.Ver != "" && conf.Env != "" && conf.Token != "" &&
  133. (strings.HasPrefix(conf.Ver, "shsb") || (strings.HasPrefix(conf.Ver, "shylf"))) {
  134. if err = cli.init(); err != nil {
  135. return nil, err
  136. }
  137. go cli.updateproc()
  138. return
  139. }
  140. if conf.Zone != "" && conf.AppID != "" && conf.Host != "" && conf.Path != "" && conf.Addr != "" && conf.Ver != "" && conf.DeployEnv != "" && conf.Token != "" {
  141. if err = cli.init2(); err != nil {
  142. return nil, err
  143. }
  144. go cli.updateproc2()
  145. cli.useV2 = true
  146. return
  147. }
  148. err = fmt.Errorf("at least one params is empty. app=%s, version=%s, hostname=%s, addr=%s, path=%s, Env=%s, Token =%s, DeployEnv=%s, TreeID=%s, appID=%s",
  149. conf.Svr, conf.Ver, conf.Host, conf.Addr, conf.Path, conf.Env, conf.Token, conf.DeployEnv, conf.TreeID, conf.AppID)
  150. return
  151. }
  152. // Path get confFile Path.
  153. func (c *Client) Path() string {
  154. return conf.Path
  155. }
  156. // Toml return config value.
  157. func (c *Client) Toml() (cf string, ok bool) {
  158. if c.useV2 {
  159. return c.Toml2()
  160. }
  161. var (
  162. m map[string]*Namespace
  163. n *Namespace
  164. )
  165. if m, ok = c.data.Load().(map[string]*Namespace); !ok {
  166. return
  167. }
  168. if n, ok = m[""]; !ok {
  169. return
  170. }
  171. cf, ok = n.Data[commonKey]
  172. return
  173. }
  174. // Value return config value.
  175. func (c *Client) Value(key string) (cf string, ok bool) {
  176. if c.useV2 {
  177. return c.Value2(key)
  178. }
  179. var (
  180. m map[string]*Namespace
  181. n *Namespace
  182. )
  183. if m, ok = c.data.Load().(map[string]*Namespace); !ok {
  184. return
  185. }
  186. if n, ok = m[""]; !ok {
  187. return
  188. }
  189. cf, ok = n.Data[key]
  190. return
  191. }
  192. // SetCustomize set customize value.
  193. func (c *Client) SetCustomize(value string) {
  194. c.customize = value
  195. }
  196. // Event client update event.
  197. func (c *Client) Event() <-chan string {
  198. return c.event
  199. }
  200. // Watch watch filename change.
  201. func (c *Client) Watch(filename ...string) {
  202. if c.watchFile == nil {
  203. c.watchFile = map[string]struct{}{}
  204. }
  205. for _, f := range filename {
  206. c.watchFile[f] = struct{}{}
  207. }
  208. }
  209. // WatchAll watch all filename change.
  210. func (c *Client) WatchAll() {
  211. c.watchAll = true
  212. }
  213. // checkLocal check local config is ok
  214. func (c *Client) init() (err error) {
  215. var ver int64
  216. if ver, err = c.checkVersion(_unknownVersion); err != nil {
  217. fmt.Printf("get remote version error(%v)\n", err)
  218. return
  219. }
  220. for i := 0; i < 3; i++ {
  221. if ver == _unknownVersion {
  222. fmt.Println("get null version")
  223. return
  224. }
  225. if err = c.download(ver); err == nil {
  226. return
  227. }
  228. fmt.Printf("retry times: %d, c.download() error(%v)\n", i, err)
  229. time.Sleep(_retryInterval)
  230. }
  231. return
  232. }
  233. func (c *Client) updateproc() (err error) {
  234. var ver int64
  235. for {
  236. time.Sleep(_retryInterval)
  237. if ver, err = c.checkVersion(c.ver); err != nil {
  238. log.Error("c.checkVersion(%d) error(%v)", c.ver, err)
  239. continue
  240. } else if ver == c.ver {
  241. continue
  242. }
  243. if err = c.download(ver); err != nil {
  244. log.Error("c.download() error(%s)", err)
  245. continue
  246. }
  247. c.event <- ""
  248. }
  249. }
  250. // download download config from config service
  251. func (c *Client) download(ver int64) (err error) {
  252. var data *data
  253. if data, err = c.getConfig(ver); err != nil {
  254. return
  255. }
  256. return c.update(data)
  257. }
  258. // poll config server
  259. func (c *Client) checkVersion(reqVer int64) (ver int64, err error) {
  260. var (
  261. url string
  262. req *http.Request
  263. resp *http.Response
  264. rb []byte
  265. )
  266. if url = c.makeURL(_apiCheck, reqVer); url == "" {
  267. err = fmt.Errorf("checkVersion() c.makeUrl() error url empty")
  268. return
  269. }
  270. // http
  271. if req, err = http.NewRequest("GET", url, nil); err != nil {
  272. return
  273. }
  274. if resp, err = c.httpCli.Do(req); err != nil {
  275. return
  276. }
  277. defer resp.Body.Close()
  278. if resp.StatusCode != http.StatusOK {
  279. err = fmt.Errorf("checkVersion() http error url(%s) status: %d", url, resp.StatusCode)
  280. return
  281. }
  282. // ok
  283. if rb, err = ioutil.ReadAll(resp.Body); err != nil {
  284. return
  285. }
  286. v := &version{}
  287. if err = json.Unmarshal(rb, v); err != nil {
  288. return
  289. }
  290. switch v.Code {
  291. case _codeOk:
  292. if v.Data == nil {
  293. err = fmt.Errorf("checkVersion() response error result: %v", v)
  294. return
  295. }
  296. ver = v.Data.Version
  297. case _codeNotModified:
  298. ver = reqVer
  299. default:
  300. err = fmt.Errorf("checkVersion() response error result: %v", v)
  301. }
  302. return
  303. }
  304. // updateVersion update config version
  305. func (c *Client) getConfig(ver int64) (data *data, err error) {
  306. var (
  307. url string
  308. req *http.Request
  309. resp *http.Response
  310. rb []byte
  311. res = &result{}
  312. )
  313. if url = c.makeURL(_apiGet, ver); url == "" {
  314. err = fmt.Errorf("getConfig() c.makeUrl() error url empty")
  315. return
  316. }
  317. // http
  318. if req, err = http.NewRequest("GET", url, nil); err != nil {
  319. return
  320. }
  321. if resp, err = c.httpCli.Do(req); err != nil {
  322. return
  323. }
  324. defer resp.Body.Close()
  325. // ok
  326. if resp.StatusCode != http.StatusOK {
  327. err = fmt.Errorf("getConfig() http error url(%s) status: %d", url, resp.StatusCode)
  328. return
  329. }
  330. if rb, err = ioutil.ReadAll(resp.Body); err != nil {
  331. return
  332. }
  333. if err = json.Unmarshal(rb, res); err != nil {
  334. return
  335. }
  336. switch res.Code {
  337. case _codeOk:
  338. // has new config
  339. if res.Data == nil {
  340. err = fmt.Errorf("getConfig() response error result: %v", res)
  341. return
  342. }
  343. data = res.Data
  344. default:
  345. err = fmt.Errorf("getConfig() response error result: %v", res)
  346. }
  347. return
  348. }
  349. // update write config
  350. func (c *Client) update(d *data) (err error) {
  351. var (
  352. tmp = make(map[string]*Namespace)
  353. bs = []byte(d.Content)
  354. buf = new(bytes.Buffer)
  355. n *Namespace
  356. ok bool
  357. )
  358. // md5 file
  359. if mh := md5.Sum(bs); hex.EncodeToString(mh[:]) != d.Md5 {
  360. err = fmt.Errorf("md5 mismatch, local:%s, remote:%s", hex.EncodeToString(mh[:]), d.Md5)
  361. return
  362. }
  363. // write conf
  364. if err = json.Unmarshal(bs, &tmp); err != nil {
  365. return
  366. }
  367. for _, value := range tmp {
  368. for k, v := range value.Data {
  369. if strings.Contains(k, ".toml") {
  370. buf.WriteString(v)
  371. buf.WriteString("\n")
  372. }
  373. if err = ioutil.WriteFile(path.Join(conf.Path, k), []byte(v), 0644); err != nil {
  374. return
  375. }
  376. }
  377. }
  378. if n, ok = tmp[""]; !ok {
  379. n = &Namespace{Data: make(map[string]string)}
  380. tmp[""] = n
  381. }
  382. n.Data[commonKey] = buf.String()
  383. // update current version
  384. c.ver = d.Version
  385. c.data.Store(tmp)
  386. return
  387. }
  388. // makeUrl signed url
  389. func (c *Client) makeURL(api string, ver int64) (query string) {
  390. params := url.Values{}
  391. // service
  392. params.Set("service", conf.Svr)
  393. params.Set("hostname", conf.Host)
  394. params.Set("build", conf.Ver)
  395. params.Set("version", fmt.Sprint(ver))
  396. params.Set("ip", localIP())
  397. params.Set("environment", conf.Env)
  398. params.Set("token", conf.Token)
  399. params.Set("appoint", conf.Appoint)
  400. params.Set("customize", c.customize)
  401. // api
  402. query = fmt.Sprintf(api, conf.Addr, params.Encode())
  403. return
  404. }
  405. // localIP return local IP of the host.
  406. func localIP() string {
  407. addrs, err := net.InterfaceAddrs()
  408. if err != nil {
  409. return ""
  410. }
  411. for _, address := range addrs {
  412. // check the address type and if it is not a loopback the display it
  413. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  414. if ipnet.IP.To4() != nil {
  415. return ipnet.IP.String()
  416. }
  417. }
  418. }
  419. return ""
  420. }