| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// The deploy program builds the Guestbook server locally and deploys it to |
| 16 |
// GKE. |
| 17 |
package main |
| 18 |
|
| 19 |
import ( |
| 20 |
"encoding/json" |
| 21 |
"flag" |
| 22 |
"fmt" |
| 23 |
"log" |
| 24 |
"os" |
| 25 |
"os/exec" |
| 26 |
"path/filepath" |
| 27 |
"strings" |
| 28 |
"time" |
| 29 |
) |
| 30 |
|
| 31 |
func main() { |
| 32 |
log.SetFlags(0) |
| 33 |
log.SetPrefix("gcp/deploy: ") |
| 34 |
guestbookDir := flag.String("guestbook_dir", "..", "directory containing the guestbook example") |
| 35 |
tfStatePath := flag.String("tfstate", "terraform.tfstate", "path to terraform state file") |
| 36 |
flag.Parse() |
| 37 |
if err := deploy(*guestbookDir, *tfStatePath); err != nil { |
| 38 |
log.Fatal(err) |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
func deploy(guestbookDir, tfStatePath string) error { |
| 43 |
type tfItem struct { |
| 44 |
Sensitive bool |
| 45 |
Type string |
| 46 |
Value string |
| 47 |
} |
| 48 |
type state struct { |
| 49 |
Project tfItem |
| 50 |
ClusterName tfItem `json:"cluster_name"` |
| 51 |
ClusterZone tfItem `json:"cluster_zone"` |
| 52 |
Bucket tfItem |
| 53 |
DatabaseInstance tfItem `json:"database_instance"` |
| 54 |
DatabaseRegion tfItem `json:"database_region"` |
| 55 |
MotdVarConfig tfItem `json:"motd_var_config"` |
| 56 |
MotdVarName tfItem `json:"motd_var_name"` |
| 57 |
} |
| 58 |
tfStateb, err := runb("terraform", "output", "-state", tfStatePath, "-json") |
| 59 |
if err != nil { |
| 60 |
return err |
| 61 |
} |
| 62 |
var tfState state |
| 63 |
if err := json.Unmarshal(tfStateb, &tfState); err != nil { |
| 64 |
return fmt.Errorf("parsing terraform state JSON: %v", err) |
| 65 |
} |
| 66 |
zone := tfState.ClusterZone.Value |
| 67 |
if zone == "" { |
| 68 |
return fmt.Errorf("empty or missing cluster_zone in %s", tfStatePath) |
| 69 |
} |
| 70 |
tempDir, err := os.MkdirTemp("", "guestbook-k8s-") |
| 71 |
if err != nil { |
| 72 |
return fmt.Errorf("making temp dir: %v", err) |
| 73 |
} |
| 74 |
defer os.RemoveAll(tempDir) |
| 75 |
|
| 76 |
// Fill in Kubernetes template parameters. |
| 77 |
proj := strings.Replace(tfState.Project.Value, ":", "/", -1) |
| 78 |
imageName := fmt.Sprintf("gcr.io/%s/guestbook", proj) |
| 79 |
gbyin, err := os.ReadFile(filepath.Join(guestbookDir, "gcp", "guestbook.yaml.in")) |
| 80 |
if err != nil { |
| 81 |
return fmt.Errorf("reading guestbook.yaml.in: %v", err) |
| 82 |
} |
| 83 |
gby := string(gbyin) |
| 84 |
replacements := map[string]string{ |
| 85 |
"{{IMAGE}}": imageName, |
| 86 |
"{{bucket}}": tfState.Bucket.Value, |
| 87 |
"{{database_instance}}": tfState.DatabaseInstance.Value, |
| 88 |
"{{database_region}}": tfState.DatabaseRegion.Value, |
| 89 |
"{{motd_var_config}}": tfState.MotdVarConfig.Value, |
| 90 |
"{{motd_var_name}}": tfState.MotdVarName.Value, |
| 91 |
} |
| 92 |
for old, new := range replacements { |
| 93 |
gby = strings.Replace(gby, old, new, -1) |
| 94 |
} |
| 95 |
if err := os.WriteFile(filepath.Join(tempDir, "guestbook.yaml"), []byte(gby), 0o666); err != nil { |
| 96 |
return fmt.Errorf("writing guestbook.yaml: %v", err) |
| 97 |
} |
| 98 |
|
| 99 |
// Build Guestbook Docker image. |
| 100 |
log.Printf("Building %s...", imageName) |
| 101 |
build := exec.Command("go", "build", "-o", "gcp/guestbook") |
| 102 |
env := append(build.Env, "GOOS=linux", "GOARCH=amd64") |
| 103 |
env = append(env, os.Environ()...) |
| 104 |
build.Env = env |
| 105 |
absDir, err := filepath.Abs(guestbookDir) |
| 106 |
if err != nil { |
| 107 |
return fmt.Errorf("getting abs path to guestbook dir (%s): %v", guestbookDir, err) |
| 108 |
} |
| 109 |
build.Dir = absDir |
| 110 |
build.Stderr = os.Stderr |
| 111 |
if err := build.Run(); err != nil { |
| 112 |
return fmt.Errorf("building guestbook app by running %v: %v", build.Args, err) |
| 113 |
} |
| 114 |
gcp := gcloud{projectID: tfState.Project.Value} |
| 115 |
cbs := gcp.cmd("builds", "submit", "-t", imageName, filepath.Join(guestbookDir, "gcp")) |
| 116 |
if err := cbs.Run(); err != nil { |
| 117 |
return fmt.Errorf("building container image with %v: %v", cbs.Args, err) |
| 118 |
} |
| 119 |
|
| 120 |
// Run on Kubernetes. |
| 121 |
log.Printf("Deploying to %s...", tfState.ClusterName.Value) |
| 122 |
getCreds := gcp.cmd("container", "clusters", "get-credentials", "--zone", zone, tfState.ClusterName.Value) |
| 123 |
getCreds.Stderr = os.Stderr |
| 124 |
if err := getCreds.Run(); err != nil { |
| 125 |
return fmt.Errorf("getting credentials with %v: %v", getCreds.Args, err) |
| 126 |
} |
| 127 |
kubeCmds := [][]string{ |
| 128 |
{"kubectl", "apply", "-f", filepath.Join(tempDir, "guestbook.yaml")}, |
| 129 |
// Force pull the latest image. |
| 130 |
{"kubectl", "scale", "--replicas", "0", "deployment/guestbook"}, |
| 131 |
{"kubectl", "scale", "--replicas", "1", "deployment/guestbook"}, |
| 132 |
} |
| 133 |
for _, kcmd := range kubeCmds { |
| 134 |
cmd := exec.Command(kcmd[0], kcmd[1:]...) |
| 135 |
if err := cmd.Run(); err != nil { |
| 136 |
return fmt.Errorf("running %v: %v", cmd.Args, err) |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
// Wait for endpoint then print it. |
| 141 |
log.Printf("Waiting for load balancer...") |
| 142 |
for { |
| 143 |
outb, err := runb("kubectl", "get", "service", "guestbook", "-o", "json") |
| 144 |
if err != nil { |
| 145 |
return err |
| 146 |
} |
| 147 |
var s service |
| 148 |
if err := json.Unmarshal(outb, &s); err != nil { |
| 149 |
return fmt.Errorf("parsing JSON output: %v", err) |
| 150 |
} |
| 151 |
i := s.Status.LoadBalancer.Ingress |
| 152 |
if len(i) == 0 || i[0].IP == "" { |
| 153 |
dt := time.Second |
| 154 |
log.Printf("No ingress returned in %s. Trying again in %v", outb, dt) |
| 155 |
time.Sleep(dt) |
| 156 |
continue |
| 157 |
} |
| 158 |
endpoint := i[0].IP |
| 159 |
log.Printf("Deployed at http://%s:8080", endpoint) |
| 160 |
break |
| 161 |
} |
| 162 |
return nil |
| 163 |
} |
| 164 |
|
| 165 |
type ( |
| 166 |
service struct{ Status *status } |
| 167 |
status struct{ LoadBalancer loadBalancer } |
| 168 |
loadBalancer struct{ Ingress []ingress } |
| 169 |
ingress struct{ IP string } |
| 170 |
) |
| 171 |
|
| 172 |
type gcloud struct { |
| 173 |
projectID string |
| 174 |
} |
| 175 |
|
| 176 |
func (gcp *gcloud) cmd(args ...string) *exec.Cmd { |
| 177 |
args = append([]string{"--quiet", "--project", gcp.projectID}, args...) |
| 178 |
cmd := exec.Command("gcloud", args...) |
| 179 |
cmd.Env = append(cmd.Env, os.Environ()...) |
| 180 |
cmd.Stderr = os.Stderr |
| 181 |
return cmd |
| 182 |
} |
| 183 |
|
| 184 |
func run(args ...string) (stdout string, err error) { |
| 185 |
stdoutb, err := runb(args...) |
| 186 |
return strings.TrimSpace(string(stdoutb)), err |
| 187 |
} |
| 188 |
|
| 189 |
func runb(args ...string) (stdout []byte, err error) { |
| 190 |
cmd := exec.Command(args[0], args[1:]...) |
| 191 |
cmd.Stderr = os.Stderr |
| 192 |
cmd.Env = append(cmd.Env, os.Environ()...) |
| 193 |
stdoutb, err := cmd.Output() |
| 194 |
if err != nil { |
| 195 |
return nil, fmt.Errorf("running %v: %v", cmd.Args, err) |
| 196 |
} |
| 197 |
return stdoutb, nil |
| 198 |
} |