Deploy stack automatically when supplied

This commit is contained in:
Marcos Lilljedahl
2017-05-15 16:09:13 -03:00
parent a6c19e451f
commit 5dd56a2886
2 changed files with 34 additions and 3 deletions

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net/http"
"path"
"github.com/play-with-docker/play-with-docker/config"
"github.com/play-with-docker/play-with-docker/services"
@@ -33,6 +34,9 @@ func NewSession(rw http.ResponseWriter, req *http.Request) {
//TODO: Return some error code
} else {
s.StackFile = stack
if stack != "" {
go deployStack(s)
}
hostname := fmt.Sprintf("%s.%s", config.PWDCName, req.Host)
// If request is not a form, return sessionId in the body
if req.Header.Get("X-Requested-With") == "XMLHttpRequest" {
@@ -44,3 +48,22 @@ func NewSession(rw http.ResponseWriter, req *http.Request) {
http.Redirect(rw, req, fmt.Sprintf("http://%s/p/%s", hostname, s.Id), http.StatusFound)
}
}
func deployStack(s *services.Session) {
i, err := services.NewInstance(s, services.InstanceConfig{})
if err != nil {
log.Printf("Error creating instance for stack [%s]: %s\n", s.StackFile, err)
}
err = i.UploadFromURL("https://raw.githubusercontent.com/play-with-docker/stacks/master" + s.StackFile)
if err != nil {
log.Printf("Error uploading stack file [%s]: %s\n", s.StackFile, err)
}
fileName := path.Base(s.StackFile)
code, err := services.Exec(i.Name, []string{"docker-compose", "-f", "/var/run/pwd/uploads/" + fileName, "up", "-d"})
if err != nil {
log.Printf("Error executing stack [%s]: %s\n", s.StackFile, err)
}
log.Printf("Stack execution finished with code %d\n", code)
}

View File

@@ -10,6 +10,7 @@ import (
"os"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
@@ -350,9 +351,16 @@ func Exec(instanceName string, command []string) (int, error) {
if err != nil {
return 0, err
}
ins, err := c.ContainerExecInspect(context.Background(), e.ID)
if err != nil {
return 0, err
var ins types.ContainerExecInspect
for _ = range time.Tick(1 * time.Second) {
ins, err = c.ContainerExecInspect(context.Background(), e.ID)
if ins.Running {
continue
}
if err != nil {
return 0, err
}
break
}
return ins.ExitCode, nil