Debian Codegraph @

samples/guestbook/localdb/main.go

raw
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 package main
16
17 import (
18 "context"
19 "errors"
20 "flag"
21 "fmt"
22 "log"
23 "os"
24 "os/exec"
25 "os/signal"
26 "path/filepath"
27 "strings"
28 "time"
29
30 pipe "gopkg.in/pipe.v2"
31 )
32
33 func main() {
34 guestbookDir := flag.String("guestbook_dir", ".", "directory containing guestbook sample source code")
35 flag.Parse()
36 if flag.NArg() > 1 {
37 fmt.Fprintf(os.Stderr, "usage: localdb [flags] container_name\n")
38 os.Exit(1)
39 }
40 log.SetPrefix("localdb: ")
41 log.SetFlags(0)
42 if err := runLocalDB(flag.Arg(0), *guestbookDir); err != nil {
43 log.Fatal(err)
44 }
45 }
46
47 func runLocalDB(containerName, guestbookDir string) error {
48 image := "mysql:5.6"
49
50 log.Printf("Starting container running MySQL")
51 dockerArgs := []string{"run", "--rm"}
52 if containerName != "" {
53 dockerArgs = append(dockerArgs, "--name", containerName)
54 }
55 dockerArgs = append(dockerArgs,
56 "--platform", "linux/amd64",
57 "--env", "MYSQL_DATABASE=guestbook",
58 "--env", "MYSQL_ROOT_PASSWORD=password",
59 "--detach",
60 "--publish", "3306:3306",
61 image)
62 cmd := exec.Command("docker", dockerArgs...)
63 cmd.Stderr = os.Stderr
64 out, err := cmd.Output()
65 if err != nil {
66 return fmt.Errorf("running %v: %v: %s", cmd.Args, err, out)
67 }
68 containerID := strings.TrimSpace(string(out))
69 defer func() {
70 log.Printf("killing %s", containerID)
71 stop := exec.Command("docker", "kill", containerID)
72 stop.Stderr = os.Stderr
73 if err := stop.Run(); err != nil {
74 log.Printf("failed to kill db container: %v", err)
75 }
76 }()
77
78 // Stop the container on Ctrl-C.
79 ctx, cancel := context.WithCancel(context.Background())
80 go func() {
81 c := make(chan os.Signal, 1)
82 // TODO(ijt): Handle SIGTERM.
83 signal.Notify(c, os.Interrupt)
84 <-c
85 cancel()
86 }()
87
88 nap := 10 * time.Second
89 log.Printf("Waiting %v for database to come up", nap)
90 select {
91 case <-time.After(nap):
92 // ok
93 case <-ctx.Done():
94 return errors.New("interrupted while napping")
95 }
96
97 log.Printf("Initializing database schema and users")
98 schema, err := os.ReadFile(filepath.Join(guestbookDir, "schema.sql"))
99 if err != nil {
100 return fmt.Errorf("reading schema: %v", err)
101 }
102 roles, err := os.ReadFile(filepath.Join(guestbookDir, "roles.sql"))
103 if err != nil {
104 return fmt.Errorf("reading roles: %v", err)
105 }
106 tooMany := 10
107 var i int
108 for i = 0; i < tooMany; i++ {
109 mySQL := `mysql -h"${MYSQL_PORT_3306_TCP_ADDR?}" -P"${MYSQL_PORT_3306_TCP_PORT?}" -uroot -ppassword guestbook`
110 p := pipe.Line(
111 pipe.Read(strings.NewReader(string(schema)+string(roles))),
112 pipe.Exec("docker", "run", "--rm", "--interactive", "--link", containerID+":mysql", image, "sh", "-c", mySQL),
113 )
114 if _, stderr, err := pipe.DividedOutput(p); err != nil {
115 log.Printf("Failed to seed database: %q; retrying", stderr)
116 select {
117 case <-time.After(time.Second):
118 continue
119 case <-ctx.Done():
120 return errors.New("interrupted while napping in between database seeding attempts")
121 }
122 }
123 break
124 }
125 if i == tooMany {
126 return fmt.Errorf("gave up after %d tries to seed database", i)
127 }
128
129 log.Printf("Database running at localhost:3306")
130 attach := exec.CommandContext(ctx, "docker", "attach", containerID)
131 attach.Stdout = os.Stdout
132 attach.Stderr = os.Stderr
133 if err := attach.Run(); err != nil {
134 return fmt.Errorf("running %v: %q", attach.Args, err)
135 }
136
137 return nil
138 }