Update .gitreview file
[src/xds/xds-cli.git] / utils.go
1 /*
2  * Copyright (C) 2017-2018 "IoT.bzh"
3  * Author Sebastien Douheret <sebastien@iot.bzh>
4  *
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
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  */
18
19 package main
20
21 import (
22         "encoding/json"
23         "fmt"
24         "os"
25         "sort"
26         "strconv"
27         "strings"
28
29         "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xaapiv1"
30         "github.com/franciscocpg/reflectme"
31         "github.com/urfave/cli"
32 )
33
34 var cacheXdsVersion *xaapiv1.XDSVersion
35 var cacheData = xaapiv1.XDSVersion{}
36
37 // XdsVersionGet Get version of XDS agent & server
38 func XdsVersionGet(ver *xaapiv1.XDSVersion) error {
39         // Update cached data
40         if cacheXdsVersion == nil {
41                 if err := HTTPCli.Get("/version", &cacheData); err != nil {
42                         return err
43                 }
44         }
45         reflectme.Copy(&cacheData, ver)
46         return nil
47 }
48
49 // XdsConfigGet Get current XDS Agent config
50 func XdsConfigGet(cfg *xaapiv1.APIConfig) error {
51         return HTTPCli.Get("/config", cfg)
52 }
53
54 // XdsConfigSet Set XDS Agent config
55 func XdsConfigSet(cfg xaapiv1.APIConfig) error {
56         // clear cache
57         cacheXdsVersion = nil
58
59         newCfg := xaapiv1.APIConfig{}
60         if err := HTTPCli.Post("/config", cfg, &newCfg); err != nil {
61                 return err
62         }
63
64         idx := XdsServerIndexGet()
65         if !newCfg.Servers[idx].Connected {
66                 return fmt.Errorf("XDS server %s still not connected", cfg.Servers[idx].URL)
67         }
68
69         return nil
70 }
71
72 // XdsServerIDGet returns the XDS Server ID
73 func XdsServerIDGet() string {
74         ver := xaapiv1.XDSVersion{}
75         if err := XdsVersionGet(&ver); err != nil {
76                 return ""
77         }
78         if len(ver.Server) < 1 {
79                 return ""
80         }
81         return ver.Server[XdsServerIndexGet()].ID
82 }
83
84 // XdsServerIndexGet returns the index number of XDS Server
85 func XdsServerIndexGet() int {
86         // FIXME support multiple server
87         return 0
88 }
89
90 // XdsServerComputeURL computes the URL used to access to XDS Server API
91 func XdsServerComputeURL(endURL string) string {
92         return "servers/" + strconv.Itoa(XdsServerIndexGet()) + endURL
93 }
94
95 // Sort projects by Label
96 type _PrjByLabel []xaapiv1.ProjectConfig
97
98 func (s _PrjByLabel) Len() int           { return len(s) }
99 func (s _PrjByLabel) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
100 func (s _PrjByLabel) Less(i, j int) bool { return s[i].Label < s[j].Label }
101
102 // ProjectsListGet Get the list of existing projects
103 func ProjectsListGet(prjs *[]xaapiv1.ProjectConfig) error {
104         var data []byte
105         if err := HTTPCli.HTTPGet("/projects", &data); err != nil {
106                 return err
107         }
108         Log.Debugf("Result of /projects: %v", string(data[:]))
109
110         if err := json.Unmarshal(data, &prjs); err != nil {
111                 return err
112         }
113
114         sort.Sort(_PrjByLabel(*prjs))
115
116         return nil
117 }
118
119 // LogPost Helper to log a POST request
120 func LogPost(format string, data interface{}) {
121         b, _ := json.Marshal(data)
122         Log.Infof(format, string(b))
123 }
124
125 // GetID Return a string ID set with --id option or as simple parameter
126 func GetID(ctx *cli.Context, idEnvVarName string) string {
127         return GetIDName(ctx, "id", idEnvVarName)
128 }
129
130 // GetIDName Return a string ID set with --XXX option or as simple parameter
131 func GetIDName(ctx *cli.Context, idName, idEnvVarName string) string {
132         if idName == "" {
133                 return ""
134         }
135
136         // Get id set using option --id
137         id := ctx.String(idName)
138
139         // Check if id has been set using env variable
140         envSdkid, _ := os.LookupEnv(idEnvVarName)
141
142         // Support as 1st arg without --id option string (for example xds-cli sdk install 123456)
143         idArgs := ctx.Args().First()
144
145         // Set or overwrite id using first arg (knowing that 1st is overwrite env variable)
146         if (id == "" && idArgs != "") || (envSdkid != "" && idArgs != "") {
147                 id = idArgs
148         }
149         return id
150 }
151
152 // Confirm Return true when user answer 'y' or 'yes' to a question
153 func Confirm(question string) bool {
154         var answer string
155         fmt.Print(question)
156         fmt.Scanln(&answer)
157         ans := strings.ToLower(strings.TrimSpace(answer))
158         return (ans == "y" || ans == "yes")
159 }
160
161 // compareID Compare an ID to a reference ID
162 func compareID(refID, ID string) bool {
163         return refID != "" && ID != "" && strings.HasPrefix(refID, ID)
164 }