Debian Codegraph @

samples/guestbook/aws/provision_db/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 // The provision_db program connects to an RDS database and initializes it with
16 // SQL from stdin. It is intended to be invoked from Terraform.
17 package main
18
19 import (
20 "flag"
21 "fmt"
22 "io"
23 "log"
24 "net/http"
25 "os"
26 "os/exec"
27 "path/filepath"
28 "strings"
29 )
30
31 func main() {
32 log.SetFlags(0)
33 log.SetPrefix("aws/provision_db: ")
34 host := flag.String("host", "", "hostname of database")
35 region := flag.String("region", "", "AWS region")
36 securityGroup := flag.String("security_group", "", "database security group")
37 database := flag.String("database", "", "name of database to provision")
38 password := flag.String("password", "", "root password on database")
39 schema := flag.String("schema", "", "path to .sql file defining the database schema")
40 flag.Parse()
41 missing := false
42 flag.VisitAll(func(f *flag.Flag) {
43 if f.Value.String() == "" {
44 log.Printf("Required flag -%s not set.", f.Name)
45 missing = true
46 }
47 })
48 if missing {
49 os.Exit(64)
50 }
51 if err := provisionDb(*host, *region, *securityGroup, *database, *password, *schema); err != nil {
52 log.Fatal(err)
53 }
54 }
55
56 func provisionDb(dbHost, region, securityGroupID, dbName, dbPassword, schemaPath string) error {
57 const mySQLImage = "mysql:5.6"
58
59 // Pull the necessary Docker images.
60 log.Print("Downloading Docker images...")
61 if _, err := run("docker", "pull", mySQLImage); err != nil {
62 return err
63 }
64
65 // Create a temporary directory to hold the certificates.
66 // We resolve all symlinks to avoid Docker on Mac issues, see
67 // https://github.com/google/go-cloud/issues/110.
68 tempdir, err := os.MkdirTemp("", "guestbook-ca")
69 if err != nil {
70 return fmt.Errorf("creating temp dir for certs: %v", err)
71 }
72 defer os.RemoveAll(tempdir)
73 tempdir, err = filepath.EvalSymlinks(tempdir)
74 if err != nil {
75 return fmt.Errorf("evaluating any symlinks: %v", err)
76 }
77 resp, err := http.Get("https://s3.amazonaws.com/rds-downloads/rds-ca-2015-root.pem")
78 if err != nil {
79 return fmt.Errorf("fetching pem file: %v", err)
80 }
81 if resp.StatusCode != 200 {
82 return fmt.Errorf("response status code is %d, want 200", resp.StatusCode)
83 }
84 defer resp.Body.Close()
85 caPath := filepath.Join(tempdir, "rds-ca.pem")
86 caFile, err := os.Create(caPath)
87 if err != nil {
88 return err
89 }
90 if _, err := io.Copy(caFile, resp.Body); err != nil {
91 return fmt.Errorf("copying response to file: %v", err)
92 }
93
94 log.Print("Adding a temporary ingress rule")
95 if _, err := run("aws", "ec2", "authorize-security-group-ingress", "--region", region, "--group-id", securityGroupID, "--protocol=tcp", "--port=3306", "--cidr=0.0.0.0/0"); err != nil {
96 return err
97 }
98 defer func() {
99 log.Print("Removing ingress rule...")
100 if _, err := run("aws", "ec2", "revoke-security-group-ingress", "--region", region, "--group-id", securityGroupID, "--protocol=tcp", "--port=3306", "--cidr=0.0.0.0/0"); err != nil {
101 log.Print(err)
102 }
103 }()
104 log.Printf("Added ingress rule to %s for port 3306", securityGroupID)
105
106 // Send schema.
107 log.Print("Sending schema to database...")
108 schema, err := os.Open(schemaPath)
109 if err != nil {
110 return err
111 }
112 defer schema.Close()
113 mySQLCmd := fmt.Sprintf(`mysql -h'%s' -uroot -p'%s' --ssl-ca=/ca/rds-ca.pem '%s'`, dbHost, dbPassword, dbName)
114 connect := exec.Command("docker", "run", "--rm", "--interactive", "--volume", tempdir+":/ca", mySQLImage, "sh", "-c", mySQLCmd)
115 connect.Stdin = schema
116 connect.Stderr = os.Stderr
117 if err := connect.Run(); err != nil {
118 return fmt.Errorf("running %v: %v", connect.Args, err)
119 }
120
121 return nil
122 }
123
124 func run(args ...string) (stdout string, err error) {
125 cmd := exec.Command(args[0], args[1:]...)
126 cmd.Stderr = os.Stderr
127 cmd.Env = append(cmd.Env, os.Environ()...)
128 stdoutb, err := cmd.Output()
129 if err != nil {
130 return "", fmt.Errorf("running %v: %v", cmd.Args, err)
131 }
132 return strings.TrimSpace(string(stdoutb)), nil
133 }