/
mdbFieldDirectory.go
94 lines (86 loc) · 2.14 KB
/
mdbFieldDirectory.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
package filegen
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"time"
"github.com/Cloud-Foundations/Dominator/lib/log"
"github.com/Cloud-Foundations/Dominator/lib/mdb"
)
var (
machineType = reflect.TypeOf(mdb.Machine{})
)
type mdbFieldDirectoryType struct {
directory string
index []int
tagKey string
}
func makeGenerator(field string) (*mdbFieldDirectoryType, error) {
if fParts := strings.Split(field, "."); len(fParts) == 2 {
if fParts[0] == "Tags" {
return &mdbFieldDirectoryType{tagKey: fParts[1]}, nil
}
}
structField, found := machineType.FieldByName(field)
if !found {
return nil, fmt.Errorf(
"field: \"%s\" not found in mdb.Machine type", field)
}
if structField.Type.Kind() != reflect.String {
return nil, fmt.Errorf(
"field: \"%s\" is not string type", field)
}
return &mdbFieldDirectoryType{index: structField.Index}, nil
}
func sendNotifications(notifierChannel chan<- string,
interval time.Duration) {
for ; ; time.Sleep(interval) {
notifierChannel <- ""
}
}
func (m *Manager) registerMdbFieldDirectoryForPath(pathname string,
field, directory string, interval time.Duration) error {
generator, err := makeGenerator(field)
if err != nil {
return err
}
generator.directory = directory
notifierChannel := m.RegisterGeneratorForPath(pathname,
generator)
if interval <= 0 {
close(notifierChannel)
return nil
}
go sendNotifications(notifierChannel, interval)
return nil
}
func (g *mdbFieldDirectoryType) Generate(machine mdb.Machine,
logger log.Logger) ([]byte, time.Time, error) {
var fieldValue string
if g.tagKey != "" {
fieldValue = machine.Tags[g.tagKey]
} else {
fieldValue = reflect.ValueOf(machine).FieldByIndex(
g.index).String()
}
if fieldValue == "" {
fieldValue = "*"
}
pathname := filepath.Join(g.directory,
filepath.Clean(fieldValue))
if data, err := ioutil.ReadFile(pathname); err != nil {
if os.IsNotExist(err) && fieldValue != "*" {
data, err := ioutil.ReadFile(filepath.Join(g.directory,
"*"))
if err == nil {
return data, time.Time{}, nil
}
}
return nil, time.Time{}, err
} else {
return data, time.Time{}, nil
}
}