-
Notifications
You must be signed in to change notification settings - Fork 9
/
state.go
191 lines (159 loc) · 5.09 KB
/
state.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
// Package state contains a thread safe state struct that stores information
// about the edged
package state
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"os"
"strings"
"sync"
"github.com/spf13/viper"
"github.com/buger/jsonparser"
"github.com/gladiusio/gladius-edged/edged/p2p/handler"
"github.com/rs/zerolog/log"
)
// New returns a new state struct
func New(p2pHandler *handler.P2PHandler) *State {
state := &State{running: true, content: &contentStore{make(map[string]*websiteContent)}, runChannel: make(chan bool), p2p: p2pHandler}
state.startContentSyncWatcher()
return state
}
// State is a thread safe struct for keeping information about the edged
type State struct {
p2p *handler.P2PHandler
running bool
content *contentStore
runChannel chan (bool)
mux sync.Mutex
}
type contentStore struct {
websites map[string]*websiteContent
}
func (c contentStore) getContentList() []string {
contentList := make([]string, 0)
for websiteName, wc := range c.websites {
for assetName := range wc.assets {
contentList = append(contentList, strings.Join([]string{websiteName, assetName}, "/"))
}
}
return contentList
}
func (c contentStore) getWebsite(name string) *websiteContent {
return c.websites[name]
}
func (c contentStore) createWebsite(name string) *websiteContent {
wc := &websiteContent{make(map[string][]byte)}
c.websites[name] = wc
return wc
}
type websiteContent struct {
assets map[string][]byte
}
func (w websiteContent) getAsset(name string) []byte {
return w.assets[name]
}
func (w *websiteContent) createAsset(name string, content []byte) {
w.assets[name] = content
}
type status struct {
Running bool
Version string
}
func (s *State) GetAsset(website, asset string) []byte {
s.mux.Lock()
// Lock so only one goroutine at a time can access the map
defer s.mux.Unlock()
w := s.content.getWebsite(website)
if w != nil {
return w.getAsset(asset)
}
return nil
}
func (s *State) Info() string {
s.mux.Lock()
defer s.mux.Unlock()
status := &status{Running: s.running}
jsonString, _ := json.Marshal(status)
return string(jsonString)
}
type networkContent struct {
contentName string
contentLocations []string
}
type contentList struct {
Content []string `json:"content"`
}
func (c *contentList) Marshal() string {
b, _ := json.Marshal(c)
return string(b)
}
// getNeededFromControld asks the controld what we need
func getNeededFromControld(content []string) []string {
c := &contentList{Content: content}
resp, err := postToControld("/p2p/state/content_diff", c.Marshal())
if err != nil {
log.Warn().Err(err).Msg("Problem getting needed content list from network gateway")
return []string{}
}
body, _ := ioutil.ReadAll(resp.Body)
contentNeeded := make([]string, 0)
// Get every string in the response (our needed content)
jsonparser.ArrayEach(body, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
contentNeeded = append(contentNeeded, string(value))
}, "response")
return contentNeeded
}
// getContentLocationsFromControld gets a list of networkContent objects
func getContentLocationsFromControld(content []string) []*networkContent {
c := &contentList{Content: content}
resp, err := postToControld("/p2p/state/content_links", c.Marshal())
if err != nil {
log.Warn().Err(err).Msg("Problem getting links for needed content from network gateway")
return []*networkContent{&networkContent{}}
}
body, _ := ioutil.ReadAll(resp.Body)
ncList := make([]*networkContent, 0)
// Get all of the files
jsonparser.ObjectEach(body, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
nc := &networkContent{contentName: string(key), contentLocations: make([]string, 0)}
// Get all of the links for that file
jsonparser.ArrayEach(value, func(v []byte, dataType jsonparser.ValueType, offset int, err error) {
nc.contentLocations = append(nc.contentLocations, string(v))
})
// Add this to the network content list
ncList = append(ncList, nc)
return nil
}, "response")
return ncList
}
func postToControld(endpoint, message string) (*http.Response, error) {
controldBase := viper.GetString("NetworkGatewayProtocol") + "://" + viper.GetString("NetworkGatewayHostname") + ":" + viper.GetString("NetworkGatewayPort") + "/api"
byteMessage := []byte(message)
return http.Post(controldBase+endpoint, "application/json", bytes.NewBuffer(byteMessage))
}
// getContentList returns a list of the content we have on disk in the format of:
// <website name>/<fileName>
func (s *State) getContentList() []string {
s.mux.Lock()
defer s.mux.Unlock()
return s.content.getContentList()
}
func getContentDir() (string, error) {
contentDir := viper.GetString("ContentDirectory")
if contentDir == "" {
return contentDir, errors.New("No content directory specified")
} else {
if _, err := os.Stat(contentDir); os.IsNotExist(err) {
err := os.MkdirAll(contentDir, os.ModePerm)
if err != nil {
log.Error().Err(err).Msg("Could not create content directory")
return "", errors.New("Could not create content directory")
}
return contentDir, nil
}
}
return contentDir, nil
}