-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcli.go
253 lines (208 loc) · 4.91 KB
/
cli.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
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"os"
"time"
"cloud.google.com/go/bigquery"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
colorable "github.com/mattn/go-colorable"
"github.com/mitchellh/colorstring"
"google.golang.org/api/option"
)
const (
gcpKey string = "auth.json"
dbFile string = "sqlite.db"
)
const (
// EnvDebug is environmental var to handle debug mode
EnvDebug = "BQCOP_DEBUG"
)
// Exit codes are in value that represnet an exit code for a paticular error
const (
ExitCodeOK int = 0
// Errors start at 10
ExitCodeError = 10 + iota
ExitCodeParseFlagsError
ExitCodeBadArgs
)
// CLI is the command line object
type CLI struct {
outStream, errStream io.Writer
}
// BQJob is BigQuery Job Object
type BQJob struct {
gorm.Model
JobID string `gorm:"primary_key"`
Query string
UserEmail string
TotalBytesBilled int64
StartTime time.Time
EndTime time.Time
}
// BQCop is exec client
type BQCop struct {
db *gorm.DB
authFile string
projectID string
}
// Debugf prints debug output when EnvDebug is given
func Debugf(format string, args ...interface{}) {
if env := os.Getenv(EnvDebug); len(env) != 0 {
log.Printf("[DEBUG] "+format+"\n", args...)
}
}
// PrintErrorf prints error message on console
func PrintErrorf(format string, args ...interface{}) {
format = fmt.Sprintf("[red]%s[reset]\n", format)
fmt.Fprint(colorable.NewColorableStderr(),
colorstring.Color(fmt.Sprintf(format, args...)))
}
// insert does
func (b *BQCop) insert(ctx context.Context, it *bigquery.JobIterator) *bigquery.JobIterator {
job, err := it.Next()
if err != nil {
return nil
}
if job == nil {
return nil
}
status, err := job.Status(ctx)
if err != nil || status == nil {
return it
}
jc, _ := job.Config()
if jc == nil {
return it
}
queryConfig, ok := jc.(*bigquery.QueryConfig)
if !ok {
return it
}
query := queryConfig.Q
if query == "" {
return it
}
id := job.ID()
details := job.LastStatus().Statistics.Details
qstat := details.(*bigquery.QueryStatistics)
stat := status.Statistics
bqJob := &BQJob{
JobID: id,
Query: query,
UserEmail: job.Email(),
TotalBytesBilled: qstat.TotalBytesBilled,
StartTime: stat.StartTime,
EndTime: stat.EndTime,
}
log.Printf("Insert jobID: %s", id)
b.db.Create(bqJob)
return it
}
// Do does do
func (b *BQCop) Do() int {
ctx := context.Background()
client, err := bigquery.NewClient(
ctx,
b.projectID,
option.WithServiceAccountFile(b.authFile))
if err != nil {
panic("ERROR")
}
defer client.Close()
it := client.Jobs(ctx)
it.State = bigquery.Done
it.AllUsers = true
now := time.Now()
it.MinCreationTime = now.AddDate(0, 0, -1) // 1 day ago
it.MaxCreationTime = now
for {
it := b.insert(ctx, it)
if it == nil {
break
}
}
log.Printf("Finished.")
defer b.db.Close()
return ExitCodeOK
}
// connectDB connects data base
func connectDB(dialect string, path string) *gorm.DB {
Debugf("Connect to: %s %s", dialect, path)
db, err := gorm.Open(dialect, path)
if err != nil {
// done
return nil
}
db.AutoMigrate(&BQJob{})
return db
}
// Run invokes the CLI with the given arguments
func (c *CLI) Run(args []string) int {
var (
auth string
projectID string
dbDialect string
dbPath string
debug bool
version bool
)
flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
flags.Usage = func() {
fmt.Fprint(c.errStream, helpText)
}
flags.StringVar(&auth, "auth-json", "", "")
flags.StringVar(&projectID, "project-id", "", "")
flags.StringVar(&dbDialect, "db-dialect", "sqlite3", "")
flags.StringVar(&dbPath, "db-path", dbFile, "")
flags.BoolVar(&debug, "debug", false, "")
flags.BoolVar(&debug, "d", false, "")
flags.BoolVar(&version, "version", false, "")
flags.BoolVar(&version, "v", false, "")
// Parse flag
if err := flags.Parse(args[1:]); err != nil {
return ExitCodeParseFlagsError
}
if debug {
os.Setenv(EnvDebug, "1")
Debugf("Run as DEBUG mode")
}
if version {
fmt.Fprintf(c.outStream, fmt.Sprintf("%s\n", Version))
return ExitCodeOK
}
authFile := gcpKey
if auth != "" {
authFile = auth
}
if projectID == "" {
PrintErrorf("Invalid argument: -project-id must be specified.")
return ExitCodeBadArgs
}
db := connectDB(dbDialect, dbPath)
if db == nil {
return ExitCodeError
}
cop := &BQCop{
db: db,
authFile: authFile,
projectID: projectID,
}
return cop.Do()
}
var helpText = `Usage: bqcop -project-id=project-id -auth-json=auth-json [options...]
bqcop is a tool to fetch BigQuery jobs and store it to DB.
Options:
-project-id Project ID of BigQuery.
-auth-json Auth File of BigQuery.
-db-dialect Dialect of Database.
default: sqlite3
-db-path Path of Database.
default: sqlite.db
-d, --debug Enable debug mode.
-v, --version Print current version.
`