forked from viant/endly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
335 lines (304 loc) · 9.21 KB
/
service.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
package transformer
import (
"fmt"
"github.com/viant/dsc"
"github.com/viant/toolbox"
"os"
"path"
"sync"
"sync/atomic"
"time"
)
//Service represents transformer service
type Service interface {
Copy(request *CopyRequest) *CopyResponse
TaskList(request *TaskListRequest) *TaskListResponse
KillTask(request *KillTaskRequest) *KillTaskResponse
}
type service struct {
mutex *sync.RWMutex
tasks map[string]*Task
}
func (s *service) registerTask(baseResponse *BaseResponse, taskInfo *TaskInfo, dataset string, request interface{}) {
var task = &Task{
ID: toolbox.AsString(time.Now().Nanosecond()),
Table: dataset,
BaseResponse: baseResponse,
TaskInfo: taskInfo,
Request: request,
}
task.Status = "running"
task.StatusCode = 1
s.mutex.Lock()
defer s.mutex.Unlock()
var now = time.Now()
for k, v := range s.tasks {
if v.Expired(now) {
delete(s.tasks, k)
}
}
s.tasks[task.ID] = task
}
func (s *service) getManager(config *dsc.Config) (dsc.Manager, error) {
if err := config.Init(); err != nil {
return nil, err
}
return dsc.NewManagerFactory().Create(config)
}
func (s *service) transformIfNeeded(transformer Transformer, source map[string]interface{}) ([]map[string]interface{}, error) {
if transformer == nil {
return []map[string]interface{}{source}, nil
}
return transformer(source)
}
func (s *service) appendRecords(transformer Transformer, record map[string]interface{}, records *[]interface{}) error {
transformed, err := s.transformIfNeeded(transformer, record)
if err != nil {
return err
}
for _, item := range transformed {
*records = append(*records, item)
}
return nil
}
func (s *service) drainRecordsIfNeeded(count int, channel chan map[string]interface{}, records *[]interface{}, transformer Transformer) error {
for i := 0; i < count; i++ {
record := <-channel
err := s.appendRecords(transformer, record, records)
if err != nil {
return err
}
}
return nil
}
func (s *service) fetchData(connection dsc.Connection, destinationManager dsc.Manager, dmlProvider dsc.DmlProvider, recordChannel chan map[string]interface{}, transformer Transformer, fetchedCompleted *int32, request *CopyRequest, response *CopyResponse) (completed bool, err error) {
var batchSize = request.BatchSize
if batchSize == 0 {
batchSize++
}
var records = make([]interface{}, 0)
var count = len(recordChannel)
if count == 0 {
select {
case record := <-recordChannel:
count = len(recordChannel)
err = s.appendRecords(transformer, record, &records)
if err != nil {
return false, err
}
count = len(recordChannel)
case <-time.After(time.Millisecond):
count = len(recordChannel)
completed = atomic.LoadInt32(fetchedCompleted) == 1
if completed {
if len(records) == 0 && count == 0 {
return true, nil
}
} else if len(records) < batchSize {
return
}
}
}
err = s.drainRecordsIfNeeded(count, recordChannel, &records, transformer)
if err != nil {
return false, err
}
return s.persist(records, connection, destinationManager, dmlProvider, request)
}
func (s *service) persist(records []interface{}, connection dsc.Connection, destinationManager dsc.Manager, dmlProvider dsc.DmlProvider, request *CopyRequest) (completed bool, err error) {
if len(records) > 0 {
if request.InsertMode {
parametrizedSQLProvider := func(item interface{}) *dsc.ParametrizedSQL {
return dmlProvider.Get(dsc.SQLTypeInsert, item)
}
_, err = destinationManager.PersistData(connection, records, request.Destination.Table, dmlProvider, parametrizedSQLProvider)
if err != nil {
//return false, err
}
} else {
_, _, err = destinationManager.PersistAll(&records, request.Destination.Table, dmlProvider)
if err != nil {
//return false, err
}
}
}
if err != nil || completed {
return true, err
}
return false, err
}
func (s *service) persistInBackground(sourceManager, destinationManager dsc.Manager, records chan map[string]interface{}, request *CopyRequest, response *CopyResponse, fetchedCompleted *int32) *sync.WaitGroup {
var result = &sync.WaitGroup{}
result.Add(1)
destination := request.Destination
tableDescriptor := &dsc.TableDescriptor{
Table: destination.Table,
PkColumns: destination.PkColumns,
Columns: destination.Columns,
}
if len(tableDescriptor.Columns) == 0 {
var table = request.Source.Table
if table == "" {
table = request.Destination.Table
}
dialect := dsc.GetDatastoreDialect(sourceManager.Config().DriverName)
datastore, err := dialect.GetCurrentDatastore(sourceManager)
if err == nil {
columns, err := dialect.GetColumns(sourceManager, datastore, table)
if err == nil {
tableDescriptor.Columns = []string{}
for _, column := range columns {
tableDescriptor.Columns = append(tableDescriptor.Columns, column.Name())
}
}
}
}
destinationManager.TableDescriptorRegistry().Register(tableDescriptor)
dmlProvider := dsc.NewMapDmlProvider(tableDescriptor)
transformer, _ := Transformers[request.Transformer]
var completed bool
go func() {
var err error
defer func() {
if err != nil {
s.updateResponse(response, err)
}
result.Done()
}()
connection, err := destinationManager.ConnectionProvider().Get()
for {
completed, err = s.fetchData(connection, destinationManager, dmlProvider, records, transformer, fetchedCompleted, request, response)
if err != nil {
response.BaseResponse.Status = "error"
response.Error = err.Error()
return
}
if completed {
return
}
}
}()
return result
}
func (s *service) copyData(sourceManager, destinationManager dsc.Manager, request *CopyRequest, response *CopyResponse, keys []interface{}) error {
var batchSize = request.BatchSize
if batchSize == 0 {
batchSize = 1
}
var records = make(chan map[string]interface{}, batchSize+1)
var fetchCompleted int32
waitGroup := s.persistInBackground(sourceManager, destinationManager, records, request, response, &fetchCompleted)
err := sourceManager.ReadAllWithHandler(request.Source.SQL, keys, func(scanner dsc.Scanner) (bool, error) {
var statusCode = atomic.LoadInt32(&response.StatusCode)
var record = make(map[string]interface{})
if statusCode == StatusTaskNotRunning {
return false, nil
}
response.RecordCount++
err := scanner.Scan(&record)
if err != nil {
return false, fmt.Errorf("failed to scan:%v", err)
}
if len(record) == 0 {
response.SkippedRecordCount++
return true, nil
}
records <- record
return true, nil
})
if err != nil {
return err
}
atomic.StoreInt32(&fetchCompleted, 1)
waitGroup.Wait()
return nil
}
func (s *service) openKeyFiles(keyPath string) ([]*os.File, error) {
var result = make([]*os.File, 0)
directory, err := os.Open(keyPath)
if err != nil {
return nil, err
}
files, err := directory.Readdir(0)
if err != nil {
return nil, err
}
for _, info := range files {
filename := path.Join(keyPath, info.Name())
osFile, err := os.Open(filename)
if err != nil {
return nil, err
}
result = append(result, osFile)
}
return result, nil
}
//Copy copy data from source to destination
func (s *service) Copy(request *CopyRequest) *CopyResponse {
var response = &CopyResponse{BaseResponse: &BaseResponse{Status: "ok", StartTime: time.Now()}, TaskInfo: &TaskInfo{StatusCode: StatusTaskRunning}}
response.StatusCode = 1
var dataset = request.Source.Table
if dataset == "" {
dataset = request.Source.SQL
}
s.registerTask(response.BaseResponse, response.TaskInfo, dataset, request)
var err error
var sourceManager, destinationManager dsc.Manager
defer func() { s.updateResponse(response, err) }()
sourceManager, err = s.getManager(request.Source.DsConfig)
if err != nil {
return response
}
destinationManager, err = s.getManager(request.Destination.DsConfig)
if err != nil {
return response
}
destinationManager.TableDescriptorRegistry().Register(request.Destination.AsTableDescription())
keys := []interface{}{}
err = s.copyData(sourceManager, destinationManager, request, response, keys)
s.updateResponse(response, err)
return response
}
//TaskList returns a list of copy tasks
func (s *service) TaskList(request *TaskListRequest) *TaskListResponse {
var response = &TaskListResponse{Status: "ok",
Tasks: make([]*Task, 0),
}
s.mutex.RLock()
defer s.mutex.RUnlock()
for _, candidate := range s.tasks {
if candidate.Table == request.Table {
response.Tasks = append(response.Tasks, candidate)
}
}
return response
}
//KillTask changes status of task to stop it
func (s *service) KillTask(request *KillTaskRequest) *KillTaskResponse {
var response = &KillTaskResponse{BaseResponse: &BaseResponse{StartTime: time.Now()}}
for _, candidate := range s.tasks {
if request.ID == candidate.ID {
response.Task = candidate
atomic.StoreInt32(&candidate.StatusCode, StatusTaskNotRunning)
break
}
}
return response
}
//NewService returns new transformer service
func NewService() Service {
return &service{
tasks: make(map[string]*Task),
mutex: &sync.RWMutex{},
}
}
func (s *service) updateResponse(response *CopyResponse, err error) {
atomic.StoreInt32(&response.StatusCode, 0)
response.EndTime = time.Now()
if err != nil {
response.BaseResponse.Status = "error"
response.Error = err.Error()
} else if response.BaseResponse.Status == "" {
response.BaseResponse.Status = "ok"
}
}