/
eek.go
359 lines (292 loc) · 8.63 KB
/
eek.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
package eek
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"plugin"
"reflect"
"regexp"
"runtime"
"strings"
)
type eekType int
const (
eekTypeSimple eekType = iota
eekTypeComplex
)
var (
regexFileName = regexp.MustCompile("[^A-Za-z0-9]+")
)
// Eek is main type used on the evaluation
type Eek struct {
name string
functions []Func
variables []Var
packages []string
evaluationType eekType
operation string
baseBuildPath string
buildPath string
buildFilePath string
UseCachedBuildForSameFormula bool
}
// Func is reflect to a single typed reusable function
type Func struct {
Name string
BodyFunction string
}
// Var is reflect to a single typed variable with/without a default value
type Var struct {
Name string
Type string
DefaultValue interface{}
}
// ExecVar is used on defining value in the evaluation
type ExecVar map[string]interface{}
// New used to create eek object. This function accept an optional variable that will be used as the evaluation name
func New(args ...string) *Eek {
eek := new(Eek)
if len(args) > 0 {
eek.SetName(args[0])
}
eek.functions = make([]Func, 0)
eek.variables = make([]Var, 0)
eek.packages = make([]string, 0)
eek.evaluationType = eekTypeSimple
eek.UseCachedBuildForSameFormula = true
eek.setDefaultBaseBuildPath()
return eek
}
func (e *Eek) setDefaultBaseBuildPath() {
basePath := ""
tmpFolderName := "go-eek-plugins"
switch runtime.GOOS {
case "darwin", "freebsd", "linux":
basePath = os.Getenv("TMPDIR")
if basePath == "" {
tempFolder := "/tmp"
if tempBasePath := filepath.Join(tempFolder, tmpFolderName); e.isPathExists(tempBasePath) {
basePath = tempFolder
} else if err := os.MkdirAll(tempBasePath, os.ModePerm); err == nil {
basePath = tempFolder
}
}
case "windows":
basePath = os.Getenv("TEMP")
default:
}
if basePath == "" {
basePath = "./"
}
defaultBaseBuildPath := filepath.Join(basePath, tmpFolderName)
e.SetBaseBuildPath(defaultBaseBuildPath)
}
// SetName set the evaluation name
func (e *Eek) SetName(name string) {
e.name = name
}
// SetBaseBuildPath set the base build path. Every so file generated from build will be stored into <baseBuildPath>/<name>/<name>.so
func (e *Eek) SetBaseBuildPath(baseBuildPath string) {
e.baseBuildPath = baseBuildPath
}
// ImportPackage specify which packages will be imported
func (e *Eek) ImportPackage(dependencies ...string) {
e.packages = append(e.packages, dependencies...)
}
// DefineVariable used to define variables that will be used in the operation
func (e *Eek) DefineVariable(variable Var) {
e.variables = append(e.variables, variable)
}
// DefineFunction used to define reusable functions that will be used in the operation
func (e *Eek) DefineFunction(fun Func) {
e.functions = append(e.functions, fun)
}
// PrepareEvaluation prepare the layout of evaluation string
func (e *Eek) PrepareEvaluation(operation string) {
e.evaluationType = eekTypeSimple
e.operation = strings.TrimSpace(operation)
}
// Build build the evaluation
func (e *Eek) Build() error {
if e.name == "" {
return fmt.Errorf("name is mandatory")
} else if e.evaluationType != eekTypeSimple && e.evaluationType != eekTypeComplex {
return fmt.Errorf("evaluationType is invalid")
} else if e.operation == "" {
return fmt.Errorf("evaluation cannot be empty")
}
var code string
var err error
switch e.evaluationType {
case eekTypeSimple:
code, err = e.buildSimpleEvaluation()
case eekTypeComplex:
code, err = e.buildComplexEvaluation()
default:
return nil
}
if err != nil {
return err
}
// write code into temporary file, then build the code as go plugin file
if err := e.writeToFileThenBuild(code); err != nil {
return err
}
return nil
}
func (e *Eek) buildSimpleEvaluation() (string, error) {
// code base code
code := strings.TrimSpace(`
package main
$packages
$functions
$variables
func Evaluate() interface{} {
$operation
}
`)
// inject packages
packageLayout := ""
for _, each := range e.packages {
if each == "" {
continue
}
packageLayout = fmt.Sprintf("%s\n\"%s\"", packageLayout, each)
}
packageLayout = fmt.Sprintf(strings.TrimSpace(`import (%s)`), strings.TrimSpace(packageLayout))
code = strings.Replace(code, "$packages", packageLayout, 1)
// inject functions
functionLayout := ""
for _, each := range e.functions {
bodyFunc := strings.TrimSpace(each.BodyFunction)
if each.Name == "" || bodyFunc == "" {
continue
}
functionLayout = fmt.Sprintf("%s\nvar %s = %s", functionLayout, each.Name, bodyFunc)
}
code = strings.Replace(code, "$functions", strings.TrimSpace(functionLayout), 1)
// inject variables
variableLayout := ""
for _, each := range e.variables {
if each.Name == "" || each.Type == "" {
continue
}
if prefix := strings.ToUpper(string(each.Name[0])); prefix != string(each.Name[0]) {
return "", fmt.Errorf("defined variable must be exported. %s must be %s%s", each.Name, prefix, each.Name[1:])
}
if each.DefaultValue == nil {
variableLayout = fmt.Sprintf("%s\n%s %s", variableLayout, each.Name, each.Type)
} else {
switch each.DefaultValue.(type) {
case string:
variableLayout = fmt.Sprintf("%s\n%s %s = \"%v\"", variableLayout, each.Name, each.Type, each.DefaultValue)
default:
variableLayout = fmt.Sprintf("%s\n%s %s = %v", variableLayout, each.Name, each.Type, each.DefaultValue)
}
}
}
variableLayout = fmt.Sprintf(strings.TrimSpace(`var (%s)`), strings.TrimSpace(variableLayout))
code = strings.Replace(code, "$variables", variableLayout, 1)
// inject operation
code = strings.Replace(code, "$operation", e.operation, 1)
return code, nil
}
func (e *Eek) buildComplexEvaluation() (string, error) {
return "", fmt.Errorf("currently complex evaluation is still not supported")
}
func (e *Eek) writeToFileThenBuild(code string) error {
name := regexFileName.ReplaceAllString(e.name, "_")
e.buildPath = filepath.Join(e.baseBuildPath, name)
e.buildFilePath = filepath.Join(e.buildPath, fmt.Sprintf("%s_%s.so", name, e.md5(code)))
if e.UseCachedBuildForSameFormula {
if e.isPathExists(e.buildFilePath) {
return nil
}
}
os.RemoveAll(e.buildPath)
err := os.MkdirAll(e.buildPath, os.ModePerm)
if err != nil {
return err
}
mainFilePath := filepath.Join(e.buildPath, "main.go")
err = ioutil.WriteFile(mainFilePath, []byte(code), os.ModePerm)
if err != nil {
return err
}
op := fmt.Sprintf("cd %s && go build -buildmode=plugin -o %s", e.buildPath, filepath.Base(e.buildFilePath))
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin", "freebsd", "linux":
cmd = exec.Command("bash", "-c", op)
case "windows":
cmd = exec.Command("cmd", "/C", op)
default:
return fmt.Errorf("unsupported operating system")
}
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s: %s", err.Error(), output)
}
return nil
}
// Evaluate execute using particular data
func (e *Eek) Evaluate(data ExecVar) (interface{}, error) {
if !e.isPathExists(e.buildFilePath) {
return nil, fmt.Errorf("build file is not found. please try to rebuild the formula")
}
p, err := plugin.Open(e.buildFilePath)
if err != nil {
return nil, err
}
for varName, varValue := range data {
lookedUpVar, err := p.Lookup(varName)
if err != nil {
return nil, err
}
(func() {
// recover panic error from reflect operation
defer func() {
if recovered := recover(); recovered != nil {
recoveredInString := fmt.Sprintf("%v", recovered)
recoveredInString = strings.Replace(recoveredInString, "reflect.Set: value of type ", "", -1)
recoveredInString = strings.Replace(recoveredInString, "is not assignable to type ", "", -1)
if parts := strings.Split(recoveredInString, " "); len(parts) == 2 {
err = fmt.Errorf("Error on setting value of variable %s (type %s) with value %v (type %s)", varName, parts[0], varValue, parts[1])
} else {
err = fmt.Errorf("%v", recoveredInString)
}
}
}()
// line underneath has a protential to generate a panic error
// reflect.Set: value of type int is not assignable to type float64
reflect.ValueOf(lookedUpVar).Elem().Set(reflect.ValueOf(varValue))
})()
if err != nil {
return nil, err
}
}
lookedUpEvaluate, err := p.Lookup("Evaluate")
if err != nil {
return nil, err
}
result := lookedUpEvaluate.(func() interface{})()
return result, nil
}
func (*Eek) md5(str string) string {
hasher := md5.New()
_, err := hasher.Write([]byte(str))
if err != nil {
return ""
}
return hex.EncodeToString(hasher.Sum(nil))
}
func (e *Eek) isPathExists(str string) bool {
if _, err := os.Stat(str); err == nil {
return true
}
return false
}