Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Dockerコンテナの立ち上げとコード転送の実装 #11

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ require (
github.com/opencontainers/image-spec v1.0.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
golang.org/x/net v0.0.0-20220630215102-69896b714898 // indirect
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e // indirect
golang.org/x/net v0.0.0-20220708220712-1185a9018129 // indirect
golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d // indirect
)
4 changes: 4 additions & 0 deletions server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLL
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20220630215102-69896b714898 h1:K7wO6V1IrczY9QOQ2WkVpw4JQSwCd52UsxVEirZUfiw=
golang.org/x/net v0.0.0-20220630215102-69896b714898/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.0.0-20220708220712-1185a9018129 h1:vucSRfWwTsoXro7P+3Cjlr6flUMtzCwzlvkxEQtHHB0=
golang.org/x/net v0.0.0-20220708220712-1185a9018129/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand All @@ -47,6 +49,8 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e h1:CsOuNlbOuf0mzxJIefr6Q4uAUetRUwZE4qt7VfzP+xo=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d h1:/m5NbqQelATgoSPVC2Z23sR4kVNokFwDDyWh/3rGY+I=
golang.org/x/sys v0.0.0-20220708085239-5a0f0661e09d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
Expand Down
133 changes: 133 additions & 0 deletions server/service/docker/build.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package docker

import (
"archive/tar"
"bufio"
"bytes"
"context"
"encoding/json"
"github.com/docker/docker/api/types"
"io/ioutil"
"log"
"os"
"strings"
)

func BuildDockerImage(ImageName string, ContainerTag string) (parsed ParsedBuildOutput, err error) {

buildOpts := types.ImageBuildOptions{
Dockerfile: ImageName,
Tags: []string{ContainerTag},
}

res, err := cli.ImageBuild(
context.Background(),
makeArchivedDockerfile(ImageName),
buildOpts,
)
if err != nil {
return
}
defer res.Body.Close()

body, _ := ioutil.ReadAll(res.Body)
//fmt.Println(string(body), res)
parsed, err = buildOutPutParser(string(body))
if err != nil {
return
}

return
}

// DockerはtarでまとめられたDockerfileしか受け取らないのでtarでまとめる
func makeArchivedDockerfile(fileName string) *bytes.Reader {
f, err := os.Open(fileName)
if err != nil {
log.Panic(err)
}
defer func() {
if err := f.Close(); err != nil {
log.Panic(err)
}
}()
b, err := ioutil.ReadAll(f)
if err != nil {
log.Panic(err)
}

// archive Dockerfile
tarHeader := &tar.Header{
Name: fileName,
Size: int64(len(b)),
}
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
defer tw.Close()
err = tw.WriteHeader(tarHeader)
if err != nil {
log.Panic(err)
}
_, err = tw.Write(b)
if err != nil {
log.Panic(err)
}

return bytes.NewReader(buf.Bytes())
}

type buildOutput struct {
Stream string `json:"stream"`
Aux auxID `json:"aux"`
}

type auxID struct {
ID string `json:"ID"`
}

type ParsedBuildOutput struct {
Log string
ImageID string
}

/*
DockerのImage Buildの出力はJSON形式で、
{"stream": "出力"}
{"aux": {"ID": "sha256"}}

*/
func buildOutPutParser(Out string) (res ParsedBuildOutput, err error) {
var readLine []string

// ビルドの出力を1行ごとに分解する
reader := bufio.NewReader(strings.NewReader(Out))
for {
l, err := reader.ReadString('\n')
if err != nil {
break
}

readLine = append(readLine, l)
}

var parsedOutPutStrings []string
for _, v := range readLine {
tmp := buildOutput{}
// 出力はJSONなのでパース
err := json.Unmarshal([]byte(v), &tmp)
if err != nil {
return ParsedBuildOutput{}, err
}

parsedOutPutStrings = append(parsedOutPutStrings, tmp.Stream)
if tmp.Aux.ID != "" {
// ビルドされたImageのIDの出力の先頭に sha256: がついているのでカット
res.ImageID = tmp.Aux.ID[7:]
}
}

// 出力を連結
res.Log = strings.Join(parsedOutPutStrings, "")

return
}
14 changes: 14 additions & 0 deletions server/service/docker/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package docker

import "github.com/docker/docker/client"

var cli *client.Client

func NewDockerClient() (err error) {
cli, err = client.NewClientWithOpts(client.FromEnv)
if err != nil {
return err
}

return nil
}
58 changes: 58 additions & 0 deletions server/service/docker/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package docker

import (
"bufio"
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"os"
"os/exec"
)

func CreateContainer(ImageID string, ContainerName string, Env []string, AppID string) (containerID string, warnings []string, err error) {
containerConfig := &container.Config{
Env: Env,
Image: ImageID,
}

create, err := cli.ContainerCreate(context.Background(), containerConfig, &container.HostConfig{}, nil, nil, ContainerName)
if err != nil {
return
}

_, err = makeTarBall(AppID)
if err != nil {
return
}

err = sendCodeToContainer(cli, create.ID, AppID)
if err != nil {
return
}

return create.ID, create.Warnings, nil
}

func sendCodeToContainer(cli *client.Client, ContainerID string, AppID string) error {
archive, _ := os.Open(AppID + ".tar")
defer archive.Close()

return cli.CopyToContainer(context.Background(), ContainerID, "/", bufio.NewReader(archive), types.CopyToContainerOptions{})
}

/*
コンテナにファイルをコピーするにはtarアーカイブで無ければいけないのでtarにまとめる
.git/は除外
*/
func makeTarBall(AppID string) (Log string, err error) {
command := fmt.Sprintf("cd %s;tar --exclude .git -cf ../%s.tar *", AppID, AppID)
l, err := exec.Command("sh", "-c", command).CombinedOutput()
if err != nil {
return
}

Log = string(l)
return
}
14 changes: 14 additions & 0 deletions server/service/docker/start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package docker

import (
"context"
"github.com/docker/docker/api/types"
)

func StartContainer(ContainerID string) error {
err := cli.ContainerStart(context.Background(), ContainerID, types.ContainerStartOptions{})
if err != nil {
return err
}
return nil
}