support config consul by env
[msb/service-mesh.git] / msb2pilot / src / msb2pilot / consul / controller.go
1 /**
2  * Copyright (c) 2018 ZTE Corporation.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * and the Apache License 2.0 which both accompany this distribution,
6  * and are available at http://www.eclipse.org/legal/epl-v10.html
7  * and http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Contributors:
10  *     ZTE - initial Project
11  */
12 package consul
13
14 import (
15         "msb2pilot/log"
16         "msb2pilot/models"
17         "msb2pilot/util"
18         "os"
19         "path/filepath"
20
21         "github.com/hashicorp/consul/api"
22 )
23
24 var client *api.Client
25 var consulAddress string
26
27 var (
28         cfgFilePath = filepath.Join(util.GetCfgPath(), "consul.yml")
29 )
30
31 const (
32         defaultAddress = "http://localhost:8500"
33 )
34
35 func init() {
36         consulAddress = getConsulAddress(cfgFilePath)
37
38         conf := api.DefaultConfig()
39         conf.Address = consulAddress
40         var err error
41         client, err = api.NewClient(conf)
42
43         if err != nil {
44                 log.Log.Error("failed to init consul client", err)
45         }
46 }
47
48 func getConsulAddress(path string) string {
49         res := os.Getenv(models.EnvConsulAddress)
50         if res != "" {
51                 return res
52         }
53
54         cfg, err := loadCfgInfo(path)
55         if err != nil {
56                 log.Log.Error("load consul config info error", err)
57                 return defaultAddress
58         } else {
59                 if addr, exist := cfg["address"]; exist {
60                         return addr.(string)
61                 } else {
62                         return defaultAddress
63                 }
64         }
65 }
66
67 func loadCfgInfo(path string) (map[interface{}]interface{}, error) {
68         log.Log.Informational("consul config path is:" + path)
69         cfg, err := util.Read(path)
70         if err != nil {
71                 return nil, err
72         }
73
74         result := make(map[interface{}]interface{})
75         err = util.UnmarshalYaml(cfg, result)
76         if err != nil {
77                 return nil, err
78         }
79         return result, nil
80 }
81
82 func GetServices() (map[string][]string, error) {
83         data, _, err := client.Catalog().Services(nil)
84
85         if err != nil {
86                 return nil, err
87         }
88         return data, nil
89 }
90
91 func GetInstances(serviceName string) ([]*api.CatalogService, error) {
92         endpoints, _, err := client.Catalog().Service(serviceName, "", nil)
93         if err != nil {
94                 log.Log.Error("can not get endpoints of ", serviceName)
95                 return nil, err
96         }
97         return endpoints, nil
98 }