forked from pydio/cells-sync
/
http-server.go
352 lines (308 loc) · 9.87 KB
/
http-server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* Copyright 2019 Abstrium SAS
*
* This file is part of Cells Sync.
*
* Cells Sync is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cells Sync is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cells Sync. If not, see <https://www.gnu.org/licenses/>.
*/
package control
import (
"bufio"
"context"
"io"
"net/http"
"time"
"github.com/gin-gonic/contrib/secure"
"github.com/pydio/cells/common/sync/model"
servicecontext "github.com/pydio/cells/common/service/context"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/pborman/uuid"
"gopkg.in/olahol/melody.v1"
"github.com/pydio/cells-sync/app/ux"
"github.com/pydio/cells-sync/common"
"github.com/pydio/cells-sync/config"
"github.com/pydio/cells/common/log"
)
type HttpServer struct {
WebSocket *melody.Melody
LogSocket *melody.Melody
logSocketConnected bool
done chan bool
recentLogs [][]byte
lastSyncState common.SyncState
ctx context.Context
logWriter *io.PipeWriter
}
// NewHttpServer creates a supervisor service for spinning the http server.
func NewHttpServer() *HttpServer {
httpServerCtx := servicecontext.WithServiceName(context.Background(), "http-server")
httpServerCtx = servicecontext.WithServiceColor(httpServerCtx, servicecontext.ServiceColorRest)
r, w := io.Pipe()
h := &HttpServer{
ctx: httpServerCtx,
logWriter: w,
}
log.RegisterWriteSyncer(h)
go func() {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if h.LogSocket != nil && h.logSocketConnected {
h.LogSocket.Broadcast([]byte(line))
}
// Keep last 200 lines in memory
if len(h.recentLogs) < 200 {
h.recentLogs = append(h.recentLogs, []byte(line))
} else {
h.recentLogs = append(h.recentLogs[1:], []byte(line))
}
}
}()
return h
}
// Sync implements the io.Writer method.
func (h *HttpServer) Sync() error {
return nil
}
// Write implements the io.Writer method (used by logs).
func (h *HttpServer) Write(p []byte) (n int, err error) {
go h.logWriter.Write(p)
return len(p), nil
}
// InitHandlers initialize WebSocket handlers.
func (h *HttpServer) InitHandlers() {
h.LogSocket = melody.New()
h.LogSocket.Config.MaxMessageSize = 2048
h.LogSocket.HandleError(func(session *melody.Session, i error) {
//log.Logger(context.Background()).Info("Got Error from LogSocket " + i.Error())
})
h.LogSocket.HandleClose(func(session *melody.Session, i int, i2 string) error {
h.logSocketConnected = false
session.Close()
return nil
})
h.LogSocket.HandleConnect(func(session *melody.Session) {
h.logSocketConnected = true
for _, p := range h.recentLogs {
session.Write(p)
}
})
h.WebSocket = melody.New()
h.WebSocket.Config.MaxMessageSize = 2048
h.WebSocket.HandleError(func(session *melody.Session, i error) {
//log.Logger(context.Background()).Info("Got Error from WebSocket " + i.Error())
})
h.WebSocket.HandleClose(func(session *melody.Session, i int, i2 string) error {
session.Close()
return nil
})
h.WebSocket.HandleMessage(func(session *melody.Session, bytes []byte) {
data := common.MessageFromData(bytes)
switch data.Type {
case "PING":
m := &common.Message{Type: "PONG", Content: "Hello new client!"}
session.Write(m.Bytes())
// Publish state if there are tasks, or empty state
if len(config.Default().Tasks) == 0 {
emptyState := &common.Message{Type: "STATE", Content: nil}
session.Write(emptyState.Bytes())
} else {
// Publish sync states
GetBus().Pub(MessagePublishState, TopicSyncAll)
}
// Publish Authorities list
message := &common.Message{Type: "AUTHORITIES", Content: config.Default().PublicAuthorities()}
session.Write(message.Bytes())
case "WEBVIEW_ROUTE":
// Just forward to webview
h.WebSocket.Broadcast(bytes)
case "CMD":
if cmd, ok := data.Content.(*common.CmdContent); ok {
if intCmd, err := MessageFromString(cmd.Cmd); err == nil {
if cmd.UUID != "" {
go GetBus().Pub(intCmd, TopicSync_+cmd.UUID)
} else {
if intCmd == MessageHalt || intCmd == MessageRestart {
GetBus().Pub(intCmd, TopicGlobal)
} else {
go GetBus().Pub(intCmd, TopicSyncAll)
}
}
}
}
case "CONFIG":
if confContent, ok := data.Content.(*common.ConfigContent); ok {
confs := config.Default()
if confContent.Task != nil {
if confContent.Cmd == "create" {
confContent.Task.Uuid = uuid.New()
confs.CreateTask(confContent.Task)
} else if confContent.Cmd == "edit" {
confs.UpdateTask(confContent.Task)
} else if confContent.Cmd == "delete" {
confs.RemoveTask(confContent.Task)
}
} else if confContent.Authority != nil {
if confContent.Cmd == "create" {
confs.CreateAuthority(confContent.Authority)
} else if confContent.Cmd == "edit" {
confs.UpdateAuthority(confContent.Authority, false)
} else if confContent.Cmd == "delete" {
confs.RemoveAuthority(confContent.Authority)
} else if confContent.Cmd == "list" {
message := &common.Message{Type: "AUTHORITIES", Content: confs.PublicAuthorities()}
session.Write(message.Bytes())
}
}
}
case "UPDATE":
if req, ok := data.Content.(*common.UpdateCheckRequest); ok {
if req.Check {
go GetBus().Pub(req, TopicUpdate)
} else if req.Version {
// Just publish version back to client
message := &common.Message{Type: "UPDATE", Content: &common.UpdateVersion{
PackageName: common.PackageType,
Version: common.Version,
Revision: common.BuildRevision,
BuildStamp: common.BuildStamp,
}}
session.Write(message.Bytes())
}
} else if req, ok := data.Content.(*common.UpdateApplyRequest); ok {
go GetBus().Pub(req, TopicUpdate)
}
default:
log.Logger(h.ctx).Error("Cannot read message " + string(bytes))
}
})
go h.ListenStatus()
go h.ListenAuthorities()
}
func (h *HttpServer) drop(s common.SyncState) bool {
defer func() {
h.lastSyncState = s
}()
if (h.lastSyncState == common.SyncState{}) {
return false
}
if h.lastSyncState.Status == model.TaskStatusProcessing && s.Status == model.TaskStatusProcessing && s.LastProcessStatus != nil {
newPg := s.LastProcessStatus.Progress()
oldPg := float32(0)
if h.lastSyncState.LastProcessStatus != nil {
oldPg = h.lastSyncState.LastProcessStatus.Progress()
}
// Limit number of events, except if progress is 100% which may indicate some additional checks/cleaning operations
if newPg > 0 && newPg < 1 && oldPg > 0 && newPg-oldPg <= 0.001 {
return true
}
}
return false
}
// ListenStatus is hooked to the general Bus to listen for SyncStates and UpdateMessages.
// It should be called as a goroutine
func (h *HttpServer) ListenStatus() {
statuses := GetBus().Sub(TopicState, TopicUpdate)
for {
select {
case <-h.done:
GetBus().Unsub(statuses, TopicState, TopicUpdate)
return
case s := <-statuses:
if state, ok := s.(common.SyncState); ok {
if !h.drop(state) {
m := &common.Message{
Type: "STATE",
Content: s,
}
h.WebSocket.Broadcast(m.Bytes())
}
} else if update, ok := s.(common.UpdateMessage); ok {
m := &common.Message{
Type: "UPDATE",
Content: update,
}
h.WebSocket.Broadcast(m.Bytes())
}
}
}
}
// ListenAuthorities listens to a config watcher for transmitting Authority changes.
// It should be called as a goroutine.
func (h *HttpServer) ListenAuthorities() {
watches := config.Watch()
for w := range watches {
if _, ok := w.(*config.AuthChange); ok {
// Broadcast servers list to all clients
message := &common.Message{Type: "AUTHORITIES", Content: config.Default().PublicAuthorities()}
h.WebSocket.Broadcast(message.Bytes())
}
}
}
// Serve implements supervisor service interface. It basically starts the http server.
func (h *HttpServer) Serve() {
h.done = make(chan bool)
h.InitHandlers()
gin.SetMode(gin.ReleaseMode)
gin.DisableConsoleColor()
Server := gin.New()
Server.NoRoute(func(i *gin.Context) {
ux.Box.Bytes("index.html")
i.Data(http.StatusOK, "text/html; charset=utf-8", ux.Box.Bytes("index.html"))
})
Server.Use(gin.Recovery())
Server.Use(static.Serve("/", ux.Box))
addr, err := config.GetHttpAddress()
if err != nil {
log.Logger(h.ctx).Error("Cannot start server: " + err.Error())
return
}
Server.Use(secure.Secure(secure.Options{
AllowedHosts: []string{addr},
}))
Server.GET("/status", func(c *gin.Context) {
h.WebSocket.HandleRequest(c.Writer, c.Request)
})
Server.GET("/logs", func(c *gin.Context) {
h.LogSocket.HandleRequest(c.Writer, c.Request)
})
// Simple RestAPI for browsing/creating nodes inside Endpoints
Server.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"PUT", "POST"},
AllowHeaders: []string{"*"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
// Manage Tree
Server.POST("/default", h.defaultDir)
Server.POST("/tree", h.ls)
Server.PUT("/tree", h.mkdir)
// Load Patch contents
Server.GET("/patches/:uuid/:offset/:limit", h.listPatches)
// Manage global config
Server.GET("/config", h.loadConf)
Server.PUT("/config", h.updateConf)
log.Logger(h.ctx).Info("Starting HttpServer on " + addr)
if e := http.ListenAndServe(addr, Server); e != nil {
log.Logger(h.ctx).Error("Cannot start server: " + e.Error())
}
}
// Stop implements supervisor service interface.
func (h *HttpServer) Stop() {
h.done <- true
}