-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.go
377 lines (318 loc) · 9.09 KB
/
server.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
package compilers
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"strings"
"github.com/eris-ltd/eris-compilers/Godeps/_workspace/src/github.com/ebuchman/go-shell-pipes"
"github.com/eris-ltd/eris-compilers/Godeps/_workspace/src/github.com/eris-ltd/common/go/common"
"github.com/eris-ltd/eris-compilers/Godeps/_workspace/src/github.com/go-martini/martini"
"github.com/eris-ltd/eris-compilers/Godeps/_workspace/src/github.com/martini-contrib/gorelic"
"github.com/eris-ltd/eris-compilers/Godeps/_workspace/src/github.com/martini-contrib/secure"
segment "github.com/eris-ltd/eris-compilers/Godeps/_workspace/src/github.com/segmentio/analytics-go"
)
var (
NEWRELIC_KEY = os.Getenv("NEWRELIC_KEY")
NEWRELIC_APP = os.Getenv("NEWRELIC_APP")
SEGMENT_KEY = os.Getenv("SEGMENT_KEY")
)
// must have compiler installed!
func homeDir() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
return usr.HomeDir
}
// Server cache location in eris tree
var ServerCache = path.Join(common.LllcScratchPath, "server")
// Handler for proxy requests (ie. a compile request from langauge other than go)
func ProxyHandler(w http.ResponseWriter, r *http.Request) {
// read the request body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Errorln("err on read http request body", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("body:", string(body))
req := new(ProxyReq)
err = json.Unmarshal(body, req)
if err != nil {
logger.Errorln("err on read http request body", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var resp *Response
if req.Literal {
resp = CompileLiteral(req.Source, req.Language)
} else {
resp = Compile(req.Source, req.Libraries)
}
respJ, err := json.Marshal(resp)
if err != nil {
logger.Errorln("failed to marshal", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Write(respJ)
}
// Main http request handler
// Read request, compile, build response object, write
func CompileHandler(w http.ResponseWriter, r *http.Request) {
resp := compileResponse(w, r)
if resp == nil {
return
}
respJ, err := json.Marshal(resp)
if err != nil {
logger.Errorln("failed to marshal", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Write(respJ)
}
// Convenience wrapper for javascript frontend
func CompileHandlerJs(w http.ResponseWriter, r *http.Request) {
resp := compileResponse(w, r)
if resp == nil {
return
}
respJ, err := json.Marshal(resp)
if err != nil {
logger.Errorln("failed to marshal", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Write(respJ)
}
// read in the files from the request, compile them
func compileResponse(w http.ResponseWriter, r *http.Request) *Response {
// read the request body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Errorln("err on read http request body", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
// unmarshall body into req struct
req := new(Request)
err = json.Unmarshal(body, req)
if err != nil {
logger.Errorln("err on json unmarshal of request", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
logger.Debugf("New Request =>\t\t%v\n", req)
resp := compileServerCore(req)
// track
if SEGMENT_KEY != "" {
informSegment(req.Language, r)
}
return resp
}
// core compile functionality. used by the server and locally to mimic the server
func compileServerCore(req *Request) *Response {
lang := req.Language
compiler := Languages[lang]
c := req.Script
if c == nil || len(c) == 0 {
return NewResponse("", nil, "", fmt.Errorf("No script provided"))
}
// take sha256 of request object to get tmp filename
hash := sha256.Sum256(c)
filename := path.Join(ServerCache, compiler.Ext(hex.EncodeToString(hash[:])))
maybeCached := true
// lllc requires a file to read
// check if filename already exists. if not, write
if _, err := os.Stat(filename); err != nil {
ioutil.WriteFile(filename, c, 0644)
logger.Debugln(filename, "does not exist. Writing")
maybeCached = false
}
// loop through includes, also save to drive
var includes []string
for k, v := range req.Includes {
filename := path.Join(ServerCache, compiler.Ext(k))
if _, err := os.Stat(filename); err != nil {
maybeCached = false
}
includes = append(includes, filepath.Base(filename))
ioutil.WriteFile(filename, v, 0644)
}
// check cache
if maybeCached {
r, err := checkCache(filename) // TODO: use checkCached?
if err == nil {
return r
}
}
//compile scripts, return bytecode and error
resp := CompileWrapper(filename, lang, includes, req.Libraries)
// cache
if resp.Error == "" {
// iterate over the array
for _, r := range resp.Objects {
// TODO: cache results using the cacheFile?
cacheResult(r.Objectname, r.Bytecode, r.ABI)
}
}
return resp
}
func informSegment(lang string, r *http.Request) {
seg := segment.New(SEGMENT_KEY)
con := make(map[string]interface{})
ip := strings.Split(r.RemoteAddr, ":")[0]
con["ip"] = ip
prp := make(map[string]interface{})
prp["name"] = lang
prp["path"] = "/compile/" + lang
prp["url"] = DefaultUrl + lang
t := &segment.Page{
Context: con,
Traits: prp,
AnonymousId: ip,
// Category: lang,
Name: "Compile lang: " + lang,
}
logger.Debugln("Sending notification to Segment.")
seg.Page(t)
}
func commandWrapper_(prgrm string, args []string) (string, error) {
a := fmt.Sprint(args)
logger.Infoln(fmt.Sprintf("Running command %s %s ", prgrm, a))
cmd := exec.Command(prgrm, args...)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return "", err
}
outstr := out.String()
// get rid of new lines at the end
outstr = strings.TrimSpace(outstr)
return outstr, nil
}
func commandWrapper(tokens ...string) (string, error) {
s, err := pipes.RunStrings(tokens...)
s = strings.TrimSpace(s)
return s, err
}
// wrapper to cli
func CompileWrapper(filename string, lang string, includes []string, libraries string) *Response {
// we need to be in the same dir as the files for sake of includes
cur, _ := os.Getwd()
dir := path.Dir(filename)
dir, _ = filepath.Abs(dir)
filename = path.Base(filename)
if _, ok := Languages[lang]; !ok {
return NewResponse(filename, nil, "", UnknownLang(lang))
}
os.Chdir(dir)
defer func() {
os.Chdir(cur)
}()
tokens := Languages[lang].Cmd(filename, includes, libraries)
hexCode, err := commandWrapper(tokens...)
if err != nil {
logger.Errorln("Couldn't compile!!", err)
logger.Errorf("Command =>\t\t\t%v\n", tokens)
return NewResponse(filename, nil, "", err)
}
var resp *Response
// attempt to decode as a solc json return structure
solcResp := new(SolcResponse)
err = json.Unmarshal([]byte(hexCode), solcResp)
if err == nil {
respItemArray := make([]ResponseItem, 1)
for contract, item := range solcResp.Contracts {
b, err := hex.DecodeString(item.Bin)
if err == nil {
respItem := ResponseItem{
Objectname: contract,
Bytecode: b,
ABI: item.Abi,
}
respItemArray = append(respItemArray, respItem)
}
}
return &Response{
Objects: respItemArray,
Error: "",
}
} else {
// if doesn't work, then not a solc response
tokens = Languages[lang].Abi(filename, includes)
jsonAbi, err := commandWrapper(tokens...)
if err != nil {
logger.Errorln("Couldn't produce abi doc!!", err)
// we swallow this error, but maybe we shouldnt...
}
b, err := hex.DecodeString(hexCode)
if err != nil {
// in that case, the bytecode is not valid, so it should be flagged.
resp = NewResponse(filename, nil, "", err)
} else {
resp = NewResponse(filename, b, jsonAbi, nil)
}
}
return resp
}
// Start the compile server
func StartServer(addrUnsecure, addrSecure, key, cert string) {
martini.Env = martini.Prod
srv := martini.New()
srv.Use(martini.Logger())
srv.Use(martini.Recovery())
// Static files
srv.Use(martini.Static("./web"))
// Routes
r := martini.NewRouter()
srv.MapTo(r, (*martini.Routes)(nil))
srv.Action(r.Handle)
r.Post("/compile", CompileHandler)
r.Post("/compile2", CompileHandlerJs)
// new relic for error reporting
if NEWRELIC_KEY != "" {
logger.Infoln("Starting new relic.")
gorelic.InitNewrelicAgent(NEWRELIC_KEY, NEWRELIC_APP, false)
srv.Use(gorelic.Handler)
}
// Use SSL ?
if addrSecure == "" {
srv.RunOnAddr(addrUnsecure)
} else {
srv.Use(secure.Secure(secure.Options{
SSLRedirect: true,
SSLHost: addrSecure,
}))
// HTTP
if addrUnsecure != "" {
go func() {
if err := http.ListenAndServe(addrUnsecure, srv); err != nil {
fmt.Println("Cannot serve on http port: ", err)
os.Exit(1)
}
}()
}
// HTTPS
if err := http.ListenAndServeTLS(addrSecure, cert, key, srv); err != nil {
fmt.Println("Cannot serve on https port: ", err)
os.Exit(1)
}
}
}
// Start the proxy server
// Dead simple json-rpc so we can compile code from languages other than go
func StartProxy(addr string) {
srv := martini.Classic()
srv.Post("/", ProxyHandler)
srv.RunOnAddr(addr)
}