tener endpoint y cositas

This commit is contained in:
Cat /dev/Nulo 2023-05-22 12:17:20 -03:00
parent 9a457d3258
commit 08097035e4

71
main.go
View file

@ -22,29 +22,50 @@ import (
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.POST("/run", run)
e.GET("/", hello)
runVM()
// e.Logger.Fatal(e.Start(":8080"))
e.Logger.Fatal(e.Start(":8080"))
}
func hello(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
type runResp struct {
VmId string
}
func runVM() {
const socketPath = "/tmp/firecracker.sock"
func run(c echo.Context) error {
script, err := ioutil.ReadAll(c.Request().Body)
if err != nil {
panic(err)
}
vmid, agent, m := startVM()
err = agent.run(script)
if err != nil {
return err
}
go func() {
ctx := context.Background()
if err := m.Wait(ctx); err != nil {
panic(err)
}
}()
defer agent.off()
return c.JSON(http.StatusOK, runResp{
VmId: vmid,
})
}
func startVM() (string, agentConfig, *firecracker.Machine) {
nanid, err := nanoid.Standard(21)
if err != nil {
panic(err)
}
vmid := nanid()
secret := nanid()
socketPath := "/tmp/firecracker-" + vmid + ".sock"
cfg := firecracker.Config{
SocketPath: socketPath,
@ -91,8 +112,6 @@ func runVM() {
panic(fmt.Errorf("failed to create new machine: %v", err))
}
defer os.Remove(cfg.SocketPath)
if err := m.Start(ctx); err != nil {
panic(fmt.Errorf("failed to initialize machine: %v", err))
}
@ -100,7 +119,7 @@ func runVM() {
ip := m.Cfg.NetworkInterfaces[0].StaticConfiguration.IPConfiguration.IPAddr.IP
log.Printf("IP: %s", ip.String())
defer m.StopVMM()
// defer m.StopVMM()
agent := agentConfig{ip: ip.String(), secret: secret}
@ -108,17 +127,18 @@ func runVM() {
log.Panic(err)
}
if err := agent.run("#!/bin/sh\necho hola mundo"); err != nil {
log.Println(err)
}
if err := agent.run("#!/bin/sh\nreboot"); err != nil {
log.Println(err)
}
go func() {
ctx := context.Background()
if err := m.Wait(ctx); err != nil {
panic(err)
}
os.Remove(cfg.SocketPath)
}()
// if err := m.Wait(ctx); err != nil {
// panic(err)
// }
return vmid, agent, m
}
type agentConfig struct {
@ -135,8 +155,8 @@ func (a agentConfig) request() *http.Request {
return req
}
func (a agentConfig) run(script string) error {
req, err := http.NewRequest("POST", "http://"+a.ip+":8080/run", bytes.NewBuffer([]byte(script)))
func (a agentConfig) run(script []byte) error {
req, err := http.NewRequest("POST", "http://"+a.ip+":8080/run", bytes.NewBuffer(script))
req.Header.Set("Authorization", "Bearer "+a.secret)
if err != nil {
panic(err)
@ -145,7 +165,6 @@ func (a agentConfig) run(script string) error {
if err != nil {
return err
}
log.Println(res.Body)
byt, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
@ -155,6 +174,10 @@ func (a agentConfig) run(script string) error {
return nil
}
func (a agentConfig) off() error {
return a.run([]byte("#!/bin/sh\nreboot"))
}
func (a agentConfig) waitForAgent() error {
client := http.Client{
Timeout: time.Millisecond * 50,