1ba2cd850f99b3a8e734d968ee8aa94a20b37e18
[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/util"
17         "path/filepath"
18
19         "github.com/hashicorp/consul/api"
20 )
21
22 var client *api.Client
23 var consulAddress string
24
25 var (
26         cfgFilePath = filepath.Join(util.GetCfgPath(), "consul.yml")
27 )
28
29 const (
30         defaultAddress = "http://localhost:8500"
31 )
32
33 func init() {
34         consulAddress = getConsulAddress(cfgFilePath)
35
36         conf := api.DefaultConfig()
37         conf.Address = consulAddress
38         var err error
39         client, err = api.NewClient(conf)
40
41         if err != nil {
42                 log.Log.Error("failed to init consul client", err)
43         }
44 }
45
46 func getConsulAddress(path string) string {
47         cfg, err := loadCfgInfo(path)
48         if err != nil {
49                 log.Log.Error("load consul config info error", err)
50                 return defaultAddress
51         } else {
52                 if addr, exist := cfg["address"]; exist {
53                         return addr.(string)
54                 } else {
55                         return defaultAddress
56                 }
57         }
58 }
59
60 func loadCfgInfo(path string) (map[interface{}]interface{}, error) {
61         log.Log.Informational("consul config path is:" + path)
62         cfg, err := util.Read(path)
63         if err != nil {
64                 return nil, err
65         }
66
67         result := make(map[interface{}]interface{})
68         err = util.UnmarshalYaml(cfg, result)
69         if err != nil {
70                 return nil, err
71         }
72         return result, nil
73 }
74
75 func GetServices() (map[string][]string, error) {
76         data, _, err := client.Catalog().Services(nil)
77
78         if err != nil {
79                 return nil, err
80         }
81         return data, nil
82 }
83
84 func GetInstances(serviceName string) ([]*api.CatalogService, error) {
85         endpoints, _, err := client.Catalog().Service(serviceName, "", nil)
86         if err != nil {
87                 log.Log.Error("can not get endpoints of ", serviceName)
88                 return nil, err
89         }
90         return endpoints, nil
91 }