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.
30 "github.com/gin-gonic/gin"
31 "github.com/iotbzh/xds-agent/lib/xaapiv1"
32 "github.com/iotbzh/xds-agent/lib/xdsconfig"
33 common "github.com/iotbzh/xds-common/golib"
34 "github.com/iotbzh/xds-server/lib/xsapiv1"
35 uuid "github.com/satori/go.uuid"
36 sio_client "github.com/sebd71/go-socket.io-client"
40 type XdsServer struct {
49 ServerConfig *xsapiv1.APIConfig
53 CBOnDisconnect func(error)
54 sockEvents map[string][]*caller
55 sockEventsLock *sync.Mutex
58 client *common.HTTPClient
59 ioSock *sio_client.Client
61 apiRouter *gin.RouterGroup
62 cmdList map[string]interface{}
65 // EventCB Event emitter callback
66 type EventCB func(privData interface{}, evtData interface{}) error
68 // caller Used to chain event listeners
73 PrivateData interface{}
76 const _IDTempoPrefix = "tempo-"
78 // NewXdsServer creates an instance of XdsServer
79 func NewXdsServer(ctx *Context, conf xdsconfig.XDSServerConf) *XdsServer {
82 ID: _IDTempoPrefix + uuid.NewV1().String(),
84 APIURL: conf.APIBaseURL + conf.APIPartialURL,
85 PartialURL: conf.APIPartialURL,
86 ConnRetry: conf.ConnRetry,
90 sockEvents: make(map[string][]*caller),
91 sockEventsLock: &sync.Mutex{},
93 cmdList: make(map[string]interface{}),
97 // Close Free and close XDS Server connection
98 func (xs *XdsServer) Close() error {
106 // Connect Establish HTTP connection with XDS Server
107 func (xs *XdsServer) Connect() error {
115 for retry = xs.ConnRetry; retry > 0; retry-- {
116 if err = xs._CreateConnectHTTP(); err == nil {
119 if retry == xs.ConnRetry {
120 // Notify only on the first conn error
121 // doing that avoid 2 notifs (conn false; conn true) on startup
124 xs.Log.Infof("Establishing connection to XDS Server (retry %d/%d)", retry, xs.ConnRetry)
125 time.Sleep(time.Second)
128 // FIXME: re-use _reconnect to wait longer in background
129 return fmt.Errorf("Connection to XDS Server failure")
135 // Check HTTP connection and establish WS connection
136 err = xs._connect(false)
141 // IsTempoID returns true when server as a temporary id
142 func (xs *XdsServer) IsTempoID() bool {
143 return strings.HasPrefix(xs.ID, _IDTempoPrefix)
146 // SetLoggerOutput Set logger ou
147 func (xs *XdsServer) SetLoggerOutput(out io.Writer) {
151 // SendCommand Send a command to XDS Server
152 func (xs *XdsServer) SendCommand(cmd string, body []byte, res interface{}) error {
154 if !strings.HasPrefix("/", cmd) {
157 return xs.client.Post(url, string(body), res)
160 // GetVersion Send Get request to retrieve XDS Server version
161 func (xs *XdsServer) GetVersion(res interface{}) error {
162 return xs.client.Get("/version", &res)
165 // GetFolders Send GET request to get current folder configuration
166 func (xs *XdsServer) GetFolders(folders *[]xsapiv1.FolderConfig) error {
167 return xs.client.Get("/folders", folders)
170 // FolderAdd Send POST request to add a folder
171 func (xs *XdsServer) FolderAdd(fld *xsapiv1.FolderConfig, res interface{}) error {
172 err := xs.client.Post("/folders", fld, res)
174 return fmt.Errorf("FolderAdd error: %s", err.Error())
179 // FolderDelete Send DELETE request to delete a folder
180 func (xs *XdsServer) FolderDelete(id string) error {
181 return xs.client.HTTPDelete("/folders/" + id)
184 // FolderSync Send POST request to force synchronization of a folder
185 func (xs *XdsServer) FolderSync(id string) error {
186 return xs.client.HTTPPost("/folders/sync/"+id, "")
189 // FolderUpdate Send PUT request to update a folder
190 func (xs *XdsServer) FolderUpdate(fld *xsapiv1.FolderConfig, resFld *xsapiv1.FolderConfig) error {
191 return xs.client.Put("/folders/"+fld.ID, fld, resFld)
194 // CommandExec Send POST request to execute a command
195 func (xs *XdsServer) CommandExec(args *xsapiv1.ExecArgs, res *xsapiv1.ExecResult) error {
196 return xs.client.Post("/exec", args, res)
199 // CommandSignal Send POST request to send a signal to a command
200 func (xs *XdsServer) CommandSignal(args *xsapiv1.ExecSignalArgs, res *xsapiv1.ExecSigResult) error {
201 return xs.client.Post("/signal", args, res)
204 // SetAPIRouterGroup .
205 func (xs *XdsServer) SetAPIRouterGroup(r *gin.RouterGroup) {
209 // PassthroughGet Used to declare a route that sends directly a GET request to XDS Server
210 func (xs *XdsServer) PassthroughGet(url string) {
211 if xs.apiRouter == nil {
212 xs.Log.Errorf("apiRouter not set !")
216 xs.apiRouter.GET(url, func(c *gin.Context) {
218 // Take care of param (eg. id in /projects/:id)
220 if strings.Contains(url, ":") {
221 nURL = strings.TrimPrefix(c.Request.URL.Path, xs.APIURL)
224 if err := xs.client.Get(nURL, &data); err != nil {
225 if strings.Contains(err.Error(), "connection refused") {
229 common.APIError(c, err.Error())
233 c.JSON(http.StatusOK, data)
237 // PassthroughPost Used to declare a route that sends directly a POST request to XDS Server
238 func (xs *XdsServer) PassthroughPost(url string) {
239 if xs.apiRouter == nil {
240 xs.Log.Errorf("apiRouter not set !")
244 xs.apiRouter.POST(url, func(c *gin.Context) {
246 n, err := c.Request.Body.Read(bodyReq)
248 common.APIError(c, err.Error())
252 // Take care of param (eg. id in /projects/:id)
254 if strings.Contains(url, ":") {
255 nURL = strings.TrimPrefix(c.Request.URL.Path, xs.APIURL)
259 body, err := json.Marshal(bodyReq[:n])
261 common.APIError(c, err.Error())
265 response, err := xs.client.HTTPPostWithRes(nURL, string(body))
267 common.APIError(c, err.Error())
271 bodyRes, err := ioutil.ReadAll(response.Body)
273 common.APIError(c, "Cannot read response body")
276 c.JSON(http.StatusOK, string(bodyRes))
280 // EventRegister Post a request to register to an XdsServer event
281 func (xs *XdsServer) EventRegister(evName string, id string) error {
282 return xs.client.Post(
284 xsapiv1.EventRegisterArgs{
291 // EventEmit Emit a event to XDS Server through WS
292 func (xs *XdsServer) EventEmit(message string, args ...interface{}) error {
293 if xs.ioSock == nil {
294 return fmt.Errorf("Io.Socket not initialized")
297 return xs.ioSock.Emit(message, args...)
300 // EventOn Register a callback on events reception
301 func (xs *XdsServer) EventOn(evName string, privData interface{}, f EventCB) (uuid.UUID, error) {
302 if xs.ioSock == nil {
303 return uuid.Nil, fmt.Errorf("Io.Socket not initialized")
306 xs.sockEventsLock.Lock()
307 defer xs.sockEventsLock.Unlock()
309 if _, exist := xs.sockEvents[evName]; !exist {
310 // Register listener only the first time
313 // FIXME: use generic type: data interface{} instead of data xsapiv1.EventMsg
315 if evName == "event:folder-state-change" {
316 err = xs.ioSock.On(evn, func(data xsapiv1.EventMsg) error {
317 xs.sockEventsLock.Lock()
318 sEvts := make([]*caller, len(xs.sockEvents[evn]))
319 copy(sEvts, xs.sockEvents[evn])
320 xs.sockEventsLock.Unlock()
321 for _, c := range sEvts {
322 c.Func(c.PrivateData, data)
327 err = xs.ioSock.On(evn, func(data interface{}) error {
328 xs.sockEventsLock.Lock()
329 sEvts := make([]*caller, len(xs.sockEvents[evn]))
330 copy(sEvts, xs.sockEvents[evn])
331 xs.sockEventsLock.Unlock()
332 for _, c := range sEvts {
333 c.Func(c.PrivateData, data)
347 PrivateData: privData,
350 xs.sockEvents[evName] = append(xs.sockEvents[evName], c)
354 // EventOff Un-register a (or all) callbacks associated to an event
355 func (xs *XdsServer) EventOff(evName string, id uuid.UUID) error {
356 xs.sockEventsLock.Lock()
357 defer xs.sockEventsLock.Unlock()
358 if _, exist := xs.sockEvents[evName]; exist {
361 xs.sockEvents[evName] = []*caller{}
363 // Un-register only the specified callback
364 for i, ff := range xs.sockEvents[evName] {
365 if uuid.Equal(ff.id, id) {
366 xs.sockEvents[evName] = append(xs.sockEvents[evName][:i], xs.sockEvents[evName][i+1:]...)
375 // ProjectToFolder Convert Project structure to Folder structure
376 func (xs *XdsServer) ProjectToFolder(pPrj xaapiv1.ProjectConfig) *xsapiv1.FolderConfig {
378 if pPrj.Type == xsapiv1.TypeCloudSync {
379 stID, _ = xs.SThg.IDGet()
381 // TODO: limit ClientData size and gzip it (see https://golang.org/pkg/compress/gzip/)
382 fPrj := xsapiv1.FolderConfig{
385 ClientPath: pPrj.ClientPath,
386 Type: xsapiv1.FolderType(pPrj.Type),
388 IsInSync: pPrj.IsInSync,
389 DefaultSdk: pPrj.DefaultSdk,
390 ClientData: pPrj.ClientData,
391 DataPathMap: xsapiv1.PathMapConfig{
392 ServerPath: pPrj.ServerPath,
394 DataCloudSync: xsapiv1.CloudSyncConfig{
396 STLocIsInSync: pPrj.IsInSync,
397 STLocStatus: pPrj.Status,
398 STSvrIsInSync: pPrj.IsInSync,
399 STSvrStatus: pPrj.Status,
406 // FolderToProject Convert Folder structure to Project structure
407 func (xs *XdsServer) FolderToProject(fPrj xsapiv1.FolderConfig) xaapiv1.ProjectConfig {
408 inSync := fPrj.IsInSync
411 if fPrj.Type == xsapiv1.TypeCloudSync {
412 inSync = fPrj.DataCloudSync.STSvrIsInSync && fPrj.DataCloudSync.STLocIsInSync
414 sts = fPrj.DataCloudSync.STSvrStatus
415 switch fPrj.DataCloudSync.STLocStatus {
416 case xaapiv1.StatusErrorConfig, xaapiv1.StatusDisable, xaapiv1.StatusPause:
417 sts = fPrj.DataCloudSync.STLocStatus
419 case xaapiv1.StatusSyncing:
420 if sts != xaapiv1.StatusErrorConfig && sts != xaapiv1.StatusDisable && sts != xaapiv1.StatusPause {
421 sts = xaapiv1.StatusSyncing
424 case xaapiv1.StatusEnable:
430 pPrj := xaapiv1.ProjectConfig{
434 ClientPath: fPrj.ClientPath,
435 ServerPath: fPrj.DataPathMap.ServerPath,
436 Type: xaapiv1.ProjectType(fPrj.Type),
439 DefaultSdk: fPrj.DefaultSdk,
440 ClientData: fPrj.ClientData,
445 // CommandAdd Add a new command to the list of running commands
446 func (xs *XdsServer) CommandAdd(cmdID string, data interface{}) error {
447 if xs.CommandGet(cmdID) != nil {
448 return fmt.Errorf("command id already exist")
450 xs.cmdList[cmdID] = data
454 // CommandDelete Delete a command from the command list
455 func (xs *XdsServer) CommandDelete(cmdID string) error {
456 if xs.CommandGet(cmdID) == nil {
457 return fmt.Errorf("unknown command id")
459 delete(xs.cmdList, cmdID)
463 // CommandGet Retrieve a command data
464 func (xs *XdsServer) CommandGet(cmdID string) interface{} {
465 d, exist := xs.cmdList[cmdID]
476 // Create HTTP client
477 func (xs *XdsServer) _CreateConnectHTTP() error {
479 xs.client, err = common.HTTPNewClient(xs.BaseURL,
480 common.HTTPClientConfig{
481 URLPrefix: "/api/v1",
482 HeaderClientKeyName: "Xds-Sid",
485 LogPrefix: "XDSSERVER: ",
486 LogLevel: common.HTTPLogLevelWarning,
489 xs.client.SetLogLevel(xs.Log.Level.String())
492 msg := ": " + err.Error()
493 if strings.Contains(err.Error(), "connection refused") {
494 msg = fmt.Sprintf("(url: %s)", xs.BaseURL)
496 return fmt.Errorf("ERROR: cannot connect to XDS Server %s", msg)
498 if xs.client == nil {
499 return fmt.Errorf("ERROR: cannot connect to XDS Server (null client)")
505 // Re-established connection
506 func (xs *XdsServer) _reconnect() error {
507 err := xs._connect(true)
509 // Reload projects list for this server
510 err = xs.projects.Init(xs)
515 // Established HTTP and WS connection and retrieve XDSServer config
516 func (xs *XdsServer) _connect(reConn bool) error {
518 xdsCfg := xsapiv1.APIConfig{}
519 if err := xs.client.Get("/config", &xdsCfg); err != nil {
527 if reConn && xs.ID != xdsCfg.ServerUID {
528 xs.Log.Warningf("Reconnected to server but ID differs: old=%s, new=%s", xs.ID, xdsCfg.ServerUID)
531 // Update local XDS config
532 xs.ID = xdsCfg.ServerUID
533 xs.ServerConfig = &xdsCfg
535 // Establish WS connection and register listen
536 if err := xs._SocketConnect(); err != nil {
547 // Create WebSocket (io.socket) connection
548 func (xs *XdsServer) _SocketConnect() error {
550 xs.Log.Infof("Connecting IO.socket for server %s (url %s)", xs.ID, xs.BaseURL)
552 opts := &sio_client.Options{
553 Transport: "websocket",
554 Header: make(map[string][]string),
556 opts.Header["XDS-SID"] = []string{xs.client.GetClientID()}
558 iosk, err := sio_client.NewClient(xs.BaseURL, opts)
560 return fmt.Errorf("IO.socket connection error for server %s: %v", xs.ID, err)
564 // Register some listeners
566 iosk.On("error", func(err error) {
567 xs.Log.Infof("IO.socket Error server %s; err: %v", xs.ID, err)
568 if xs.CBOnError != nil {
573 iosk.On("disconnection", func(err error) {
574 xs.Log.Infof("IO.socket disconnection server %s", xs.ID)
575 if xs.CBOnDisconnect != nil {
576 xs.CBOnDisconnect(err)
581 // Try to reconnect during 15min (or at least while not disabled)
585 for !xs.Disabled && !xs.Connected {
590 if waitTime > 15*60 {
591 xs.Log.Infof("Stop reconnection to server url=%s id=%s !", xs.BaseURL, xs.ID)
594 time.Sleep(time.Second * time.Duration(waitTime))
595 xs.Log.Infof("Try to reconnect to server %s (%d)", xs.BaseURL, count)
602 // XXX - There is no connection event generated so, just consider that
603 // we are connected when NewClient return successfully
604 /* iosk.On("connection", func() { ... }) */
605 xs.Log.Infof("IO.socket connected server url=%s id=%s", xs.BaseURL, xs.ID)
610 // Send event to notify changes
611 func (xs *XdsServer) _NotifyState() {
613 evSts := xaapiv1.ServerCfg{
617 PartialURL: xs.PartialURL,
618 ConnRetry: xs.ConnRetry,
619 Connected: xs.Connected,
621 if err := xs.events.Emit(xaapiv1.EVTServerConfig, evSts, ""); err != nil {
622 xs.Log.Warningf("Cannot notify XdsServer state change: %v", err)