-
Notifications
You must be signed in to change notification settings - Fork 25
/
job.go
236 lines (210 loc) · 5.15 KB
/
job.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
package bqjob
import (
"context"
"encoding/csv"
"fmt"
"io"
"os"
"reflect"
"regexp"
"dekart/src/proto"
"dekart/src/server/job"
"dekart/src/server/storage"
"cloud.google.com/go/bigquery"
"google.golang.org/api/googleapi"
)
// Job implements the dekart.Job interface for BigQuery; concurrency safe.
type Job struct {
job.BasicJob
bigqueryJob *bigquery.Job
storageObject storage.StorageObject
maxReadStreamsCount int32
maxBytesBilled int64
}
var contextCancelledRe = regexp.MustCompile(`context canceled`)
var orderByRe = regexp.MustCompile(`(?ims)order[\s]+by`)
func (job *Job) close(storageWriter io.WriteCloser, csvWriter *csv.Writer) {
csvWriter.Flush()
err := storageWriter.Close()
if err != nil {
// maybe we should not close when context is canceled in job.write()
if err == context.Canceled {
return
}
if contextCancelledRe.MatchString(err.Error()) {
return
}
job.Logger.Err(err).Send()
job.CancelWithError(err)
return
}
resultSize, err := job.storageObject.GetSize(job.GetCtx())
if err != nil {
job.Logger.Err(err).Send()
job.CancelWithError(err)
return
}
job.Logger.Debug().Msg("Writing Done")
job.Lock()
job.ResultSize = *resultSize
jobID := job.GetID()
job.ResultID = &jobID
job.Unlock()
job.Status() <- int32(proto.Query_JOB_STATUS_DONE)
job.Cancel()
}
func (job *Job) setJobStats(queryStatus *bigquery.JobStatus, table *bigquery.Table) error {
if table == nil {
return fmt.Errorf("table is nil")
}
tableMetadata, err := table.Metadata(job.GetCtx())
if err != nil {
return err
}
job.Lock()
defer job.Unlock()
if queryStatus.Statistics != nil {
job.ProcessedBytes = queryStatus.Statistics.TotalBytesProcessed
}
job.TotalRows = int64(tableMetadata.NumRows)
return nil
}
// write csv rows to storage
func (job *Job) write(csvRows chan []string) {
storageWriter := job.storageObject.GetWriter(job.GetCtx())
csvWriter := csv.NewWriter(storageWriter)
for {
csvRow, more := <-csvRows
if !more {
break
}
err := csvWriter.Write(csvRow)
if err == context.Canceled {
break
}
if err != nil {
job.Logger.Err(err).Send()
job.CancelWithError(err)
break
}
}
job.close(storageWriter, csvWriter)
}
type AvroSchema struct {
Fields []struct {
Name string `json:"name"`
} `json:"fields"`
}
func (job *Job) processApiErrors(err error) {
if apiError, ok := err.(*googleapi.Error); ok {
for _, e := range apiError.Errors {
if e.Reason == "bytesBilledLimitExceeded" {
job.Logger.Warn().Str(
"DEKART_BIGQUERY_MAX_BYTES_BILLED", os.Getenv("DEKART_BIGQUERY_MAX_BYTES_BILLED"),
).Msg(e.Message)
}
}
}
}
func (job *Job) getResultTable() (*bigquery.Table, error) {
jobConfig, err := job.bigqueryJob.Config()
if err != nil {
return nil, err
}
jobConfigVal := reflect.ValueOf(jobConfig).Elem()
table, ok := jobConfigVal.FieldByName("Dst").Interface().(*bigquery.Table)
if !ok {
err := fmt.Errorf("cannot get destination table from job config")
job.Logger.Error().Err(err).Str("jobConfig", fmt.Sprintf("%v+", jobConfig)).Send()
return nil, err
}
if table == nil {
err := fmt.Errorf("destination table is nil")
job.Logger.Error().Err(err).Str("jobConfig", fmt.Sprintf("%v+", jobConfig)).Send()
return nil, err
}
return table, nil
}
func (job *Job) wait() {
queryStatus, err := job.bigqueryJob.Wait(job.GetCtx())
if err == context.Canceled {
return
}
if err != nil {
job.processApiErrors(err)
job.CancelWithError(err)
return
}
if queryStatus == nil {
job.Logger.Fatal().Msgf("queryStatus == nil")
}
if err := queryStatus.Err(); err != nil {
job.CancelWithError(err)
return
}
table, err := job.getResultTable()
if err != nil {
job.CancelWithError(err)
return
}
err = job.setJobStats(queryStatus, table)
if err != nil {
job.CancelWithError(err)
return
}
job.Status() <- int32(proto.Query_JOB_STATUS_READING_RESULTS)
csvRows := make(chan []string, job.TotalRows)
errors := make(chan error)
// read table rows into csvRows
go Read(
job.GetCtx(),
errors,
csvRows,
table,
job.Logger,
job.maxReadStreamsCount,
)
// write csvRows to storage
go job.write(csvRows)
// wait for errors
err = <-errors
if err != nil {
job.CancelWithError(err)
return
}
job.Logger.Debug().Msg("Job Wait Done")
}
func (job *Job) setMaxReadStreamsCount(queryText string) {
job.Lock()
defer job.Unlock()
if orderByRe.MatchString(queryText) {
job.maxReadStreamsCount = 1 // keep order of items
} else {
job.maxReadStreamsCount = 10
}
}
// Run implementation
func (job *Job) Run(storageObject storage.StorageObject) error {
job.Logger.Debug().Msg("Run BigQuery Job")
client, err := bigquery.NewClient(job.GetCtx(), os.Getenv("DEKART_BIGQUERY_PROJECT_ID"))
if err != nil {
job.Cancel()
return err
}
query := client.Query(job.QueryText)
query.MaxBytesBilled = job.maxBytesBilled
job.setMaxReadStreamsCount(job.QueryText)
bigqueryJob, err := query.Run(job.GetCtx())
if err != nil {
job.Cancel()
return err
}
job.Lock()
job.bigqueryJob = bigqueryJob
job.storageObject = storageObject
job.Unlock()
job.Status() <- int32(proto.Query_JOB_STATUS_RUNNING)
job.Logger.Debug().Msg("Waiting for results")
go job.wait()
return nil
}