github.com/wmuizelaar/kpt@v0.0.0-20221018115725-bd564717b2ed/internal/fnruntime/nodejs.go (about) 1 // Copyright 2022 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package fnruntime 16 17 import ( 18 "fmt" 19 "io" 20 "os" 21 "path/filepath" 22 23 fnresult "github.com/GoogleContainerTools/kpt/pkg/api/fnresult/v1" 24 ) 25 26 const ( 27 WasmPathEnv = "KPT_FN_WASM_PATH" 28 ) 29 30 type WasmNodejsFn struct { 31 NodeJsRunner *ExecFn 32 loader WasmLoader 33 } 34 35 func NewNodejsFn(loader WasmLoader) (*WasmNodejsFn, error) { 36 cacheDir := filepath.Join(os.TempDir(), "kpt-wasm-fn") 37 err := os.MkdirAll(cacheDir, 0755) 38 if err != nil { 39 return nil, fmt.Errorf("unable to create cache dir: %w", err) 40 } 41 tempDir, err := os.MkdirTemp(cacheDir, "nodejs-") 42 if err != nil { 43 return nil, fmt.Errorf("unable to create temp dir: %w", err) 44 } 45 jsPath := filepath.Join(tempDir, "kpt-fn-wasm-glue-runner.js") 46 if err = os.WriteFile(jsPath, []byte(golangWasmJSCode+glueCode), 0644); err != nil { 47 return nil, fmt.Errorf("unable to write the js glue code file: %w", err) 48 } 49 50 wasmFile, err := loader.getFilePath() 51 if err != nil { 52 return nil, err 53 } 54 55 f := &WasmNodejsFn{ 56 NodeJsRunner: &ExecFn{ 57 Path: "node", 58 Args: []string{jsPath}, 59 Env: map[string]string{ 60 WasmPathEnv: wasmFile, 61 }, 62 FnResult: &fnresult.Result{}, 63 }, 64 loader: loader, 65 } 66 return f, nil 67 } 68 69 func (f *WasmNodejsFn) Run(r io.Reader, w io.Writer) error { 70 if err := f.NodeJsRunner.Run(r, w); err != nil { 71 return fmt.Errorf("failed to run wasm with node.js: %w", err) 72 } 73 return f.loader.cleanup() 74 }