| 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 a Cloud SQL database and initializes it |
| 16 |
// with SQL from a file. It's intended to be invoked from Terraform. |
| 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 |
) |
| 29 |
|
| 30 |
func main() { |
| 31 |
log.SetFlags(0) |
| 32 |
log.SetPrefix("gcp/provision_db: ") |
| 33 |
project := flag.String("project", "", "GCP project ID") |
| 34 |
serviceAccount := flag.String("service_account", "", "name of service account in GCP project") |
| 35 |
instance := flag.String("instance", "", "database instance name") |
| 36 |
database := flag.String("database", "", "name of database to initialize") |
| 37 |
password := flag.String("password", "", "root password for the database") |
| 38 |
schema := flag.String("schema", "", "path to .sql file defining the database schema") |
| 39 |
flag.Parse() |
| 40 |
missing := false |
| 41 |
flag.VisitAll(func(f *flag.Flag) { |
| 42 |
if f.Value.String() == "" { |
| 43 |
log.Printf("Required flag -%s is not set.", f.Name) |
| 44 |
missing = true |
| 45 |
} |
| 46 |
}) |
| 47 |
if missing { |
| 48 |
os.Exit(64) |
| 49 |
} |
| 50 |
if err := provisionDB(*project, *serviceAccount, *instance, *database, *password, *schema); err != nil { |
| 51 |
log.Fatal(err) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
type key struct { |
| 56 |
PrivateKeyID string `json:"private_key_id"` |
| 57 |
} |
| 58 |
|
| 59 |
func provisionDB(projectID, serviceAccount, dbInstance, dbName, dbPassword, schemaPath string) error { |
| 60 |
log.Printf("Downloading Docker images...") |
| 61 |
const mySQLImage = "mysql:5.6" |
| 62 |
cloudSQLProxyImage := "gcr.io/cloudsql-docker/gce-proxy:1.11" |
| 63 |
images := []string{mySQLImage, cloudSQLProxyImage} |
| 64 |
for _, img := range images { |
| 65 |
if _, err := run("docker", "pull", img); err != nil { |
| 66 |
return err |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
log.Printf("Getting connection string from database metadata...") |
| 71 |
gcp := &gcloud{projectID} |
| 72 |
dbConnStr, err := run(gcp.cmd("sql", "instances", "describe", "--format", "value(connectionName)", dbInstance)...) |
| 73 |
if err != nil { |
| 74 |
return fmt.Errorf("getting connection string: %v", err) |
| 75 |
} |
| 76 |
|
| 77 |
// Create a temporary directory to hold the service account key. |
| 78 |
// We resolve all symlinks to avoid Docker on Mac issues, see |
| 79 |
// https://github.com/google/go-cloud/issues/110. |
| 80 |
serviceAccountVolDir, err := os.MkdirTemp("", "guestbook-service-acct") |
| 81 |
if err != nil { |
| 82 |
return fmt.Errorf("creating temp dir to hold service account key: %v", err) |
| 83 |
} |
| 84 |
serviceAccountVolDir, err = filepath.EvalSymlinks(serviceAccountVolDir) |
| 85 |
if err != nil { |
| 86 |
return fmt.Errorf("evaluating any symlinks: %v", err) |
| 87 |
} |
| 88 |
defer os.RemoveAll(serviceAccountVolDir) |
| 89 |
log.Printf("Created %v", serviceAccountVolDir) |
| 90 |
|
| 91 |
// Furnish a new service account key. |
| 92 |
if _, err := run(gcp.cmd("iam", "service-accounts", "keys", "create", "--iam-account="+serviceAccount, serviceAccountVolDir+"/key.json")...); err != nil { |
| 93 |
return fmt.Errorf("creating new service account key: %v", err) |
| 94 |
} |
| 95 |
keyJSONb, err := os.ReadFile(filepath.Join(serviceAccountVolDir, "key.json")) |
| 96 |
if err != nil { |
| 97 |
return fmt.Errorf("reading key.json file: %v", err) |
| 98 |
} |
| 99 |
var k key |
| 100 |
if err := json.Unmarshal(keyJSONb, &k); err != nil { |
| 101 |
return fmt.Errorf("parsing key.json: %v", err) |
| 102 |
} |
| 103 |
serviceAccountKeyID := k.PrivateKeyID |
| 104 |
defer func() { |
| 105 |
if _, err := run(gcp.cmd("iam", "service-accounts", "keys", "delete", "--iam-account", serviceAccount, serviceAccountKeyID)...); err != nil { |
| 106 |
log.Printf("deleting service account key: %v", err) |
| 107 |
} |
| 108 |
}() |
| 109 |
log.Printf("Created service account key %s", serviceAccountKeyID) |
| 110 |
|
| 111 |
log.Printf("Starting Cloud SQL proxy...") |
| 112 |
proxyContainerID, err := run("docker", "run", "--detach", "--rm", "--volume", serviceAccountVolDir+":/creds", "--publish", "3306", cloudSQLProxyImage, "/cloud_sql_proxy", "-instances", dbConnStr+"=tcp:0.0.0.0:3306", "-credential_file=/creds/key.json") |
| 113 |
if err != nil { |
| 114 |
return err |
| 115 |
} |
| 116 |
defer func() { |
| 117 |
if _, err := run("docker", "kill", proxyContainerID); err != nil { |
| 118 |
log.Printf("failed to kill docker container for proxy: %v", err) |
| 119 |
} |
| 120 |
}() |
| 121 |
|
| 122 |
log.Print("Sending schema to database...") |
| 123 |
mySQLCmd := fmt.Sprintf(`mysql --wait -h"$PROXY_PORT_3306_TCP_ADDR" -P"$PROXY_PORT_3306_TCP_PORT" -uroot -p'%s' '%s'`, dbPassword, dbName) |
| 124 |
connect := exec.Command("docker", "run", "--rm", "--interactive", "--link", proxyContainerID+":proxy", mySQLImage, "sh", "-c", mySQLCmd) |
| 125 |
schema, err := os.Open(schemaPath) |
| 126 |
if err != nil { |
| 127 |
return err |
| 128 |
} |
| 129 |
defer schema.Close() |
| 130 |
connect.Stdin = schema |
| 131 |
connect.Stderr = os.Stderr |
| 132 |
if err := connect.Run(); err != nil { |
| 133 |
return fmt.Errorf("running %v: %v", connect.Args, err) |
| 134 |
} |
| 135 |
|
| 136 |
return nil |
| 137 |
} |
| 138 |
|
| 139 |
func run(args ...string) (stdout string, err error) { |
| 140 |
cmd := exec.Command(args[0], args[1:]...) |
| 141 |
cmd.Stderr = os.Stderr |
| 142 |
cmd.Env = append(cmd.Env, os.Environ()...) |
| 143 |
stdoutb, err := cmd.Output() |
| 144 |
if err != nil { |
| 145 |
return "", fmt.Errorf("running %v: %v", cmd.Args, err) |
| 146 |
} |
| 147 |
return strings.TrimSpace(string(stdoutb)), nil |
| 148 |
} |
| 149 |
|
| 150 |
type gcloud struct { |
| 151 |
// project ID |
| 152 |
project string |
| 153 |
} |
| 154 |
|
| 155 |
func (gcp *gcloud) cmd(args ...string) []string { |
| 156 |
return append([]string{"gcloud", "--quiet", "--project", gcp.project}, args...) |
| 157 |
} |