Added api to list and reconnect a XDS-Server.
[src/xds/xds-agent.git] / lib / agent / apiv1.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 package agent
19
20 import (
21         "fmt"
22         "strconv"
23         "strings"
24
25         "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent/lib/xaapiv1"
26         "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent/lib/xdsconfig"
27         "gerrit.automotivelinux.org/gerrit/src/xds/xds-server.git/lib/xsapiv1"
28         "github.com/gin-gonic/gin"
29 )
30
31 const apiBaseURL = "/api/v1"
32
33 // APIService .
34 type APIService struct {
35         *Context
36         apiRouter   *gin.RouterGroup
37         serverIndex int
38 }
39
40 // NewAPIV1 creates a new instance of API service
41 func NewAPIV1(ctx *Context) *APIService {
42         s := &APIService{
43                 Context:     ctx,
44                 apiRouter:   ctx.webServer.router.Group(apiBaseURL),
45                 serverIndex: 0,
46         }
47
48         s.apiRouter.GET("/version", s.getVersion)
49
50         s.apiRouter.GET("/config", s.getConfig)
51         s.apiRouter.POST("/config", s.setConfig)
52
53         // s.apiRouter.GET("/browse", s.browseFS)
54
55         s.apiRouter.GET("/projects", s.getProjects)
56         s.apiRouter.GET("/projects/:id", s.getProject)
57         s.apiRouter.PUT("/projects/:id", s.updateProject)
58         s.apiRouter.POST("/projects", s.addProject)
59         s.apiRouter.POST("/projects/sync/:id", s.syncProject)
60         s.apiRouter.DELETE("/projects/:id", s.delProject)
61
62         s.apiRouter.POST("/exec", s.execCmd)
63         s.apiRouter.POST("/exec/:id", s.execCmd)
64         s.apiRouter.POST("/signal", s.execSignalCmd)
65
66         s.apiRouter.GET("/events", s.eventsList)
67         s.apiRouter.POST("/events/register", s.eventsRegister)
68         s.apiRouter.POST("/events/unregister", s.eventsUnRegister)
69
70         return s
71 }
72
73 // Stop Used to stop/close created services
74 func (s *APIService) Stop() {
75         for _, svr := range s.xdsServers {
76                 svr.Close()
77         }
78 }
79
80 // AddXdsServer Add a new XDS Server to the list of a server
81 func (s *APIService) AddXdsServer(cfg xdsconfig.XDSServerConf) (*XdsServer, error) {
82         var svr *XdsServer
83         var exist, tempoID bool
84         tempoID = false
85
86         // First check if not already exist and update it
87         if svr, exist = s.xdsServers[cfg.ID]; exist {
88
89                 // Update: Found, so just update some settings
90                 svr.ConnRetry = cfg.ConnRetry
91
92                 tempoID = svr.IsTempoID()
93                 if svr.Connected && !svr.Disabled && svr.BaseURL == cfg.URL && tempoID {
94                         return svr, nil
95                 }
96
97                 // URL differ or not connected, so need to reconnect
98                 svr.BaseURL = cfg.URL
99
100         } else {
101
102                 // Create a new server object
103                 cfg.URLIndex = strconv.Itoa(s.serverIndex)
104                 s.serverIndex = s.serverIndex + 1
105                 if cfg.APIBaseURL == "" {
106                         cfg.APIBaseURL = apiBaseURL
107                 }
108                 if cfg.APIPartialURL == "" {
109                         cfg.APIPartialURL = "/servers/" + cfg.URLIndex
110                 }
111
112                 // Create a new XDS Server
113                 svr = NewXdsServer(s.Context, cfg)
114
115                 svr.SetLoggerOutput(s.Config.LogVerboseOut)
116
117                 // Define API group for this XDS Server
118                 grp := s.apiRouter.Group(svr.PartialURL)
119                 svr.SetAPIRouterGroup(grp)
120
121                 // Define servers API processed locally
122                 s.apiRouter.GET("/servers", s.getServersList)       // API /servers
123                 svr.apiRouter.GET("", s.getServer)                  // API /servers/:id
124                 svr.apiRouter.POST("/reconnect", s.reconnectServer) // API /servers/:id/reconnect
125
126                 // Declare passthrough API/routes
127                 s.sdksPassthroughInit(svr)
128                 s.targetsPassthroughInit(svr)
129
130                 // Register callback on Connection
131                 svr.ConnectOn(func(server *XdsServer) error {
132
133                         // Add server to list
134                         s.xdsServers[server.ID] = svr
135
136                         // Register events forwarder
137                         if err := s.sdksEventsForwardInit(server); err != nil {
138                                 s.Log.Errorf("XDS Server %v - sdk events forwarding error: %v", server.ID, err)
139                         }
140
141                         // Load projects
142                         if err := s.projects.Init(server); err != nil {
143                                 s.Log.Errorf("XDS Server %v - project init error: %v", server.ID, err)
144                         }
145
146                         // Registered to all events
147                         if err := server.EventRegister(xsapiv1.EVTAll, ""); err != nil {
148                                 s.Log.Errorf("XDS Server %v - register all events error: %v", server.ID, err)
149                         }
150
151                         return nil
152                 })
153         }
154
155         // Established connection
156         err := svr.Connect()
157
158         // Delete temporary ID with it has been replaced by right Server ID
159         if tempoID && !svr.IsTempoID() {
160                 delete(s.xdsServers, cfg.ID)
161         }
162
163         return svr, err
164 }
165
166 // DelXdsServer Delete an XDS Server from the list of a server
167 func (s *APIService) DelXdsServer(id string) error {
168         if _, exist := s.xdsServers[id]; !exist {
169                 return fmt.Errorf("Unknown Server ID %s", id)
170         }
171         // Don't really delete, just disable it
172         s.xdsServers[id].Close()
173         return nil
174 }
175
176 // UpdateXdsServer Update XDS Server configuration settings
177 func (s *APIService) UpdateXdsServer(cfg xaapiv1.ServerCfg) error {
178         if _, exist := s.xdsServers[cfg.ID]; !exist {
179                 return fmt.Errorf("Unknown Server ID %s", cfg.ID)
180         }
181
182         svr := s.xdsServers[cfg.ID]
183
184         // Update only some configurable fields
185         svr.ConnRetry = cfg.ConnRetry
186
187         return nil
188 }
189
190 // GetXdsServerFromURLIndex Retrieve XdsServer from URLIndex value
191 func (s *APIService) GetXdsServerFromURLIndex(urlIdx string) *XdsServer {
192         for _, svr := range s.xdsServers {
193                 if svr.URLIndex == urlIdx {
194                         return svr
195                 }
196         }
197         return nil
198 }
199
200 // ParamGetIndex Retrieve numerical parameter in request url
201 func (s *APIService) ParamGetIndex(c *gin.Context) string {
202         uri := c.Request.RequestURI
203         for idx := strings.LastIndex(uri, "/"); idx > 0; {
204                 id := uri[idx+1:]
205                 if _, err := strconv.Atoi(id); err == nil {
206                         return id
207                 }
208                 uri = uri[:idx]
209                 idx = strings.LastIndex(uri, "/")
210         }
211         return ""
212 }