-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
151 lines (123 loc) · 4.03 KB
/
main.go
File metadata and controls
151 lines (123 loc) · 4.03 KB
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
package main
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
slicer "github.com/slicervm/sdk"
)
const sampleInput = `hello from host
this file will be copied into the VM
then transformed to upper-case
`
func main() {
baseURL := envOrDefault("SLICER_URL", "http://192.168.1.34:8080")
token := os.Getenv("SLICER_TOKEN")
hostGroup := envOrDefault("SLICER_HOST_GROUP", "vm")
tag := envOrDefault("FILE_TRANSFER_TAG", fmt.Sprintf("file-transfer-%d", time.Now().Unix()))
inputContent := envOrDefault("FILE_TRANSFER_INPUT", sampleInput)
outputName := envOrDefault("FILE_TRANSFER_OUTPUT", "processed.txt")
if token == "" {
fmt.Println("SLICER_TOKEN is required")
os.Exit(1)
}
client := slicer.NewSlicerClient(baseURL, token, "slicer-file-transfer/1.0", nil)
createCtx, createCancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer createCancel()
node, err := client.CreateVM(createCtx, hostGroup, slicer.SlicerCreateNodeRequest{
Tags: []string{tag},
})
if err != nil {
fmt.Printf("create VM failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("created VM: hostname=%s ip=%s tag=%s\n", node.Hostname, node.IP, tag)
execCtx, execCancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer execCancel()
if err := waitForVMReady(execCtx, client, node.Hostname); err != nil {
fmt.Printf("VM not ready yet: %v\n", err)
os.Exit(1)
}
localInput := "input-" + node.Hostname + ".txt"
if err := os.WriteFile(localInput, []byte(inputContent), 0o600); err != nil {
fmt.Printf("write local input failed: %v\n", err)
os.Exit(1)
}
if err := client.CpToVM(execCtx, node.Hostname, localInput, "/home/ubuntu/input.txt", 1000, 1000, "600", "binary"); err != nil {
fmt.Printf("copy input to VM failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("copied local file to VM: %s -> /home/ubuntu/input.txt\n", localInput)
out, err := runFileTransform(execCtx, client, node.Hostname)
if err != nil {
fmt.Printf("transform command failed: %v\n", err)
if strings.TrimSpace(out) != "" {
fmt.Printf("transform output:\n%s\n", strings.TrimSpace(out))
}
os.Exit(1)
}
localOutput := "output-" + node.Hostname + ".txt"
if err := client.CpFromVM(execCtx, node.Hostname, "/home/ubuntu/output.txt", localOutput, "600", "binary"); err != nil {
fmt.Printf("copy output from VM failed: %v\n", err)
os.Exit(1)
}
result, err := os.ReadFile(localOutput)
if err != nil {
fmt.Printf("read local output failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("transform output copied to: ./%s\n", localOutput)
fmt.Printf("content:\n%s", string(result))
if outputName != "" && outputName != localOutput {
if err := os.WriteFile(outputName, result, 0o600); err != nil {
fmt.Printf("rename output failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("also written to: ./%s\n", outputName)
}
}
func waitForVMReady(ctx context.Context, client *slicer.SlicerClient, nodeName string) error {
retryDelay := 10 * time.Millisecond
for attempt := 1; ; attempt++ {
if ctx.Err() != nil {
return ctx.Err()
}
if _, err := client.GetAgentHealth(ctx, nodeName, false); err == nil {
return nil
}
if attempt%5 == 0 {
fmt.Printf("attempt %d: VM not ready yet\n", attempt)
}
select {
case <-time.After(retryDelay):
case <-ctx.Done():
return ctx.Err()
}
}
}
func runFileTransform(ctx context.Context, client *slicer.SlicerClient, nodeName string) (string, error) {
// Upper-case transform to demonstrate processing on the VM.
cmd := client.CommandContext(ctx, nodeName, "bash", "-lc",
"tr '[:lower:]' '[:upper:]' < /home/ubuntu/input.txt > /home/ubuntu/output.txt")
cmd.UID = 1000
cmd.GID = 1000
stdout, err := cmd.Output()
if err != nil {
if exitErr := new(slicer.ExitError); errors.As(err, &exitErr) && len(exitErr.Stderr) > 0 {
return string(stdout) + string(exitErr.Stderr), err
}
return string(stdout), err
}
if len(strings.TrimSpace(string(stdout))) == 0 {
return "", nil
}
return string(stdout), nil
}
func envOrDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}