/
parameter.go
740 lines (678 loc) · 19.2 KB
/
parameter.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
package admin
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"unicode"
"gopkg.in/yaml.v3"
. "github.com/onlineconf/onlineconf/admin/go/common"
)
var (
ErrAccessDenied = errors.New("Access denied")
ErrAlreadyExists = errors.New("Parameter already exists")
ErrVersionNotMatch = errors.New("Version not match")
ErrCommentRequired = errors.New("Comment required")
ErrInvalidValue = errors.New("Invalid value")
ErrNotEmpty = errors.New("Parameter has children")
ErrNotFound = errors.New("Parameter not found")
ErrParentNotFound = errors.New("Parent not found")
)
const selectFields string = `
SELECT t.ID, t.Name, t.ParentID, t.Path, t.Value, t.ContentType, t.Summary, t.Description, t.Version, t.MTime, t.Deleted,
(SELECT count(*) FROM my_config_tree c WHERE c.ParentID = t.ID AND NOT c.Deleted) AS NumChildren,
(SELECT count(*) <> 0 FROM my_config_tree_group g WHERE g.NodeID = t.ID) AS AccessModified,
my_config_tree_access(t.ID, ?) AS RW,
my_config_tree_notification(t.ID) AS Notification,
t.Notification IS NOT NULL AS NotificationModified
`
const selectFromConfig string = selectFields + `
FROM my_config_tree t
`
type Parameter struct {
ID int `json:"-"`
Name string `json:"name"`
ParentID sql.NullInt64 `json:"-"`
Path string `json:"path"`
Value NullString `json:"data"`
ContentType string `json:"mime"`
Summary string `json:"summary"`
Description string `json:"description"`
Version int `json:"version"`
MTime string `json:"mtime"`
Deleted bool `json:"-"`
NumChildren int `json:"num_children"`
AccessModified bool `json:"access_modified"`
RW NullBool `json:"rw"`
Notification string `json:"notification"`
NotificationModified bool `json:"notification_modified"`
}
func SelectParameter(ctx context.Context, path string) (*Parameter, error) {
query := selectFromConfig + "WHERE Path = ? AND NOT Deleted\n"
row := DB.QueryRowContext(ctx, query, Username(ctx), path)
p := Parameter{}
err := row.Scan(
&p.ID, &p.Name, &p.ParentID, &p.Path, &p.Value, &p.ContentType,
&p.Summary, &p.Description, &p.Version, &p.MTime, &p.Deleted,
&p.NumChildren, &p.AccessModified, &p.RW, &p.Notification, &p.NotificationModified,
)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
if !p.RW.Valid {
p.Value = NullString{}
}
return &p, nil
}
func SelectParameterFollowingSymlink(ctx context.Context, path string) (*Parameter, error) {
return selectParameterFollowingSymlink(ctx, path, map[string]bool{})
}
func selectParameterFollowingSymlink(ctx context.Context, path string, seen map[string]bool) (*Parameter, error) {
if seen[path] {
return nil, nil
}
seen[path] = true
defer delete(seen, path)
parameter, err := SelectParameter(ctx, path)
if err != nil {
return nil, err
}
if parameter != nil {
return parameter, nil
}
realPath := ""
segments := strings.Split(path, "/")[1:]
for i, s := range segments {
realPath += "/" + s
if i < len(segments)-1 {
parameter, err = selectParameterResolvingSymlink(ctx, realPath, seen)
} else {
parameter, err = selectParameterFollowingSymlink(ctx, realPath, seen)
}
if err != nil {
return nil, err
}
if parameter == nil {
return nil, nil
}
realPath = parameter.Path
}
return parameter, nil
}
func SelectParameterResolvingSymlink(ctx context.Context, path string) (*Parameter, error) {
return selectParameterResolvingSymlink(ctx, path, map[string]bool{})
}
func selectParameterResolvingSymlink(ctx context.Context, path string, seen map[string]bool) (*Parameter, error) {
parameter, err := selectParameterFollowingSymlink(ctx, path, seen)
if err != nil {
return nil, err
}
if parameter == nil {
return nil, nil
}
if parameter.ContentType == "application/x-symlink" {
seen[path] = true
defer delete(seen, path)
return selectParameterResolvingSymlink(ctx, parameter.Value.String, seen)
}
return parameter, nil
}
type ParameterWithDescendants interface {
GetParameter() *Parameter
AddChild(Parameter)
}
func selectChildren(ctx context.Context, params []ParameterWithDescendants) error {
paramsMap := make(map[int]ParameterWithDescendants, len(params))
ids := make([]interface{}, 0, len(params))
for _, param := range params {
p := param.GetParameter()
if p.NumChildren != 0 {
ids = append(ids, p.ID)
paramsMap[p.ID] = param
}
}
if len(ids) == 0 {
return nil
}
marks := make([]string, len(ids))
for i := range marks {
marks[i] = "?"
}
marksStr := strings.Join(marks, ", ")
query := selectFromConfig + `
WHERE ParentID IN (` + marksStr + `) AND NOT Deleted
ORDER BY Name
`
binds := append([]interface{}{Username(ctx)}, ids...)
rows, err := DB.QueryContext(ctx, query, binds...)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
c := Parameter{}
err := rows.Scan(
&c.ID, &c.Name, &c.ParentID, &c.Path, &c.Value, &c.ContentType,
&c.Summary, &c.Description, &c.Version, &c.MTime, &c.Deleted,
&c.NumChildren, &c.AccessModified, &c.RW, &c.Notification, &c.NotificationModified,
)
if err != nil {
return err
}
if !c.RW.Valid {
c.Value = NullString{}
}
parent := paramsMap[int(c.ParentID.Int64)]
parent.AddChild(c)
}
return nil
}
type ParameterWithChildren struct {
Parameter
Children []Parameter `json:"children"`
}
func (p *ParameterWithChildren) GetParameter() *Parameter {
return &p.Parameter
}
func (p *ParameterWithChildren) AddChild(child Parameter) {
p.Children = append(p.Children, child)
}
func SelectChildren(ctx context.Context, params []*ParameterWithChildren) error {
paramsIf := make([]ParameterWithDescendants, 0, len(params))
for _, p := range params {
p.Children = []Parameter{}
paramsIf = append(paramsIf, p)
}
return selectChildren(ctx, paramsIf)
}
func (p *Parameter) WithChildren(ctx context.Context) (*ParameterWithChildren, error) {
pc := ParameterWithChildren{Parameter: *p}
err := SelectChildren(ctx, []*ParameterWithChildren{&pc})
if err != nil {
return nil, err
}
return &pc, nil
}
type ParameterWithSubtree struct {
Parameter
Children []ParameterWithSubtree `json:"children"`
}
func (p *ParameterWithSubtree) GetParameter() *Parameter {
return &p.Parameter
}
func (p *ParameterWithSubtree) AddChild(child Parameter) {
p.Children = append(p.Children, ParameterWithSubtree{Parameter: child})
}
func SelectSubtree(ctx context.Context, params []*ParameterWithSubtree) error {
paramsIf := make([]ParameterWithDescendants, 0, len(params))
for _, p := range params {
p.Children = []ParameterWithSubtree{}
paramsIf = append(paramsIf, p)
}
err := selectChildren(ctx, paramsIf)
if err != nil {
return err
}
children := make([]*ParameterWithSubtree, 0)
for _, p := range params {
for i := range p.Children {
children = append(children, &p.Children[i])
}
}
if len(children) == 0 {
return nil
}
return SelectSubtree(ctx, children)
}
func (p *Parameter) WithSubtree(ctx context.Context) (*ParameterWithSubtree, error) {
ps := ParameterWithSubtree{Parameter: *p}
err := SelectSubtree(ctx, []*ParameterWithSubtree{&ps})
if err != nil {
return nil, err
}
return &ps, nil
}
func SelectWithChildrenMulti(ctx context.Context, paths []string) (map[string]*ParameterWithChildren, error) {
if len(paths) == 0 {
return map[string]*ParameterWithChildren{}, nil
}
pathMap := make(map[string]bool, len(paths))
binds := []interface{}{Username(ctx)}
for _, path := range paths {
binds = append(binds, path)
pathMap[path] = true
}
for _, path := range paths {
binds = append(binds, path)
}
marks := make([]string, len(paths))
for i := range marks {
marks[i] = "?"
}
marksStr := strings.Join(marks, ", ")
rows, err := DB.QueryContext(ctx, selectFields+`
FROM (
SELECT t.*
FROM my_config_tree t
WHERE t.Path IN (`+marksStr+`)
UNION
SELECT t.*
FROM my_config_tree t
JOIN my_config_tree p ON p.ID = t.ParentID
WHERE p.Path IN (`+marksStr+`)
) t
WHERE NOT t.Deleted
ORDER BY t.Path
`, binds...)
if err != nil {
return nil, err
}
defer rows.Close()
result := make(map[string]*ParameterWithChildren)
for rows.Next() {
var p Parameter
err := rows.Scan(
&p.ID, &p.Name, &p.ParentID, &p.Path, &p.Value, &p.ContentType,
&p.Summary, &p.Description, &p.Version, &p.MTime, &p.Deleted,
&p.NumChildren, &p.AccessModified, &p.RW, &p.Notification, &p.NotificationModified,
)
if err != nil {
return nil, err
}
if !p.RW.Valid {
p.Value = NullString{}
}
if pathMap[p.Path] {
result[p.Path] = &ParameterWithChildren{
Parameter: p,
Children: []Parameter{},
}
}
if p.Path != "/" {
parentPath, _ := splitPath(p.Path)
if _, ok := result[parentPath]; ok {
result[parentPath].Children = append(result[parentPath].Children, p)
}
}
}
return result, nil
}
func SearchParameters(ctx context.Context, term string) ([]Parameter, error) {
like := "%" + likeEscape(term) + "%"
publicSearch := `Summary LIKE ? OR Description LIKE ?`
bind := []interface{}{Username(ctx), like, like, like, like, like}
isASCII := strings.IndexFunc(term, func(r rune) bool { return r > unicode.MaxASCII }) == -1
if isASCII {
publicSearch = `Name COLLATE ascii_general_ci LIKE ? OR ` + publicSearch
bind = append(bind, like, like)
}
rows, err := DB.QueryContext(ctx, `
SELECT * FROM (
`+selectFromConfig+`
WHERE NOT Deleted
AND (`+publicSearch+` OR Value COLLATE utf8mb4_unicode_ci LIKE ?)
ORDER BY Path
) x
WHERE RW IS NOT NULL
OR (`+publicSearch+`)
`, bind...)
if err != nil {
return nil, err
}
defer rows.Close()
list := make([]Parameter, 0)
for rows.Next() {
var p Parameter
err := rows.Scan(
&p.ID, &p.Name, &p.ParentID, &p.Path, &p.Value, &p.ContentType,
&p.Summary, &p.Description, &p.Version, &p.MTime, &p.Deleted,
&p.NumChildren, &p.AccessModified, &p.RW, &p.Notification, &p.NotificationModified,
)
if err != nil {
return nil, err
}
if !p.RW.Valid {
p.Value = NullString{}
}
list = append(list, p)
}
return list, nil
}
func CreateParameter(ctx context.Context, path, contentType, value string, optSummary, optDescription, optNotification NullString, comment string) error {
var nullValue NullString
if contentType != "application/x-null" {
nullValue.Valid = true
nullValue.String = value
}
if err := validateParameter(ctx, contentType, nullValue); err != nil {
return err
}
var notification NullString
if optNotification.Valid {
if err := validateNotification(ctx, optNotification.String); err != nil {
return err
}
if optNotification.String != "" {
notification.Valid = true
notification.String = optNotification.String
}
}
tx, err := DB.BeginTx(ctx, nil)
if err != nil {
return err
}
parentPath, name := splitPath(path)
parent, err := selectParameterForUpdate(ctx, tx, parentPath)
if err != nil {
tx.Rollback()
if err == ErrNotFound {
return ErrParentNotFound
}
return err
}
row := tx.QueryRowContext(ctx, "SELECT Deleted FROM my_config_tree WHERE Path = ? FOR UPDATE", path)
var deleted bool
err = row.Scan(&deleted)
if err == sql.ErrNoRows {
_, err = tx.ExecContext(ctx, "INSERT INTO my_config_tree (ParentID, Name, ContentType, Value, Summary, Description, Notification) VALUES (?, ?, ?, ?, ?, ?, ?)",
parent.ID, name, contentType, nullValue, optSummary.String, optDescription.String, notification)
} else if err == nil {
if !deleted {
tx.Rollback()
return ErrAlreadyExists
}
fields := "ContentType = ?, Value = ?, "
bind := []interface{}{contentType, nullValue}
if optSummary.Valid {
fields += "Summary = ?, "
bind = append(bind, optSummary.String)
}
if optDescription.Valid {
fields += "Description = ?, "
bind = append(bind, optDescription.String)
}
if optNotification.Valid {
fields += "Notification = ?, "
bind = append(bind, notification)
}
bind = append(bind, path)
_, err = tx.ExecContext(ctx, "UPDATE my_config_tree SET "+fields+"Version = Version + 1, MTime = now(), Deleted = false WHERE Path = ?", bind...)
}
if err == nil {
err = LogLastVersion(ctx, tx, path, comment)
}
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func SetParameter(ctx context.Context, path string, version int, contentType string, value string, comment string) error {
var nullValue NullString
if contentType != "application/x-null" {
nullValue.Valid = true
nullValue.String = value
}
if err := validateParameter(ctx, contentType, nullValue); err != nil {
return err
}
tx, err := DB.BeginTx(ctx, nil)
if err != nil {
return err
}
p, err := selectParameterForUpdate(ctx, tx, path)
if err != nil {
tx.Rollback()
return err
}
if p.Version != version {
tx.Rollback()
return ErrVersionNotMatch
}
_, err = tx.ExecContext(ctx, "UPDATE my_config_tree SET ContentType = ?, Value = ?, Version = Version + 1, MTime = now() WHERE Path = ?", contentType, nullValue, path)
if err == nil {
err = LogLastVersion(ctx, tx, path, comment)
}
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func MoveParameter(ctx context.Context, path string, newPath string, symlink bool, version int, comment string) error {
newParentPath, newName := splitPath(newPath)
tx, err := DB.BeginTx(ctx, nil)
if err != nil {
return err
}
p, err := selectParameterForUpdate(ctx, tx, path)
if err != nil {
tx.Rollback()
return err
}
newParent, err := selectParameterForUpdate(ctx, tx, newParentPath)
if err != nil {
tx.Rollback()
if err == ErrNotFound {
return ErrParentNotFound
}
return err
}
if p.Version != version {
tx.Rollback()
return ErrVersionNotMatch
}
_, err = tx.ExecContext(ctx, "UPDATE my_config_tree SET ParentID = ?, Name = ?, Version = Version + 1, MTime = now() WHERE Path = ?", newParent.ID, newName, path)
if err == nil {
likePath := likeEscape(p.Path) + "/%"
_, err = tx.ExecContext(ctx, "UPDATE my_config_tree SET Path = '' WHERE Path LIKE ?", likePath)
}
if err == nil {
err = LogLastVersion(ctx, tx, newPath, fmt.Sprintf("Moved from %s. %s", path, comment))
}
if err == nil && symlink {
var nullNotification NullString
if p.NotificationModified {
nullNotification.Valid = true
nullNotification.String = p.Notification
}
_, err = tx.ExecContext(ctx, "INSERT INTO my_config_tree (ParentID, Name, ContentType, Value, Notification) VALUES (?, ?, ?, ?, ?)",
p.ParentID, p.Name, "application/x-symlink", newPath, nullNotification)
if err == nil {
err = LogLastVersion(ctx, tx, path, fmt.Sprintf("Moved to %s. %s", newPath, comment))
}
}
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func SetParameterDescription(ctx context.Context, path string, summary, description string) error {
tx, err := DB.BeginTx(ctx, nil)
if err != nil {
return err
}
_, err = selectParameterForUpdate(ctx, tx, path)
if err != nil {
tx.Rollback()
return err
}
_, err = tx.ExecContext(ctx, "UPDATE my_config_tree SET Summary = ?, Description = ? WHERE Path = ?", summary, description, path)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func SetParameterNotification(ctx context.Context, path string, notification string) error {
if err := validateNotification(ctx, notification); err != nil {
return err
}
var nullNotification NullString
if notification != "" {
nullNotification.Valid = true
nullNotification.String = notification
}
tx, err := DB.BeginTx(ctx, nil)
if err != nil {
return err
}
_, err = selectParameterForUpdate(ctx, tx, path)
if err != nil {
tx.Rollback()
return err
}
_, err = tx.ExecContext(ctx, "UPDATE my_config_tree SET Notification = ? WHERE Path = ?", nullNotification, path)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func DeleteParameter(ctx context.Context, path string, version int, comment string) error {
tx, err := DB.BeginTx(ctx, nil)
if err != nil {
return err
}
p, err := selectParameterForUpdate(ctx, tx, path)
if err != nil {
tx.Rollback()
return err
}
if p.Version != version {
tx.Rollback()
return ErrVersionNotMatch
}
row := tx.QueryRowContext(ctx, "SELECT count(*) FROM my_config_tree WHERE ParentID = ? AND Deleted = false", p.ID)
var count int
err = row.Scan(&count)
if err != nil {
tx.Rollback()
return err
} else if count != 0 {
tx.Rollback()
return ErrNotEmpty
}
_, err = tx.ExecContext(ctx, "UPDATE my_config_tree SET Deleted = true, Version = Version + 1, MTime = now() WHERE Path = ?", path)
if err == nil {
err = ClearAccess(ctx, tx, p.ID)
}
if err == nil {
err = LogLastVersion(ctx, tx, path, comment)
}
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func selectParameterForUpdate(ctx context.Context, tx *sql.Tx, path string) (*Parameter, error) {
row := tx.QueryRowContext(ctx, selectFromConfig+"WHERE Path = ? AND NOT Deleted FOR UPDATE", Username(ctx), path)
p := Parameter{}
err := row.Scan(
&p.ID, &p.Name, &p.ParentID, &p.Path, &p.Value, &p.ContentType,
&p.Summary, &p.Description, &p.Version, &p.MTime, &p.Deleted,
&p.NumChildren, &p.AccessModified, &p.RW, &p.Notification, &p.NotificationModified,
)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrNotFound
}
return nil, err
}
if !(p.RW.Valid && p.RW.Bool) {
return nil, ErrAccessDenied
}
return &p, nil
}
func validateParameter(ctx context.Context, contentType string, value NullString) error {
switch contentType {
case "application/x-null":
if value.Valid {
return ErrInvalidValue
} else {
return nil
}
case "text/plain", "application/x-list", "application/x-server", "application/x-server2", "application/x-template":
if value.Valid {
return nil
} else {
return ErrInvalidValue
}
case "application/json":
if !value.Valid {
return ErrInvalidValue
}
var i interface{}
return json.Unmarshal([]byte(value.String), &i)
case "application/x-yaml":
if !value.Valid {
return ErrInvalidValue
}
var i interface{}
return yaml.Unmarshal([]byte(value.String), &i)
case "application/x-symlink":
if !value.Valid {
return ErrInvalidValue
}
target, err := SelectParameterFollowingSymlink(ctx, value.String)
if err != nil {
return err
} else if target == nil {
return ErrInvalidValue
} else {
return nil
}
case "application/x-case":
if !value.Valid {
return ErrInvalidValue
}
var cases []map[string]NullString
if err := json.Unmarshal([]byte(value.String), &cases); err != nil {
return err
}
def := 0
for _, c := range cases {
i := 0
for _, key := range []string{"server", "group", "datacenter", "service"} {
if c[key].Valid {
i++
if c[key].String == "" {
return ErrInvalidValue
}
}
}
if i == 0 {
def++
} else if i > 1 {
return ErrInvalidValue
}
if err := validateParameter(ctx, c["mime"].String, c["value"]); err != nil {
return err
}
}
if def > 1 {
return ErrInvalidValue
}
return nil
default:
return ErrInvalidValue
}
}
func validateNotification(ctx context.Context, notification string) error {
if notification == "none" {
root, err := UserIsRoot(ctx, Username(ctx))
if err != nil {
return err
} else if !root {
return ErrAccessDenied
}
}
return nil
}