-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
344 lines (305 loc) · 10.9 KB
/
handler.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
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package grpc
import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/micro/go-micro/client"
config2 "github.com/pydio/go-os/config"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/config"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/jobs"
"github.com/pydio/cells/common/proto/object"
protosync "github.com/pydio/cells/common/proto/sync"
"github.com/pydio/cells/common/proto/tree"
"github.com/pydio/cells/common/registry"
"github.com/pydio/cells/common/service"
"github.com/pydio/cells/common/service/context"
context2 "github.com/pydio/cells/common/utils/context"
"github.com/pydio/cells/data/source/sync"
synccommon "github.com/pydio/cells/data/source/sync/lib/common"
"github.com/pydio/cells/data/source/sync/lib/endpoints"
"github.com/pydio/cells/data/source/sync/lib/filters"
"github.com/pydio/cells/data/source/sync/lib/task"
"github.com/pydio/cells/scheduler/tasks"
)
// Handler structure
type Handler struct {
globalCtx context.Context
dsName string
errorsDetected chan string
IndexClient tree.NodeProviderClient
S3client synccommon.PathSyncTarget
syncTask *task.Sync
SyncConfig *object.DataSource
ObjectConfig *object.MinioConfig
watcher config2.Watcher
reloadChan chan bool
stop chan bool
}
func NewHandler(ctx context.Context, datasource string) (*Handler, error) {
h := &Handler{
globalCtx: ctx,
dsName: datasource,
errorsDetected: make(chan string),
stop: make(chan bool),
}
var syncConfig *object.DataSource
if err := servicecontext.ScanConfig(ctx, &syncConfig); err != nil {
return nil, err
}
e := h.initSync(syncConfig)
return h, e
}
func (s *Handler) Start() {
s.syncTask.Start(s.globalCtx)
go s.watchConfigs()
go s.watchErrors()
}
func (s *Handler) Stop() {
s.stop <- true
s.syncTask.Shutdown()
if s.watcher != nil {
s.watcher.Stop()
}
}
// BroadcastCloseSession forwards session id to underlying sync task
func (s *Handler) BroadcastCloseSession(sessionUuid string) {
if s.syncTask == nil {
return
}
s.syncTask.BroadcastCloseSession(sessionUuid)
}
func (s *Handler) NotifyError(errorPath string) {
s.errorsDetected <- errorPath
}
func (s *Handler) initSync(syncConfig *object.DataSource) error {
ctx := s.globalCtx
datasource := s.dsName
var minioConfig *object.MinioConfig
service.Retry(func() error {
log.Logger(ctx).Debug("Sync " + datasource + " - Try to contact Objects")
cli := object.NewObjectsEndpointClient(registry.GetClient(common.SERVICE_DATA_OBJECTS_ + syncConfig.ObjectsServiceName))
resp, err := cli.GetMinioConfig(ctx, &object.GetMinioConfigRequest{})
if err != nil {
log.Logger(ctx).Debug(common.SERVICE_DATA_OBJECTS_ + syncConfig.ObjectsServiceName + " not yet available")
return err
}
minioConfig = resp.MinioConfig
return nil
}, 3*time.Second, 50*time.Second)
if minioConfig == nil {
return fmt.Errorf("objects not reachable")
}
var source synccommon.PathSyncTarget
if syncConfig.Watch {
return fmt.Errorf("datasource watch is not implemented yet")
} else {
s3client, errs3 := endpoints.NewS3Client(ctx,
minioConfig.BuildUrl(), minioConfig.ApiKey, minioConfig.ApiSecret, syncConfig.ObjectsBucket, syncConfig.ObjectsBaseFolder)
if errs3 != nil {
return errs3
}
normalizeS3, _ := strconv.ParseBool(syncConfig.StorageConfiguration["normalize"])
if normalizeS3 {
s3client.ServerRequiresNormalization = true
}
source = s3client
}
indexName, indexClient := registry.GetClient(common.SERVICE_DATA_INDEX_ + datasource)
indexClientWrite := tree.NewNodeReceiverClient(indexName, indexClient)
indexClientRead := tree.NewNodeProviderClient(indexName, indexClient)
sessionClient := tree.NewSessionIndexerClient(indexName, indexClient)
target := sync.NewIndexEndpoint(datasource, indexClientRead, indexClientWrite, sessionClient)
s.S3client = source
s.IndexClient = indexClientRead
s.SyncConfig = syncConfig
s.ObjectConfig = minioConfig
s.syncTask = task.NewSync(ctx, source, target)
s.syncTask.Direction = "left"
return nil
}
func (s *Handler) watchErrors() {
var branch string
for {
select {
case e := <-s.errorsDetected:
e = "/" + strings.TrimLeft(e, "/")
if len(branch) == 0 {
branch = e
} else {
path := strings.Split(e, "/")
stack := strings.Split(branch, "/")
max := math.Min(float64(len(stack)), float64(len(path)))
var commonParent []string
for i := 0; i < int(max); i++ {
if stack[i] == path[i] {
commonParent = append(commonParent, stack[i])
}
}
branch = "/" + strings.TrimLeft(strings.Join(commonParent, "/"), "/")
}
case <-time.After(5 * time.Second):
if len(branch) > 0 {
log.Logger(context.Background()).Info(fmt.Sprintf("Got errors on datasource, should resync now branch: %s", branch))
branch = ""
s.syncTask.Resync(context.Background(), false, nil, nil)
}
case <-s.stop:
return
}
}
}
func (s *Handler) watchConfigs() {
serviceName := common.SERVICE_GRPC_NAMESPACE_ + common.SERVICE_DATA_SYNC_ + s.dsName
watcher, e := config.Default().Watch("services", serviceName)
if e != nil {
return
}
s.watcher = watcher
for {
event, err := watcher.Next()
if err != nil {
continue
}
var cfg object.DataSource
if event.Scan(&cfg) == nil {
log.Logger(s.globalCtx).Debug("Config changed on "+serviceName+", comparing", zap.Any("old", s.SyncConfig), zap.Any("new", &cfg))
if s.SyncConfig.ObjectsBaseFolder != cfg.ObjectsBaseFolder || s.SyncConfig.ObjectsBucket != cfg.ObjectsBucket {
// @TODO - Object service must be restarted before restarting sync
log.Logger(s.globalCtx).Info("Path changed on " + serviceName + ", should reload sync task entirely - Please restart service")
} else if s.SyncConfig.VersioningPolicyName != cfg.VersioningPolicyName || s.SyncConfig.EncryptionMode != cfg.EncryptionMode {
log.Logger(s.globalCtx).Info("Versioning policy changed on "+serviceName+", updating internal config", zap.Any("cfg", &cfg))
s.SyncConfig.VersioningPolicyName = cfg.VersioningPolicyName
s.SyncConfig.EncryptionMode = cfg.EncryptionMode
s.SyncConfig.EncryptionKey = cfg.EncryptionKey
<-time.After(2 * time.Second)
config.TouchSourceNamesForDataServices(common.SERVICE_DATA_SYNC)
}
}
}
}
// TriggerResync sets 2 servers in sync
func (s *Handler) TriggerResync(c context.Context, req *protosync.ResyncRequest, resp *protosync.ResyncResponse) error {
var statusChan chan filters.BatchProcessStatus
var doneChan chan bool
fullLog := &jobs.ActionLog{
OutputMessage: &jobs.ActionMessage{},
}
if req.Task != nil {
statusChan = make(chan filters.BatchProcessStatus)
doneChan = make(chan bool)
subCtx := context2.WithUserNameMetadata(context.Background(), common.PYDIO_SYSTEM_USERNAME)
theTask := req.Task
autoClient := tasks.NewTaskReconnectingClient(subCtx)
taskChan := make(chan interface{})
autoClient.StartListening(taskChan)
theTask.StatusMessage = "Starting"
theTask.HasProgress = true
theTask.Progress = 0
theTask.Status = jobs.TaskStatus_Running
theTask.StartTime = int32(time.Now().Unix())
theTask.ActionsLogs = append(theTask.ActionsLogs, fullLog)
log.TasksLogger(c).Info("Starting Resync")
taskChan <- theTask
go func() {
defer close(statusChan)
defer close(doneChan)
for {
select {
case status := <-statusChan:
theTask.StatusMessage = status.StatusString
theTask.HasProgress = true
theTask.Progress = status.Progress
theTask.Status = jobs.TaskStatus_Running
if status.IsError {
log.TasksLogger(c).Error(status.StatusString)
} else {
log.TasksLogger(c).Info(status.StatusString)
}
taskChan <- theTask
case <-doneChan:
theTask := req.Task
theTask.HasProgress = true
theTask.StatusMessage = "Complete"
theTask.Progress = 1
theTask.EndTime = int32(time.Now().Unix())
theTask.Status = jobs.TaskStatus_Finished
log.TasksLogger(c).Info("Sync completed")
taskChan <- theTask
autoClient.Stop()
return
}
}
}()
}
diff, e := s.syncTask.Resync(c, req.DryRun, statusChan, doneChan)
if e != nil {
if req.Task != nil {
theTask := req.Task
taskClient := jobs.NewJobServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_JOBS, defaults.NewClient(client.Retries(3)))
theTask.StatusMessage = "Error"
theTask.HasProgress = true
theTask.Progress = 1
theTask.EndTime = int32(time.Now().Unix())
theTask.Status = jobs.TaskStatus_Error
log.TasksLogger(c).Error("Error during sync task", zap.Error(e))
theTask.ActionsLogs = append(theTask.ActionsLogs, fullLog)
taskClient.PutTask(c, &jobs.PutTaskRequest{Task: theTask})
}
return e
}
if e == nil {
data, _ := json.Marshal(diff.Stats())
resp.JsonDiff = string(data)
}
resp.Success = true
return nil
}
// Implements the S3Endpoint Interface by using the real object configs + the local datasource configs for bucket and base folder
func (s *Handler) GetDataSourceConfig(ctx context.Context, request *object.GetDataSourceConfigRequest, response *object.GetDataSourceConfigResponse) error {
s.SyncConfig.ObjectsHost = s.ObjectConfig.RunningHost
s.SyncConfig.ObjectsPort = s.ObjectConfig.RunningPort
s.SyncConfig.ObjectsSecure = s.ObjectConfig.RunningSecure
s.SyncConfig.ApiKey = s.ObjectConfig.ApiKey
s.SyncConfig.ApiSecret = s.ObjectConfig.ApiSecret
response.DataSource = s.SyncConfig
return nil
}
// CleanResourcesBeforeDelete gracefully stops the sync task and remove the associated resync job
func (s *Handler) CleanResourcesBeforeDelete(ctx context.Context, request *object.CleanResourcesRequest, response *object.CleanResourcesResponse) error {
s.syncTask.Shutdown()
serviceName := servicecontext.GetServiceName(ctx)
dsName := strings.TrimPrefix(serviceName, common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_DATA_SYNC_)
taskClient := jobs.NewJobServiceClient(common.SERVICE_GRPC_NAMESPACE_+common.SERVICE_JOBS, defaults.NewClient())
log.Logger(ctx).Info("Removing job for datasource " + dsName)
_, e := taskClient.DeleteJob(ctx, &jobs.DeleteJobRequest{
JobID: "resync-ds-" + dsName,
})
return e
}