Skip to content

Commit

Permalink
feat(cloud-endpoints): add helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Viktor Voltaire authored and viktorvoltaire committed Feb 14, 2022
1 parent f1e9683 commit dacb495
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
9 changes: 9 additions & 0 deletions tools/sgcloudendpoints/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM gcr.io/endpoints-release/endpoints-runtime-serverless:2

USER root
ENV ENDPOINTS_SERVICE_PATH /etc/endpoints/service.json
COPY ./service.json ${ENDPOINTS_SERVICE_PATH}
RUN chown -R envoy:envoy ${ENDPOINTS_SERVICE_PATH} && chmod -R 755 ${ENDPOINTS_SERVICE_PATH}
USER envoy

ENTRYPOINT ["/env_start_proxy.py"]
101 changes: 101 additions & 0 deletions tools/sgcloudendpoints/tools.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package sgcloudendpoints

import (
"context"
_ "embed"
"fmt"
"net/http"
"os"
"path/filepath"

"go.einride.tech/sage/sg"
)

//go:embed Dockerfile
var dockerfile []byte

func ConfigID(ctx context.Context, serviceName, gcpProject string) string {
sg.Logger(ctx).Printf(
"retrieving endpoints configID from %s in %s...",
serviceName,
gcpProject,
)

return sg.Output(sg.Command(
ctx,
"gcloud",
"endpoints",
"configs",
"list",
"--service",
serviceName,
"--project",
gcpProject,
"--limit",
"1",
"--format",
"value(id)",
))
}

func DockerImage(ctx context.Context, serviceName, gcpProject, gcpRegion string) string {
dir, err := os.MkdirTemp(os.TempDir(), "sgcloudendpoints")
if err != nil {
panic(err)
}
configID := ConfigID(ctx, serviceName, gcpProject)
sg.Logger(ctx).Printf(
"building image for %s with configID %s...",
serviceName,
configID,
)
req, err := http.NewRequestWithContext(
ctx,
"GET",
fmt.Sprintf(
"https://servicemanagement.googleapis.com/v1/services/%s/configs/%s?view=FULL",
serviceName,
configID,
),
nil,
)
if err != nil {
panic(err)
}
token := sg.Output(sg.Command(ctx, "gcloud", "auth", "print-access-token"))
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer func() {
_ = resp.Body.Close()
}()
f, err := os.Create(filepath.Join(dir, "service.json"))
if err != nil {
panic(err)
}
if _, err := f.ReadFrom(resp.Body); err != nil {
panic(err)
}
defer func() {
_ = f.Close()
}()
tag := fmt.Sprintf(
"%s-docker.pkg.dev/%s/docker/endpoints-runtime-serverless:%s-%s",
gcpRegion,
gcpProject,
serviceName,
configID,
)
if err := os.WriteFile(filepath.Join(dir, "Dockerfile"), dockerfile, 0o600); err != nil {
panic(err)
}
cmd := sg.Command(ctx, "docker", "build", "-t", tag, ".")
cmd.Dir = dir
if err := cmd.Run(); err != nil {
panic(err)
}
return tag
}

0 comments on commit dacb495

Please sign in to comment.