/
onpremise.go
222 lines (197 loc) · 6.27 KB
/
onpremise.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
package servers
import (
"encoding/json"
"fmt"
"html"
"net/http"
"path"
"regexp"
"sync"
"time"
"github.com/getsumio/getsum/internal/config"
. "github.com/getsumio/getsum/internal/config"
"github.com/getsumio/getsum/internal/logger"
"github.com/getsumio/getsum/internal/status"
. "github.com/getsumio/getsum/internal/supplier"
"github.com/getsumio/getsum/internal/validation"
"github.com/google/uuid"
)
//server instance to run in server mode
type OnPremiseServer struct {
StoragePath string
mux *sync.RWMutex
suppliers map[string]Supplier
}
var factory ISupplierFactory
const uuidPattern = "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$"
var regex *regexp.Regexp = regexp.MustCompile(uuidPattern)
//when we have 50 concurrent request or i.e. 15 concurrent + 35 failed in the past
//timedout suppliers will be terminated
const default_capacity = 50
//start server in given config listen address and port or tls details
func (s *OnPremiseServer) Start(config *config.Config) error {
logger.Level = logger.LevelInfo
factory = new(SupplierFactory)
s.suppliers = make(map[string]Supplier)
s.mux = &sync.RWMutex{}
http.HandleFunc("/", s.handle)
listenAddress := fmt.Sprintf("%s:%d", *config.Listen, *config.Port)
var err error
if *config.TLSKey != "" {
err = http.ListenAndServeTLS(listenAddress, *config.TLSCert, *config.TLSKey, nil)
} else {
err = http.ListenAndServe(listenAddress, nil)
}
if err != nil {
return err
}
return nil
}
//get executed to reach status
//so collect status if there is any runner
func handleGet(s *OnPremiseServer, w http.ResponseWriter, r *http.Request, id string) {
//check if any runner
s.mux.RLock()
defer s.mux.RUnlock()
logger.Info("Checking if there is a process with id : %s", id)
supplier, ok := s.suppliers[id]
if !ok {
handleError("There is no running process", w)
return
}
//collect status and return
stat := supplier.Status()
status, err := json.Marshal(stat)
if err != nil {
handleError("System can not parse given status %s", w, err.Error())
return
}
logger.Info("Returning status %v", *stat)
w.Write(status)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST,GET,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "application/json")
}
//post executed to Run a new calculation
func handlePost(s *OnPremiseServer, w http.ResponseWriter, r *http.Request) {
s.mux.Lock()
defer s.mux.Unlock()
//read the config from request
jsonDecoder := json.NewDecoder(r.Body)
config := &Config{}
err := jsonDecoder.Decode(config)
if err != nil {
handleError("Can not read given config %s", w, err.Error())
return
}
//validate config
err = validation.ValidateConfig(config, true)
if err != nil {
handleError(err.Error(), w)
return
}
//get supplier instance, only single algo supported on server mode
var algorithm = ValueOf(&config.Algorithm[0])
config.Dir = &s.StoragePath
supplier, err := factory.GetSupplierByAlgo(config, &algorithm)
if err != nil {
handleError("Can not create algorithm runner instance: "+err.Error(), w)
return
}
processId := uuid.New().String()
stat := supplier.Status()
stat.Type = status.STARTED
stat.Value = processId
jsonStat, err := json.Marshal(*stat)
if err != nil {
handleError("Can not parse status"+err.Error(), w)
return
}
w.Write(jsonStat)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS,POST,GET,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "content-type,accept,origin")
supplier.Data().StartTime = time.Now()
go supplier.Run()
s.suppliers[processId] = supplier
logger.Info("Process started")
s.ensureCapacity()
}
func handleOptions(s *OnPremiseServer, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS,POST,GET,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "content-type,accept,origin")
w.Header().Set("Allow", "OPTIONS,GET,POST,DELETE")
}
//terminates running calculation
func handleDelete(s *OnPremiseServer, w http.ResponseWriter, r *http.Request, id string) {
s.mux.Lock()
defer s.mux.Unlock()
supplier, ok := s.suppliers[id]
if !ok {
handleError("There is no running process", w)
return
}
supplier.Terminate()
supplier.Delete()
w.WriteHeader(http.StatusOK)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS,POST,GET,DELETE")
w.Header().Set("Access-Control-Allow-Headers", "content-type,accept,origin")
delete(s.suppliers, id)
logger.Info("Process terminated")
}
//delegates GET POST DELETE main server listener
func (s *OnPremiseServer) handle(w http.ResponseWriter, r *http.Request) {
logger.LogRequest(r)
switch r.Method {
case "GET":
requestId := path.Base(html.EscapeString(r.URL.Path))
if !regex.MatchString(requestId) {
logger.Error("Request is not a valid request id! %s", requestId)
w.WriteHeader(http.StatusNotFound)
return
}
handleGet(s, w, r, requestId)
case "POST":
handlePost(s, w, r)
case "OPTIONS":
handleOptions(s, w, r)
case "DELETE":
requestId := path.Base(html.EscapeString(r.URL.Path))
if !regex.MatchString(requestId) {
logger.Error("Request is not a valid request id! %s", requestId)
w.WriteHeader(http.StatusNotFound)
return
}
handleDelete(s, w, r, requestId)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
logger.Error("Can not handle request method rejecting request")
}
}
//utility to write given error to response
func handleError(message string, w http.ResponseWriter, params ...interface{}) {
if params != nil {
message = fmt.Sprintf(message, params...)
}
logger.Error("An unexpected error occured %s", message)
status := &status.Status{Type: status.ERROR, Value: message}
jsonStatus, _ := json.Marshal(status)
w.Write(jsonStatus)
return
}
func (s *OnPremiseServer) ensureCapacity() {
if len(s.suppliers) >= default_capacity {
now := time.Now()
for k := range s.suppliers {
supplier := s.suppliers[k]
if int(now.Sub(supplier.Data().StartTime).Seconds()) > (supplier.Data().TimeOut * 2) {
logger.Info("Removing orphaned process: %v", supplier.Status())
supplier.Terminate()
supplier.Delete()
delete(s.suppliers, k)
}
}
}
}