Added Copyright headers.
[src/xds/xds-cli.git] / utils.go
1 /*
2  * Copyright (C) 2017 "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
24         "github.com/iotbzh/xds-agent/lib/xaapiv1"
25         "github.com/urfave/cli"
26 )
27
28 var cacheXdsVersion *xaapiv1.XDSVersion
29
30 // XdsVersionGet Get version of XDS agent & server
31 func XdsVersionGet(ver *xaapiv1.XDSVersion) error {
32         // Use cached data
33         if cacheXdsVersion != nil {
34                 ver = cacheXdsVersion
35                 return nil
36         }
37
38         dataVer := xaapiv1.XDSVersion{}
39         if err := HTTPCli.Get("/version", &dataVer); err != nil {
40                 return err
41         }
42
43         cacheXdsVersion = &dataVer
44         *ver = dataVer
45         return nil
46 }
47
48 // XdsServerIDGet returns the XDS Server ID
49 func XdsServerIDGet() string {
50         ver := xaapiv1.XDSVersion{}
51         if err := XdsVersionGet(&ver); err != nil {
52                 return ""
53         }
54         if len(ver.Server) < 1 {
55                 return ""
56         }
57         return ver.Server[XdsServerIndexGet()].ID
58 }
59
60 // XdsServerIndexGet returns the index number of XDS Server
61 func XdsServerIndexGet() int {
62         // FIXME support multiple server
63         return 0
64 }
65
66 // ProjectsListGet Get the list of existing projects
67 func ProjectsListGet(prjs *[]xaapiv1.ProjectConfig) error {
68         var data []byte
69         if err := HTTPCli.HTTPGet("/projects", &data); err != nil {
70                 return err
71         }
72         Log.Debugf("Result of /projects: %v", string(data[:]))
73
74         return json.Unmarshal(data, &prjs)
75 }
76
77 // LogPost Helper to log a POST request
78 func LogPost(format string, data interface{}) {
79         b, _ := json.Marshal(data)
80         Log.Infof(format, string(b))
81 }
82
83 // GetID Return a string ID set with --id option or as simple parameter
84 func GetID(ctx *cli.Context) string {
85         id := ctx.String("id")
86         idArgs := ctx.Args().First()
87         if id == "" && idArgs != "" {
88                 id = idArgs
89         }
90         return id
91 }