-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
1552 lines (1463 loc) · 44.3 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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// copyright Matthias Büchse, 2019
package main
import (
"bytes"
"database/sql"
"encoding/json"
"errors"
"flag"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3"
cmap "github.com/orcaman/concurrent-map"
"golang.org/x/crypto/bcrypt"
)
type DatabaseApp struct {
dbPath string
db *sql.DB
matViewsMux sync.Mutex
matViewsMap map[int]cmap.ConcurrentMap // per access level
module Module
inter Inter
secret []byte
jobQueue chan object
imgPath string
imgPaths map[int]string
}
type Transformer interface {
transform(object)
}
type Claims struct {
jwt.StandardClaims
PrivilegeLevel int `json:"prl,omitempty"`
AccountId string `json:"sid,omitempty"`
}
type Authorization struct {
level int
subject string
id string
}
type AuthorizedApp struct {
*DatabaseApp
auth *Authorization
matViews cmap.ConcurrentMap
transformer Transformer
}
const (
GUEST = 9 // will see reduced data
PREMIUM = 8 // will see full data w/o personal data
EDITOR = 4 // will see full data, can change content within sensible boundaries
CHIEF = 3 // editor-in-chief
ADMIN = 1 // ???
ROOT = 0 // will see full data, can change almost anything
)
var PRIVILEGES = map[string]int{
"guest": GUEST,
"premium": PREMIUM,
"editor": EDITOR,
"chief": CHIEF,
"admin": ADMIN,
"root": ROOT,
}
var RESOLUTIONS []int = []int{100, 400, 720}
const QUALITY = 75
func NewDatabaseApp(dbPath string, module Module, inter Inter, secret []byte, imgPath string) (*DatabaseApp, error) {
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
return nil, err
}
if err := module.Init(db); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Join(imgPath, "full"), 0755); err != nil {
return nil, err
}
imgPaths := make(map[int]string, len(RESOLUTIONS))
for _, res := range RESOLUTIONS {
p := filepath.Join(imgPath, strconv.Itoa(res))
if err := os.MkdirAll(p, 0755); err != nil {
return nil, err
}
imgPaths[res] = p
}
return &DatabaseApp{dbPath: dbPath, db: db, matViewsMap: make(map[int]cmap.ConcurrentMap), module: module, inter: inter, secret: secret, jobQueue: make(chan object, 5), imgPath: imgPath, imgPaths: imgPaths}, nil
}
func (app *DatabaseApp) Close() {
app.db.Close()
}
type NullTransformer struct{}
type DefaultTransformer struct {
inner Transformer
auth *Authorization
}
type GuestTransformer struct {
inner Transformer
now int64
versionSuffix string
}
func (NullTransformer) transform(obj object) {
if obj[K_TYPE] == TYPE_ERROR {
return
}
version, _ := obj[K_VERSION].(string) // "" if not present
obj[K_VERSION] = version
}
func (t DefaultTransformer) transform(obj object) {
t.inner.transform(obj)
id, _ := obj[K_ID].(string)
if t.auth.level > EDITOR && (strings.HasPrefix(id, "/query/")) {
// transform a potential 404 into 401, so the matview doesn't even get computed
transformToError(obj, EACCES, fmt.Sprintf("access to sensitive information denied; user '%v'", t.auth.id))
}
typ, _ := obj[K_TYPE].(string)
if typ == TYPE_ERROR {
return
}
visibility, _ := obj["visibility"].(string)
if level, present := PRIVILEGES[visibility]; present && t.auth.level > level {
transformToError(obj, EACCES, "access denied")
}
owner, _ := obj["$owner"].(string)
if t.auth.level > EDITOR && owner != "" {
transformToError(obj, EACCES, fmt.Sprintf("access to sensitive information denied; user '%v'", t.auth.id))
}
if t.auth.level >= EDITOR && typ == TYPE_ACCOUNT && id != t.auth.id {
// do not modify version
// a) We shall always, ALWAYS redact personal data over this API, so no distinction necessary.
// b) It would make a lot of trouble in postprocessing $prefetch.
// obj[K_VERSION] = obj[K_VERSION].(string) + t.redactedVersionSuffix
transformToError(obj, EACCES, fmt.Sprintf("access to sensitive information denied; user '%v'", t.auth.id))
}
}
const THRESHOLD = 30 * 24 * 3600 // 1 month
func (t GuestTransformer) transform(obj object) {
t.inner.transform(obj)
if obj[K_TYPE] == TYPE_ERROR {
return
}
version := obj[K_VERSION].(string)
split := strings.Split(version, "/")
if len(split) > 1 && split[1] == "pruned" {
return
}
obj[K_VERSION] = split[0] + "/pruned/" + t.versionSuffix
datestr, _ := obj["date"].(string)
date, err := strconv.Atoi(datestr)
if err != nil || t.now-int64(date) > THRESHOLD {
typ := obj[K_TYPE]
if typ == TYPE_EVENT {
obj["$components"] = []interface{}{}
obj["pruned"] = true
} else if typ == "statement" {
obj["content"] = "(nicht in freier Version enthalten)"
obj["pruned"] = true
}
}
}
func (app *DatabaseApp) MatViewsForLevel(level int) cmap.ConcurrentMap {
app.matViewsMux.Lock()
defer app.matViewsMux.Unlock()
// collapse levels a bit for the matview cache... let's hope that's okay
if level >= ADMIN && level < PREMIUM {
level = PREMIUM
}
mv, present := app.matViewsMap[level]
if !present {
mv = cmap.New()
app.matViewsMap[level] = mv
}
return mv
}
func (app *DatabaseApp) MatViewsMapCopy() map[int]cmap.ConcurrentMap {
app.matViewsMux.Lock()
defer app.matViewsMux.Unlock()
result := make(map[int]cmap.ConcurrentMap, len(app.matViewsMap))
for level, m := range app.matViewsMap {
result[level] = m
}
return result
}
func (app *DatabaseApp) InvalidateMatViews() {
app.matViewsMux.Lock()
defer app.matViewsMux.Unlock()
app.matViewsMap = make(map[int]cmap.ConcurrentMap)
}
func (app *AuthorizedApp) Transformer() Transformer {
if app.transformer == nil {
var transformer Transformer = DefaultTransformer{NullTransformer{}, app.auth}
if false && app.auth.level >= GUEST {
// ^^ deactivated for the time being (only impedes alpha testing phase)
t := time.Now()
versionSuffix := fmt.Sprintf("%04d%02d%02d", t.Year(), t.Month(), t.Day())
transformer = GuestTransformer{transformer, t.Unix(), versionSuffix}
}
app.transformer = transformer
}
return app.transformer
}
func (app *DatabaseApp) loadAccount(email string) (result object) {
objects := make(objectMap)
_ = objects.queryDB(app.db, `natural join pr_email where email = ?`, 1, nil, email)
for _, obj := range objects {
return obj
}
return object{}
}
const EXTRACT = 4 // extract errors
func (app *AuthorizedApp) loadFromDatabase(objects objectMap, keys []string, flags int) error {
misses := make(map[string]bool)
err := objects.loadFromDatabase(app.db, keys, misses, flags&FOLLOWMASK)
if err == nil {
for k := range misses {
objects[k] = transformToError(object{K_ID: k}, ENOENT, "object not found")
}
t := app.Transformer()
for _, o := range objects {
t.transform(o)
}
if flags&EXTRACT != 0 {
err = objects.extractError()
}
}
return err
}
func (app *AuthorizedApp) queryDB(objects objectMap, clauses string, limit int, keys *[]string, args ...interface{}) error {
err := objects.queryDB(app.db, clauses, limit, keys, args...)
if err == nil {
t := app.Transformer()
for _, k := range *keys {
t.transform(objects[k])
}
}
return err
}
func (app *AuthorizedApp) computePreView(objects objectMap, k string) (mv object) {
targetId := ""
err := fmt.Errorf("invalid preview identifier: %v", k)
split := strings.Split(k, "/")
if split[0] != "" || len(split) < 2 {
// keep err unchanged
} else if len(split) == 3 && split[1] == "preview" {
targetId = split[2]
// !!! do not use EXTRACT here because objects could be tainted from the get go
// instead, handle direct errors below with the type distinction
err = app.loadFromDatabase(objects, []string{targetId}, FOLLOW)
}
if err == nil {
obj := objects[targetId]
if obj[K_TYPE] == "event" {
mv = object{
K_TYPE: "event-preview",
K_ID: k,
"$target?": targetId,
}
for okey, oval := range obj {
if okey != K_TYPE && okey != K_ID && okey != "$components" {
mv[okey] = oval
}
}
if components, ok := obj["$components"].([]interface{}); ok {
cs := make([]interface{}, len(components))
for i, cid := range components {
if cidstr, ok := cid.(string); ok {
com := objects[cidstr]
cs[i] = object{
"$target?": cid,
"$tags": com["$tags"],
}
}
}
mv["components"] = cs
}
} else if obj[K_TYPE] == TYPE_ERROR {
mv = object{
K_TYPE: TYPE_ERROR,
K_ID: k,
"code": obj["code"],
"msg": obj["msg"],
"$target?": targetId,
}
} else {
err = fmt.Errorf("Invalid object type for preview '%v': %v", k, obj)
}
}
if err == nil {
app.Transformer().transform(mv)
return mv
}
return transformToError(object{K_ID: k}, 500, err.Error())
}
func (app *AuthorizedApp) getPreView(objects objectMap, k string) object {
if mv, present := app.matViews.Get(k); present {
return mv.(object)
}
mv := app.computePreView(objects, k)
if mv[K_TYPE] != TYPE_ERROR {
app.matViews.Set(k, mv)
}
return mv
}
func (app *AuthorizedApp) computeMatView(objects objectMap, k string) (mv object) {
var objectKeys []string
preview := false
err := fmt.Errorf("invalid matview identifier: %v", k)
split := strings.Split(k, "/")
if split[0] != "" || len(split) < 2 {
// keep err unchanged
} else if len(split) == 2 && split[1] == "home" {
clauses := `natural join pr_date where type = ? order by date desc`
err = app.queryDB(objects, clauses, 50, &objectKeys, TYPE_EVENT)
preview = true
} else if len(split) >= 3 && split[1] == "query" && strings.HasPrefix(split[2], "owner=") {
accountId := split[2][6:]
if accountId != app.auth.id {
err = fmt.Errorf("access denied to '%v'; user '%v'", k, app.auth.id)
} else if len(split) == 3 {
clauses := `natural join pr_owner where owner = ?`
err = app.queryDB(objects, clauses, 100, &objectKeys, accountId)
}
} else if len(split) == 4 && split[1] == "latest" && strings.HasPrefix(split[2], "type=") && strings.HasPrefix(split[3], "tag=") {
typeStr := split[2][5:]
tagStr := split[3][4:]
clauses := `natural join pr_date natural join pr_tags where type = ? and tagid = ? order by date desc`
err = app.queryDB(objects, clauses, 20, &objectKeys, typeStr, tagStr)
}
if err == nil {
err = app.loadFromDatabase(objects, objectKeys, FOLLOW)
}
if err == nil {
i := 0
for j, key := range objectKeys {
okey := objectKeys[j]
var obj object
if preview {
okey = "/preview/" + okey
obj = app.getPreView(objects, okey)
objects[okey] = obj
} else {
obj = objects[key]
}
if obj["type"] != TYPE_ERROR {
objectKeys[i] = okey
i++
}
}
mv = object{
K_TYPE: TYPE_MATVIEW,
K_ID: k,
"$objects": objectKeys[:i],
}
if i != len(objectKeys) {
mv["numErrors"] = len(objectKeys) - i
}
err = objects.ComputePrefetch(mv)
}
if err == nil {
app.Transformer().transform(mv)
return mv
}
return transformToError(object{K_ID: k}, 500, err.Error())
}
func (app *AuthorizedApp) handleView(objects objectMap, k string) {
if !strings.HasPrefix(k, "/") {
return
}
if mv, present := app.matViews.Get(k); present {
objects[k] = mv.(object)
return
}
log.Printf("cache miss (level %v): %v", app.auth.level, k)
var mv object
if strings.HasPrefix(k, "/preview/") {
mv = app.computePreView(objects, k)
} else {
mv = app.computeMatView(objects, k)
}
if mv[K_TYPE] != TYPE_ERROR && !strings.HasPrefix(k, "/query/") {
app.matViews.Set(k, mv)
}
objects[k] = mv
}
func (app *AuthorizedApp) checkVersion(obj object) error {
version, ok := obj[K_VERSION].(string)
if !ok {
return nil
}
split := strings.Split(version, "/")
if len(split) == 1 {
return nil
}
return errors.New(fmt.Sprintf("Invalid version '%v' for object: %v", version, obj))
}
var editorCanChange map[string]bool = map[string]bool{
"component": true, "event": true, "book": true, "statistic": true, "statement": true,
}
// Any user can change any object they own, as well as their account.
// In addition, an editor can change any object that doesn't have an owner if its type is in editorCanChange.
// In addition, a ROOT level user can change any object.
func (app *AuthorizedApp) checkOwner(extant, obj object) error {
if app.auth.level == ROOT || extant[K_ID] == app.auth.id {
return nil
}
if owner, ok := extant["$owner"].(string); ok {
if owner == app.auth.id {
return nil
}
} else if app.auth.level <= EDITOR {
if editorCanChange[extant[K_TYPE].(string)] {
return nil
}
}
return errors.New(fmt.Sprintf("Invalid owner (current user '%v'): %v", app.auth.id, extant))
}
// The privilege level of an account must be set, and it must not be higher than that of the current user.
func (app *AuthorizedApp) checkPrivilege(obj object) error {
if obj[K_TYPE] != TYPE_ACCOUNT || app.auth.level == ROOT {
return nil
}
privilege, _ := obj["privilege"].(string)
if level, present := PRIVILEGES[privilege]; present {
if obj[K_ID] == app.auth.id && level >= app.auth.level {
return nil
}
// XXX Do we want people to be able to promote others to their own level? Or should this be left to superiors?
if level > app.auth.level {
return nil
}
}
return errors.New(fmt.Sprintf("Invalid privilege level '%v' (current user '%v'): %v", privilege, app.auth.id, obj))
}
func (app *AuthorizedApp) checkTypeChange(extant, obj object) error {
v0, _ := extant[K_TYPE].(string)
v1, _ := obj[K_TYPE].(string)
if app.auth.level == ROOT || v0 == v1 {
return nil
}
return errors.New(fmt.Sprintf("Invalid type change for '%v' from '%v' to '%v'", obj[K_ID], v0, v1))
}
func (app *AuthorizedApp) doUpsert(tx *sql.Tx, obj object, prevVersion interface{}) (err error) {
id, ok := obj["id"].(string)
if !ok {
// TODO || !sanitizeId(&id)
// FIXME id should be uuid conformant, but definitely no slashes in id (reserved for materialized views)
return BadRequest{fmt.Errorf("invalid id in object: %v", obj)}
}
objects := make(objectMap)
var rows *sql.Rows
rows, err = tx.Query(`select id, data from objects where id = ?`, id)
if err != nil {
return err
}
if err := objects.consumeRows(rows, 1, nil); err != nil {
return err
}
// sanity checks
references := make(map[string]bool)
if err := CollectReferences([]object{obj}, true, references); err != nil {
return err
}
delete(references, id) // reference yourself if you must
if err := QueryExistence(tx, references); err != nil {
return err
}
if len(references) != 0 {
return BadRequest{errors.New(fmt.Sprintf("Unsatisfied references for '%v': %v", id, references))}
}
mtx := app.module.Begin(tx)
defer mtx.Close()
if err := app.checkVersion(obj); err != nil {
return err
}
if err := app.checkPrivilege(obj); err != nil {
return err
}
if extant, present := objects[id]; present {
if prevVersion != "*" && prevVersion != extant[K_VERSION] && obj[K_VERSION] != extant[K_VERSION] {
return PreconditionFailed{fmt.Errorf("Version did not match: '%v' != '%v'", prevVersion, extant[K_VERSION])}
}
if err := app.checkOwner(extant, obj); err != nil {
return err
}
if err := app.checkTypeChange(extant, obj); err != nil {
return err
}
if err := mtx.Update(objects, obj); err != nil {
return err
}
objects[id] = obj
} else {
if prevVersion != "*" && prevVersion != "ENOENT" {
return PreconditionFailed{fmt.Errorf("Version did not match: '%v' != 'ENOENT'", prevVersion)}
}
// FIXME what kind of objects may be created by whom? Current `upsert` endpoint is only available for EDITOR and better anyway...
if err := mtx.Insert(obj); err != nil {
return err
}
}
return nil
}
func (app *AuthorizedApp) doDelete(tx *sql.Tx, id string) (err error) {
mtx := app.module.Begin(tx)
defer mtx.Close()
if err := mtx.Delete(id); err != nil {
return err
}
return nil
}
func (app *AuthorizedApp) Get(keys ...string) (result []map[string]interface{}, err error) {
objects := make(objectMap)
trueKeys := make([]string, len(keys))
j := 0
for _, key := range keys {
trueKey := strings.Split(key, ":")[0]
if strings.HasPrefix(trueKey, "/") {
app.handleView(objects, trueKey)
} else {
trueKeys[j] = trueKey
j++
}
}
if j > 0 {
if err := app.loadFromDatabase(objects, trueKeys[:j], NOFOLLOW); err != nil {
return nil, err
}
}
result = make([]map[string]interface{}, len(keys))
j = 0
for _, key := range keys {
split := strings.Split(key, ":")
o := objects[split[0]]
if err := o.extractError(); err != nil {
return nil, err
}
if len(split) < 2 || o[K_VERSION] != split[1] {
result[j] = o
j++
}
}
return result[:j], nil
}
func downloadIntoWriter(url string, wr io.Writer) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = io.Copy(wr, resp.Body)
return err
}
func downloadIntoTemp(url, target string) (fname string, typ string, err error) {
var f *os.File
f, err = ioutil.TempFile(filepath.Dir(target), "download_*")
if err != nil {
return
}
defer f.Close()
if err = downloadIntoWriter(url, f); err != nil {
return
}
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return
}
_, typ, err = image.DecodeConfig(f)
if err != nil {
return
}
return f.Name(), typ, nil
}
func shrinkImage(src, tgt, final string, edgeLength int, quality int) error {
cmd := exec.Command("convert", src, "-resize", fmt.Sprintf("%vx%v^>", edgeLength, edgeLength), "-strip", "-quality", fmt.Sprintf("%v", quality), tgt)
log.Printf("Running command: %v", cmd.Args)
if err := cmd.Run(); err != nil {
return err
}
if strings.HasSuffix(tgt, ".png") {
cmd := exec.Command("optipng", tgt)
log.Printf("Running command: %v", cmd.Args)
// out, err := cmd.CombinedOutput(); log.Println(string(out))
if err := cmd.Run(); err != nil {
return err
}
}
si, err := os.Stat(src)
if err != nil {
return err
}
ti, err := os.Stat(tgt)
if err != nil {
return err
}
if final != "" && 10*ti.Size() >= 9*si.Size() {
log.Printf("convert did not save a lot (%v -> %v); symlinking instead...", si.Size(), ti.Size())
if err := os.Remove(tgt); err != nil {
return err
}
if err := os.Symlink(final, tgt); err != nil {
return err
}
}
return nil
}
func ensureDir(path string) error {
if err := os.Mkdir(path, 0755); err != nil {
if err.(*os.PathError).Err.(syscall.Errno) != syscall.EEXIST {
return err
}
}
return nil
}
func (app *DatabaseApp) checkImage(obj object) error {
imageUrl, ok := obj["imageUrl"].(string)
if !ok || imageUrl == "" {
return nil
}
imageHash, ok := obj["imageHash"].(string)
if !ok {
imageHash = ""
}
if i := strings.Index(imageHash, ":"); i != -1 {
imageHash = imageHash[i+1:]
}
computedHash := Sum256Hex([]byte(imageUrl))
if imageHash == computedHash {
return nil
}
fullDir := filepath.Join(app.imgPath, "full", computedHash[:2])
if err := ensureDir(fullDir); err != nil {
return err
}
tmpName, typ, err := downloadIntoTemp(imageUrl, fullDir)
if err != nil {
return err
}
imgType := ".jpg"
if typ == "png" {
cmd := exec.Command("optipng", tmpName)
log.Printf("Running command: %v", cmd.Args)
if err := cmd.Run(); err != nil {
return err
}
imgType = ".png"
}
final := filepath.Join(fullDir, computedHash+imgType)
for res, path := range app.imgPaths {
resDir := filepath.Join(path, computedHash[:2])
if err := ensureDir(resDir); err != nil {
return err
}
tgt := filepath.Join(resDir, computedHash+imgType)
relFinal, err := filepath.Rel(resDir, final)
if err != nil {
return err
}
if err := shrinkImage(tmpName, tgt, relFinal, res, QUALITY); err != nil {
return err
}
}
if err := os.Rename(tmpName, final); err != nil {
return err
}
obj["imageHash"] = imgType[1:] + ":" + computedHash
return nil
}
func (app *AuthorizedApp) processRun(job object) error {
target := job["$target"].(string)
objects := make(objectMap)
// NOFOLLOW because we don't want to load scratchpad's $references, and even less so with a Transformer
if err := app.loadFromDatabase(objects, []string{target}, NOFOLLOW|EXTRACT); err != nil {
return err
}
scratchpad := objects[target]
if scratchpad[K_VERSION] != job["tVersion"] {
return fmt.Errorf("Target version does not equal current version of target: %v != %v", job["tVersion"], scratchpad[K_VERSION])
}
scratchpadRef := scratchpad["$references"].([]interface{})
scratchpadRefSet := make(map[string]bool, len(scratchpadRef))
for _, ref := range scratchpadRef {
scratchpadRefSet[ref.(string)] = true
}
content := scratchpad["content"].(string)
contentLines := strings.Split(content, "\n")
remarks := New()
ods := parseInter(contentLines, remarks)
if err := applyToObjects(app.db, ods, objects, remarks, "ENOENT"); err != nil {
return err
}
// check images and tags, count privileged objects
numPrivileged := 0
for _, od := range ods {
obj := objects[od.initial[1]]
if err := app.checkImage(obj); err != nil {
remarks.AddError(od.start, err.Error())
}
if tags, ok := obj["$tags"].([]interface{}); ok {
if obj["type"] == "statement" && len(tags) < 2 {
remarks.AddHint(od.start, "statement has less than two tags, consider adding tags")
}
}
if _, present := obj["visibility"]; present {
numPrivileged++
}
}
// commit stuff to db if no errors occurred and we aren't just checking
tx, err := app.db.Begin()
if err != nil {
return err
}
inv := make(map[string]bool, 10*len(ods))
datestr := time.Now().Format("2006-01-02 15:04:05")
if job["instruction"] != "check" && remarks.Severity() < ERROR {
newVersion := computeVersionString()
for _, od := range ods {
obj := objects[od.initial[1]]
prevVersion := obj[K_VERSION]
obj[K_VERSION] = newVersion
if err := app.doUpsert(tx, obj, prevVersion); err != nil {
// !!! do not roll back just yet !!!
remarks.AddError(od.start, err.Error())
}
typ := obj[K_TYPE].(string)
// invalidate /latest/type=TYPE/tag=TAG
if ts, ok := obj["$tags"].([]interface{}); ok {
for _, t := range ts {
inv[fmt.Sprintf("/latest/type=%v/tag=%v", typ, t.(string))] = true
}
}
// invalidate /home if TYPE == event
// invalidate /preview/ID if TYPE == event
if typ == "event" {
inv["/home"] = true
inv[fmt.Sprintf("/preview/%v", od.initial[1])] = true
}
if !scratchpadRefSet[od.initial[1]] {
scratchpadRef = append(scratchpadRef, od.initial[1])
scratchpadRefSet[od.initial[1]] = true
}
}
if remarks.Severity() < ERROR {
remarks.AddInfo(-2, "[%v] successfully upserted %v object(s)", datestr, len(ods))
} else {
// !!! we encountered problems for some objects, so rollback everything
tx.Rollback()
// FIXME clear inv...
// and start new transaction for we still want to save the scratchpad
tx, err = app.db.Begin()
if err != nil {
return err
}
}
} else {
errors := remarks.Histo(ERROR)
info := remarks.Histo(INFO) + remarks.Histo(HINT)
if errors > 0 {
remarks.AddInfo(-2, "[%v] Finished with %v error(s); see below", datestr, errors)
} else if info > 0 {
remarks.AddInfo(-2, "[%v] Finished with %v hint(s); see below", datestr, info)
} else {
remarks.AddInfo(-2, "[%v] Finished successfully!", datestr)
}
}
if numPrivileged != 0 {
remarks.AddHint(-1, "objects with explicit visibility: %d", numPrivileged)
}
content = remarks.Embed(contentLines)
scratchpad[K_VERSION] = computeVersionString()
scratchpad["content"] = content
scratchpad["$references"] = scratchpadRef
if err := app.doUpsert(tx, scratchpad, job["tVersion"].(string)); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return err
}
if len(inv) != 0 {
log.Println("Invalidating material views:", inv)
matViewsMap := app.MatViewsMapCopy()
for level, m := range matViewsMap {
l0 := m.Count()
for i := range inv {
m.Remove(i)
}
l1 := m.Count()
log.Printf("Deleted %v entries on level %v (%v remaining)", l0-l1, level, l1)
}
}
// adjust target version so the job is still recognized as "up to date"
job["tVersion"] = scratchpad[K_VERSION]
if remarks.Severity() == ERROR {
return fmt.Errorf("[%v] errors occurred during run, see scratchpad", datestr)
}
return nil
}
func authFromAccount(account object) (*Authorization, error) {
id := account["id"].(string)
privilege, _ := account["privilege"].(string)
level, present := PRIVILEGES[privilege]
if !present {
return nil, fmt.Errorf("Invalid privilege level: %v", account["privilege"])
}
return &Authorization{level: level, id: id, subject: account["email"].(string)}, nil
}
func Authorize(app *DatabaseApp, auth *Authorization) *AuthorizedApp {
return &AuthorizedApp{app, auth, app.MatViewsForLevel(auth.level), nil}
}
func (app *AuthorizedApp) processJobInner(job object) {
// catch any programming errors that lead to a panic to ensure that the job object can be updated properly
defer func() {
if err := recover(); err != nil {
job["error"] = fmt.Sprintf("%v", err)
job[K_STATE] = "failed"
log.Printf("job '%v' failed: %v", job[K_ID], err)
} else {
log.Printf("done processing job: %v", job)
}
}()
var suAuth *Authorization
accountId := job["$owner"].(string)
objects := make(objectMap)
err := app.loadFromDatabase(objects, []string{accountId}, FOLLOW|EXTRACT)
if err == nil {
suAuth, err = authFromAccount(objects[accountId])
}
if err == nil {
log.Printf("Assuming user account: %v", suAuth)
suApp := Authorize(app.DatabaseApp, suAuth)
instruction := job["instruction"]
if instruction == "check" || instruction == "run" {
err = suApp.processRun(job)
} else {
err = fmt.Errorf("Invalid instruction '%v' in job: %v", instruction, job)
}
job[K_STATE] = "done"
} else {
job[K_STATE] = "failed"
}
if err != nil {
job["error"] = err.Error()
}
}
func (app *AuthorizedApp) processJob(job object) {
// catch any database problems that occur when updating the job object
defer func() {
if err := recover(); err != nil {
log.Printf("failure during completion of job '%v': %v", job[K_ID], err)
}
}()
if job[K_STATE] != "pending" && job[K_STATE] != "running" {
return
}
app.processJobInner(job)
prevVersion := job[K_VERSION].(string)
job[K_VERSION] = "done" + computeVersionString()
tx, err := app.db.Begin()
if err != nil {
panic(err)
}
if err := app.doUpsert(tx, job, prevVersion); err != nil {
tx.Rollback()
panic(err)
}
if err := tx.Commit(); err != nil {
panic(err)
}
}
func (app *AuthorizedApp) Worker(no int, sourceChan chan object) {
log.Printf("Worker %v starting", no)
defer log.Printf("Worker %v shutting down", no)
for job := range sourceChan {
log.Printf("Worker %v processing job: %v", no, job)
app.processJob(job)
}
}
func (app *AuthorizedApp) LoadJobsWorker(doneChan chan struct{}) {
targetChan := app.jobQueue
for {
select {
case _ = <-doneChan:
close(targetChan)
break
default:
var ids []string
objects := make(objectMap)
// It was a nice idea only loading pending or running jobs, but we need to clean them jobs, too!
// clauses := `natural join pr_job`
clauses := `where type = "job"`
if err := app.queryDB(objects, clauses, 10000, &ids); err != nil {
log.Fatal("Error in LoadJobsWorker:", err)
}
log.Printf("LoadJobsWorker retrieved %v jobs from db", len(ids))
removals := make([]string, 0, len(ids))
referenceTime := time.Now().Unix() - 24*3600 // delete jobs that are at least a day old
for _, id := range ids {
job := objects[id]
state := job[K_STATE].(string)
version := job[K_VERSION].(string)
// no worries about submitting a job twice; DeliverJobsWorker keeps an "already delivered" list
// submit job regardless of state; so DeliverJobsWorker kann tidy up said list...
targetChan <- job
if state != "running" && state != "pending" {
if ci := strings.IndexRune(version, '+'); ci != -1 {
// e.g., "done+1567094170", cf. computeVersionString
if timestamp, err := strconv.ParseInt(version[ci+1:], 10, 64); err == nil && timestamp <= referenceTime {
removals = append(removals, id)
}
}
}
}
if len(removals) != 0 {
log.Printf("LoadJobsWorker going to remove %d finished jobs from database", len(removals))
tx, err := app.db.Begin()
if err != nil {
panic(err)
}
for _, id := range removals {
err = app.doDelete(tx, id)
if err != nil {
tx.Rollback()
panic(err)
}
}
if err := tx.Commit(); err != nil {
panic(err)
}
log.Println("LoadJobsWorker done removing finished jobs.")