Skip to content

Commit 134d29b

Browse files
committed
Fix logic
1 parent 7135564 commit 134d29b

File tree

10 files changed

+188
-148
lines changed

10 files changed

+188
-148
lines changed

builder/docker.go

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"fmt"
66
"log/slog"
7+
"strconv"
78

89
"github.com/docker/docker/api/types"
910
"github.com/docker/docker/api/types/container"
@@ -23,17 +24,17 @@ func NewDocker(logger *slog.Logger, cli *client.Client) *Docker {
2324
return &Docker{cli: cli, logger: logger}
2425
}
2526

26-
// Build builds docker image.
27-
func (d Docker) Build(ctx context.Context, file string) (string, error) {
28-
tar, err := archive.TarWithOptions("infra/", &archive.TarOptions{})
27+
// ImageBuild builds docker image.
28+
func (d Docker) ImageBuild(ctx context.Context, dst, name string) (string, error) {
29+
tar, err := archive.TarWithOptions(dst, &archive.TarOptions{})
2930
if err != nil {
3031
return "", fmt.Errorf("failed to create tar: %w", err)
3132
}
3233

33-
tag := "ihippik/go-lambda:v1.0.0"
34+
tag := "go-lambda:" + name
3435

3536
opts := types.ImageBuildOptions{
36-
Dockerfile: file,
37+
Dockerfile: "Dockerfile",
3738
Tags: []string{tag},
3839
Remove: true,
3940
}
@@ -54,8 +55,8 @@ func (d Docker) Build(ctx context.Context, file string) (string, error) {
5455
return tag, nil
5556
}
5657

57-
// Run create and runs docker container.
58-
func (d Docker) Run(ctx context.Context, image string) error {
58+
// ContainerCreate creates Docker container.
59+
func (d Docker) ContainerCreate(ctx context.Context, image string, port int) (string, error) {
5960
resp, err := d.cli.ContainerCreate(
6061
ctx, &container.Config{
6162
Image: image,
@@ -67,7 +68,7 @@ func (d Docker) Run(ctx context.Context, image string) error {
6768
"8080/tcp": []nat.PortBinding{
6869
{
6970
HostIP: "0.0.0.0",
70-
HostPort: "8080",
71+
HostPort: strconv.Itoa(port),
7172
},
7273
},
7374
},
@@ -77,16 +78,32 @@ func (d Docker) Run(ctx context.Context, image string) error {
7778
"go-lambda",
7879
)
7980
if err != nil {
80-
return fmt.Errorf("failed to create container: %w", err)
81+
return "", fmt.Errorf("failed to create container: %w", err)
8182
}
8283

83-
d.logger.Debug("container created", slog.String("id", resp.ID))
84+
d.logger.Info("container created", slog.String("id", resp.ID[:5]), slog.Int("port", port))
8485

85-
if err := d.cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
86+
return resp.ID, nil
87+
}
88+
89+
// ContainerStart starts Docker container.
90+
func (d Docker) ContainerStart(ctx context.Context, imageID string) error {
91+
if err := d.cli.ContainerStart(ctx, imageID, types.ContainerStartOptions{}); err != nil {
8692
return fmt.Errorf("failed to start container: %w", err)
8793
}
8894

89-
d.logger.Debug("container started", slog.String("id", resp.ID))
95+
d.logger.Debug("container started", slog.String("id", imageID[:5]))
96+
97+
return nil
98+
}
99+
100+
// ContainerStop stops Docker container.
101+
func (d Docker) ContainerStop(ctx context.Context, imageID string) error {
102+
if err := d.cli.ContainerStop(ctx, imageID, container.StopOptions{}); err != nil {
103+
return fmt.Errorf("failed to stop container: %w", err)
104+
}
105+
106+
d.logger.Debug("container stopped", slog.String("id", imageID[:5]))
90107

91108
return nil
92109
}

cmd/lambda-go/main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ func main() {
3232
return
3333
}
3434

35-
c := builder.NewDocker(logger, cli)
36-
svc := lambda.NewService(conf, logger, c)
35+
bld := builder.NewDocker(logger, cli)
36+
svc := lambda.NewService(conf, logger, bld)
3737
edp := lambda.NewEndpoint(svc, logger, conf.App.ServerAddr)
3838

3939
if err := edp.StartServer(ctx); err != nil {

config/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ type Config struct {
1414
App AppCfg `env:",prefix=APP_,required"`
1515
}
1616

17+
// AppCfg is a configuration for the application.
1718
type AppCfg struct {
18-
FuncAddr string `env:"FUNC_ADDR,required"`
1919
ServerAddr string `env:"SERVER_ADDR,required"`
2020
}
2121

infra/Dockerfile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ WORKDIR /tmp/server-app
44

55
COPY go.mod ./
66
COPY go.sum ./
7+
COPY main.go ./
8+
RUN go mod tidy
79
RUN go mod download
810

9-
COPY *.go ./
10-
1111
# Build
1212
RUN CGO_ENABLED=0 GOOS=linux go build -o ./out/server-app .
1313

infra/go.mod

Lines changed: 0 additions & 23 deletions
This file was deleted.

infra/go.sum

Lines changed: 0 additions & 54 deletions
This file was deleted.

infra/main.go

Lines changed: 0 additions & 16 deletions
This file was deleted.

lambda/endpoint.go

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package lambda
22

33
import (
44
"context"
5+
"encoding/json"
6+
"fmt"
57
"io"
68
"log/slog"
79
"net/http"
@@ -11,7 +13,7 @@ import (
1113
)
1214

1315
type service interface {
14-
Create(ctx context.Context, name string) error
16+
Create(ctx context.Context, name string, file io.ReadCloser) error
1517
Invoke(ctx context.Context, name string, data []byte) ([]byte, error)
1618
}
1719

@@ -27,40 +29,56 @@ func NewEndpoint(svc service, logger *slog.Logger, addr string) *Endpoint {
2729
return &Endpoint{svc: svc, logger: logger, serverAddr: addr}
2830
}
2931

30-
type adminRequest struct {
31-
Name string `json:"name"`
32+
type createResponse struct {
33+
Name string `json:"name"`
34+
Description string `json:"description"`
3235
}
3336

37+
// create http endpoint for create lambda function.
3438
func (e *Endpoint) create(w http.ResponseWriter, r *http.Request) {
39+
const gzHeader = "application/gzip"
3540
vars := mux.Vars(r)
3641
name := vars["name"]
3742

38-
// TODO: get tar archive from request body
43+
file, fileHeader, err := r.FormFile("file")
44+
if err != nil {
45+
fmt.Println(err)
46+
return
47+
}
3948

40-
//
41-
//if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
42-
// http.Error(w, err.Error(), http.StatusBadRequest)
43-
// return
44-
//}
49+
if fileHeader.Header.Get("Content-Type") != gzHeader {
50+
http.Error(w, "invalid file type", http.StatusBadRequest)
51+
return
52+
}
4553

46-
e.logger.Debug("got create request", slog.Any("user_name", name))
54+
e.logger.Info("got create request", slog.Any("func_name", name))
4755

48-
err := e.svc.Create(r.Context(), name)
49-
if err != nil {
56+
if err := e.svc.Create(r.Context(), name, file); err != nil {
5057
e.logger.Error("create: service error", "err", err.Error())
5158
http.Error(w, err.Error(), http.StatusBadRequest)
5259
return
5360
}
5461

55-
_, err = w.Write([]byte("ok"))
62+
resp := createResponse{Name: name, Description: "lambda function was created"}
63+
data, err := json.Marshal(resp)
64+
if err != nil {
65+
e.logger.Error("create: marshal error", "err", err.Error())
66+
http.Error(w, err.Error(), http.StatusInternalServerError)
67+
return
68+
}
69+
70+
w.WriteHeader(http.StatusCreated)
71+
72+
_, err = w.Write(data)
5673
if err != nil {
5774
e.logger.Error("create: write error", "err", err.Error())
5875
http.Error(w, err.Error(), http.StatusInternalServerError)
5976
return
6077
}
6178
}
6279

63-
func (e *Endpoint) lambda(w http.ResponseWriter, r *http.Request) {
80+
// invoke http endpoint for invoke lambda function.
81+
func (e *Endpoint) invoke(w http.ResponseWriter, r *http.Request) {
6482
vars := mux.Vars(r)
6583
name := vars["name"]
6684

@@ -71,9 +89,9 @@ func (e *Endpoint) lambda(w http.ResponseWriter, r *http.Request) {
7189
return
7290
}
7391

74-
e.logger.Debug("got lambda request", slog.Any("user_name", name))
92+
e.logger.Info("got lambda request", slog.Any("func_name", name))
7593

76-
respData, err := e.svc.Invoke(r.Context(), "test", data)
94+
respData, err := e.svc.Invoke(r.Context(), name, data)
7795
if err != nil {
7896
e.logger.Error("lambda: invoke service error", "err", err.Error())
7997
http.Error(w, err.Error(), http.StatusBadRequest)
@@ -90,8 +108,8 @@ func (e *Endpoint) lambda(w http.ResponseWriter, r *http.Request) {
90108
// StartServer starts http-server.
91109
func (e *Endpoint) StartServer(ctx context.Context) error {
92110
r := mux.NewRouter()
93-
r.HandleFunc("/lambda/{name}/create", e.create)
94-
r.HandleFunc("/lambda/{name}/run", e.lambda)
111+
r.HandleFunc("/lambda/{name}/create", e.create).Methods(http.MethodPost)
112+
r.HandleFunc("/lambda/{name}/invoke", e.invoke).Methods(http.MethodPost)
95113

96114
srv := &http.Server{
97115
Handler: r,

lambda/meta.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package lambda
2+
3+
import "strconv"
4+
5+
type metaData struct {
6+
containerID string
7+
port int
8+
}
9+
10+
func newMetaData(containerID string, port int) *metaData {
11+
return &metaData{containerID: containerID, port: port}
12+
}
13+
14+
func (m metaData) address() string {
15+
return "http://localhost:" + strconv.Itoa(m.port)
16+
}

0 commit comments

Comments
 (0)