-
Notifications
You must be signed in to change notification settings - Fork 128
/
serverless.go
304 lines (283 loc) 路 7.55 KB
/
serverless.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
package golang
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/yomorun/yomo/cli/serverless"
"github.com/yomorun/yomo/pkg/file"
"github.com/yomorun/yomo/pkg/log"
"golang.org/x/mod/modfile"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/imports"
)
// GolangServerless defines golang implementation of Serverless interface.
type GolangServerless struct {
opts *serverless.Options
source string
output string
tempDir string
}
// Init initializes the serverless
func (s *GolangServerless) Init(opts *serverless.Options) error {
s.opts = opts
if !file.Exists(s.opts.Filename) {
return fmt.Errorf("the file %s doesn't exist", s.opts.Filename)
}
// generate source code
source := file.GetBinContents(s.opts.Filename)
if len(source) < 1 {
return fmt.Errorf(`"%s" content is empty`, s.opts.Filename)
}
opt, err := ParseSrc(s.opts.Filename)
if err != nil {
return fmt.Errorf("parse source code: %s", err)
}
// append main function
ctx := Context{
Name: s.opts.Name,
ZipperAddr: s.opts.ZipperAddr,
Credential: s.opts.Credential,
WithInitFunc: opt.WithInit,
WithWantedTarget: opt.WithWantedTarget,
WithDescription: opt.WithDescription,
WithInputSchema: opt.WithInputSchema,
}
// determine: rx stream serverless or raw bytes serverless.
isRx := strings.Contains(string(source), "rx.Stream")
isWasi := opts.WASI
// main function template
mainFuncTmpl := MainFuncTmpl
// wasi template
if isWasi {
mainFuncTmpl = WasiMainFuncTmpl
}
// rx template
if isRx {
if isWasi {
return errors.New("wasi does not support rx.Stream")
}
mainFuncTmpl = MainFuncRxTmpl
}
mainFunc, err := RenderTmpl(string(mainFuncTmpl), &ctx)
if err != nil {
return fmt.Errorf("Init: %s", err)
}
// merge app source code
source = append(source, mainFunc...)
fset := token.NewFileSet()
astf, err := parser.ParseFile(fset, "", source, parser.ParseComments)
if err != nil {
return fmt.Errorf("Init: parse source file err %s", err)
}
// Add import packages
astutil.AddNamedImport(fset, astf, "", "github.com/yomorun/yomo")
astutil.AddNamedImport(fset, astf, "", "github.com/joho/godotenv")
astutil.AddNamedImport(fset, astf, "", "github.com/spf13/cobra")
astutil.AddNamedImport(fset, astf, "", "github.com/spf13/viper")
if isWasi {
// wasm guest import
astutil.AddNamedImport(fset, astf, "", "github.com/yomorun/yomo/serverless/guest")
}
// Generate the code
code, err := generateCode(fset, astf)
if err != nil {
return fmt.Errorf("Init: generate code err %s", err)
}
// fmt.Println("333.code", string(code))
// Create a temp folder.
tempDir, err := os.MkdirTemp("", "yomo_")
if err != nil {
return err
}
s.tempDir = tempDir
tempFile := filepath.Join(tempDir, "app.go")
// Fix imports
fixedSource, err := imports.Process(tempFile, code, nil)
if err != nil {
return fmt.Errorf("Init: imports %s", err)
}
if err := file.PutContents(tempFile, fixedSource); err != nil {
return fmt.Errorf("Init: write file err %s", err)
}
name := strings.ReplaceAll(opts.Name, " ", "_")
if name == "" {
name = "yomo-sfn"
}
cmd := exec.Command("go", "mod", "init", name)
cmd.Dir = tempDir
env := os.Environ()
// env = append(env, fmt.Sprintf("GO111MODULE=%s", "on"))
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("Init: go mod init err %s", out)
return err
}
s.source = tempFile
return nil
}
// Build compiles the serverless to executable
func (s *GolangServerless) Build(clean bool) error {
// check if the file exists
appPath := s.source
if _, err := os.Stat(appPath); os.IsNotExist(err) {
return fmt.Errorf("the file %s doesn't exist", appPath)
}
// env
env := os.Environ()
// use custom go.mod
if s.opts.ModFile != "" {
mfile, _ := filepath.Abs(s.opts.ModFile)
if !file.Exists(mfile) {
return fmt.Errorf("the mod file %s doesn't exist", mfile)
}
// go.mod
log.WarningStatusEvent(os.Stdout, "Use custom go.mod: %s", mfile)
modContent := file.GetBinContents(mfile)
if len(modContent) == 0 {
return errors.New("go.mod is empty")
}
f, err := modfile.Parse("go.mod", modContent, nil)
if err != nil {
return err
}
for _, r := range f.Replace {
if strings.HasPrefix(r.New.Path, ".") {
abs, err := filepath.Abs(r.New.Path)
if err != nil {
return err
}
modContent = bytes.Replace(modContent, []byte(r.New.Path), []byte(abs), 1)
}
}
// wirte to temp go.mod
tempMod := filepath.Join(s.tempDir, "go.mod")
if err := file.PutContents(tempMod, modContent); err != nil {
return fmt.Errorf("write go.mod err %s", err)
}
// mod download
cmd := exec.Command("go", "mod", "tidy")
cmd.Env = env
cmd.Dir = s.tempDir
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("Build: go mod tidy err %s", out)
return err
}
} else {
// Upgrade modules that provide packages imported by packages in the main module
cmd := exec.Command("go", "get", "-d", "./...")
cmd.Dir = s.tempDir
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("Build: go get err %s", out)
return err
}
}
// build
// wasi
dir, _ := filepath.Split(s.opts.Filename)
filename := "sfn.yomo"
if s.opts.WASI {
filename = "sfn.wasm"
}
sl, _ := filepath.Abs(dir + filename)
// clean build
if clean {
defer func() {
file.Remove(s.tempDir)
}()
}
s.output = sl
cmd := exec.Command("go", "build", "-o", sl, appPath)
// wasi
if s.opts.WASI {
tinygo, err := exec.LookPath("tinygo")
if err != nil {
return errors.New("[tinygo] command was not found. to build the wasm file, you need to install tinygo. For details, visit https://tinygo.org")
}
cmd = exec.Command(tinygo, "build", "-no-debug", "-target", "wasi", "-o", sl, appPath)
}
cmd.Env = env
cmd.Dir = s.tempDir
out, err := cmd.CombinedOutput()
if err != nil {
err = fmt.Errorf("Build: failure, %s %s", cmd.String(), out)
return err
}
return nil
}
// Run compiles and runs the serverless
func (s *GolangServerless) Run(verbose bool) error {
log.InfoStatusEvent(os.Stdout, "Run: %s", s.output)
dir := file.Dir(s.output)
cmd := exec.Command(s.output)
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Args = os.Args
cmd.Dir = dir
err := serverless.LoadEnvFile(dir)
if err != nil {
return err
}
env := os.Environ()
if verbose {
cmd.Env = append(env, "YOMO_LOG_LEVEL=debug")
}
cmd.Env = env
return cmd.Run()
}
// Executable returns true if the serverless is executable
func (s *GolangServerless) Executable() bool {
return true
}
func generateCode(fset *token.FileSet, file *ast.File) ([]byte, error) {
var output []byte
buffer := bytes.NewBuffer(output)
if err := printer.Fprint(buffer, fset, file); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
type AppOpts struct {
WithInit bool
WithWantedTarget bool
WithDescription bool
WithInputSchema bool
}
// ParseSrc parse app option from source code to run serverless
func ParseSrc(appFile string) (*AppOpts, error) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, appFile, nil, parser.SkipObjectResolution)
if err != nil {
return nil, err
}
opts := &AppOpts{}
for _, v := range f.Decls {
if d, ok := v.(*ast.FuncDecl); ok {
switch d.Name.String() {
case "Init":
opts.WithInit = true
case "Description":
opts.WithDescription = true
case "InputSchema":
opts.WithInputSchema = true
case "WantedTarget":
opts.WithWantedTarget = true
}
}
}
return opts, nil
}
func init() {
serverless.Register(&GolangServerless{}, ".go")
}