-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagellan-gcs-uploader.go
225 lines (198 loc) · 4.75 KB
/
magellan-gcs-uploader.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
package main
import (
"cloud.google.com/go/bigquery"
"cloud.google.com/go/storage"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"golang.org/x/oauth2/google"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var (
apiTokens []string
projectID string
)
func mustGetenv(ctx context.Context, k string) string {
v := os.Getenv(k)
if v == "" {
log.Fatal("%s environment variable not set.", k)
}
return v
}
func verifyApiToken(token string) error {
for _, x := range apiTokens {
if x == token {
return nil
}
}
return errors.New("invalid api token.")
}
type Response struct {
Success bool `json:"success"`
Message string `json:"message"`
}
type BigQueryRecord struct {
Row map[string]bigquery.Value
}
func (r *BigQueryRecord) Save() (row map[string]bigquery.Value, insertID string, err error) {
return r.Row, "", nil
}
func postBlocksFlow(ctx context.Context, blocks_url, blocks_api_token, gcs_url string, timestamp time.Time, r *http.Request) error {
values := url.Values{}
values.Set("api_token", blocks_api_token)
values.Set("gcs_url", gcs_url)
values.Set("target_time", timestamp.Format("2006-01-02T15:04:05.999999Z07:00"))
for k, v := range r.Form {
if k == "content" || k == "key" {
continue
}
if v[0] != "" {
values.Set(k, v[0])
}
}
res, err := http.PostForm(blocks_url, values)
if err == nil {
defer res.Body.Close()
}
return err
}
func postHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
response := Response{false, "something wrong."}
code := 500
defer func() {
outjson, e := json.Marshal(response)
if e != nil {
log.Printf(e.Error())
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
if code == 200 {
fmt.Fprint(w, string(outjson))
} else {
http.Error(w, string(outjson), code)
}
}()
if r.Method != "POST" {
response.Message = "only POST method method was accepted"
code = 404
return
}
// Check API Token
api_key := r.FormValue("key")
if apiTokens == nil {
apiTokens = strings.Split(mustGetenv(ctx, "API_TOKEN"), ",")
}
err := verifyApiToken(api_key)
if err != nil {
response.Message = err.Error()
code = 401
return
}
// Upload file to GCS
filename := r.FormValue("filename")
content, err := base64.StdEncoding.DecodeString(r.FormValue("content"))
if err != nil {
response.Message = "content parameter: invalid base64 encoded."
code = 400
return
}
client, err := storage.NewClient(ctx)
if err != nil {
log.Printf(err.Error())
response.Message = err.Error()
code = 500
return
}
bucket_name := mustGetenv(ctx, "STORAGE_BUCKET")
bucket := client.Bucket(bucket_name)
object := bucket.Object(filename)
writer := object.NewWriter(ctx)
_, err = writer.Write(content)
if err != nil {
log.Printf(err.Error())
response.Message = err.Error()
code = 500
return
}
err = writer.Close()
if err != nil {
log.Printf(err.Error())
response.Message = err.Error()
code = 500
return
}
gcs_url := "gs://" + bucket_name + "/" + filename
timestamp := time.Now()
dataset_id := os.Getenv("BIGQUERY_DATASET")
table_id := os.Getenv("BIGQUERY_TABLE")
if dataset_id != "" && table_id != "" {
// Insert metadata to BigQuery
bqclient, err := bigquery.NewClient(ctx, projectID)
if err != nil {
log.Printf(err.Error())
response.Message = err.Error()
code = 500
return
}
table := bqclient.Dataset(dataset_id).Table(table_id)
uploader := table.Uploader()
record := &BigQueryRecord{}
record.Row = make(map[string](bigquery.Value))
record.Row["gcs_url"] = gcs_url
record.Row["timestamp"] = timestamp
columns := mustGetenv(ctx, "BIGQUERY_COLUMNS")
field_names := strings.Split(columns, ",")
for _, fn := range field_names {
val := r.FormValue(fn)
if val != "" {
record.Row[fn] = val
}
}
err = uploader.Put(ctx, record)
if err != nil {
log.Printf(err.Error())
response.Message = err.Error()
code = 500
return
}
}
blocks_url := os.Getenv("BLOCKS_URL")
blocks_api_token := os.Getenv("BLOCKS_API_TOKEN")
if blocks_url != "" && blocks_api_token != "" {
err = postBlocksFlow(ctx, blocks_url, blocks_api_token, gcs_url, timestamp, r)
if err != nil {
log.Printf(err.Error())
response.Message = err.Error()
code = 500
return
}
}
response.Success = true
response.Message = "ok"
code = 200
return
}
func main() {
apiTokens = nil
http.HandleFunc("/upload", postHandler)
credentials, e := google.FindDefaultCredentials(context.Background())
if e != nil {
log.Fatal(e)
}
projectID = credentials.ProjectID
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
log.Printf("Listening on port %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}