2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
27 "github.com/franciscocpg/reflectme"
28 "github.com/iotbzh/xds-agent/lib/xaapiv1"
29 "github.com/urfave/cli"
32 var cacheXdsVersion *xaapiv1.XDSVersion
33 var cacheData = xaapiv1.XDSVersion{}
35 // XdsVersionGet Get version of XDS agent & server
36 func XdsVersionGet(ver *xaapiv1.XDSVersion) error {
38 if cacheXdsVersion == nil {
39 if err := HTTPCli.Get("/version", &cacheData); err != nil {
43 reflectme.Copy(&cacheData, ver)
47 // XdsConfigGet Get current XDS Agent config
48 func XdsConfigGet(cfg *xaapiv1.APIConfig) error {
49 return HTTPCli.Get("/config", cfg)
52 // XdsConfigSet Set XDS Agent config
53 func XdsConfigSet(cfg xaapiv1.APIConfig) error {
57 newCfg := xaapiv1.APIConfig{}
58 if err := HTTPCli.Post("/config", cfg, &newCfg); err != nil {
62 idx := XdsServerIndexGet()
63 if !newCfg.Servers[idx].Connected {
64 return fmt.Errorf("XDS server %s still not connected", cfg.Servers[idx].URL)
70 // XdsServerIDGet returns the XDS Server ID
71 func XdsServerIDGet() string {
72 ver := xaapiv1.XDSVersion{}
73 if err := XdsVersionGet(&ver); err != nil {
76 if len(ver.Server) < 1 {
79 return ver.Server[XdsServerIndexGet()].ID
82 // XdsServerIndexGet returns the index number of XDS Server
83 func XdsServerIndexGet() int {
84 // FIXME support multiple server
88 // XdsServerComputeURL computes the URL used to access to XDS Server API
89 func XdsServerComputeURL(endURL string) string {
90 return "servers/" + strconv.Itoa(XdsServerIndexGet()) + endURL
93 // ProjectsListGet Get the list of existing projects
94 func ProjectsListGet(prjs *[]xaapiv1.ProjectConfig) error {
96 if err := HTTPCli.HTTPGet("/projects", &data); err != nil {
99 Log.Debugf("Result of /projects: %v", string(data[:]))
101 return json.Unmarshal(data, &prjs)
104 // LogPost Helper to log a POST request
105 func LogPost(format string, data interface{}) {
106 b, _ := json.Marshal(data)
107 Log.Infof(format, string(b))
110 // GetID Return a string ID set with --id option or as simple parameter
111 func GetID(ctx *cli.Context) string {
112 id := ctx.String("id")
113 idArgs := ctx.Args().First()
114 if id == "" && idArgs != "" {
120 // Confirm Return true when user answer 'y' or 'yes' to a question
121 func Confirm(question string) bool {
125 ans := strings.ToLower(strings.TrimSpace(answer))
126 return (ans == "y" || ans == "yes")