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