utils.go (1225B)
1 package main 2 3 import ( 4 "fmt" 5 "log/slog" 6 "net/http" 7 "os" 8 "path" 9 10 "go.lair.cx/functions/configs" 11 "go.lair.cx/functions/internal/httpx" 12 ) 13 14 func getRootfsPath(namespace, name string) (string, error) { 15 expectedPath := path.Join( 16 configs.FuncDir, 17 namespace, 18 name, 19 ) 20 21 if _, err := os.Stat(expectedPath); err != nil { 22 return "", err 23 } 24 25 return expectedPath, nil 26 } 27 28 func checkFilesInDir(dir string, files ...string) bool { 29 for _, file := range files { 30 if _, err := os.Stat(path.Join(dir, file)); err != nil { 31 return false 32 } 33 } 34 35 return true 36 } 37 38 // runFunction invokes the function and sends shutdown signal. 39 func runFunction( 40 client *http.Client, 41 headers http.Header, 42 body []byte, 43 then func(*http.Response) error, 44 ) error { 45 resp, err := httpx.Request( 46 http.MethodPost, 47 "http://localhost/", 48 body, 49 ). 50 WithHeaders(headers). 51 Do(client) 52 53 // We need to shutdown the machine anyway. 54 _, shutdownErr := client.Get("http://localhost/shutdown") 55 if shutdownErr != nil { 56 slog.Error("failed to shutdown the machine.", "error", err) 57 58 // TODO: Shutdown forcefully if the machine is not responding. 59 } 60 61 if err != nil { 62 return fmt.Errorf("function request failed: %w", err) 63 } 64 65 return then(resp) 66 }