launch.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build ignore
  5. package main
  6. import (
  7. "bufio"
  8. "bytes"
  9. "encoding/json"
  10. "flag"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "net/http"
  16. "os"
  17. "strings"
  18. "time"
  19. "code.google.com/p/goauth2/oauth"
  20. compute "code.google.com/p/google-api-go-client/compute/v1"
  21. )
  22. var (
  23. proj = flag.String("project", "symbolic-datum-552", "name of Project")
  24. zone = flag.String("zone", "us-central1-a", "GCE zone")
  25. mach = flag.String("machinetype", "n1-standard-1", "Machine type")
  26. instName = flag.String("instance_name", "http2-demo", "Name of VM instance.")
  27. sshPub = flag.String("ssh_public_key", "", "ssh public key file to authorize. Can modify later in Google's web UI anyway.")
  28. staticIP = flag.String("static_ip", "130.211.116.44", "Static IP to use. If empty, automatic.")
  29. writeObject = flag.String("write_object", "", "If non-empty, a VM isn't created and the flag value is Google Cloud Storage bucket/object to write. The contents from stdin.")
  30. publicObject = flag.Bool("write_object_is_public", false, "Whether the object created by --write_object should be public.")
  31. )
  32. func readFile(v string) string {
  33. slurp, err := ioutil.ReadFile(v)
  34. if err != nil {
  35. log.Fatalf("Error reading %s: %v", v, err)
  36. }
  37. return strings.TrimSpace(string(slurp))
  38. }
  39. var config = &oauth.Config{
  40. // The client-id and secret should be for an "Installed Application" when using
  41. // the CLI. Later we'll use a web application with a callback.
  42. ClientId: readFile("client-id.dat"),
  43. ClientSecret: readFile("client-secret.dat"),
  44. Scope: strings.Join([]string{
  45. compute.DevstorageFull_controlScope,
  46. compute.ComputeScope,
  47. "https://www.googleapis.com/auth/sqlservice",
  48. "https://www.googleapis.com/auth/sqlservice.admin",
  49. }, " "),
  50. AuthURL: "https://accounts.google.com/o/oauth2/auth",
  51. TokenURL: "https://accounts.google.com/o/oauth2/token",
  52. RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
  53. }
  54. const baseConfig = `#cloud-config
  55. coreos:
  56. units:
  57. - name: h2demo.service
  58. command: start
  59. content: |
  60. [Unit]
  61. Description=HTTP2 Demo
  62. [Service]
  63. ExecStartPre=/bin/bash -c 'mkdir -p /opt/bin && curl -s -o /opt/bin/h2demo http://storage.googleapis.com/http2-demo-server-tls/h2demo && chmod +x /opt/bin/h2demo'
  64. ExecStart=/opt/bin/h2demo
  65. RestartSec=5s
  66. Restart=always
  67. Type=simple
  68. [Install]
  69. WantedBy=multi-user.target
  70. `
  71. func main() {
  72. flag.Parse()
  73. if *proj == "" {
  74. log.Fatalf("Missing --project flag")
  75. }
  76. prefix := "https://www.googleapis.com/compute/v1/projects/" + *proj
  77. machType := prefix + "/zones/" + *zone + "/machineTypes/" + *mach
  78. tr := &oauth.Transport{
  79. Config: config,
  80. }
  81. tokenCache := oauth.CacheFile("token.dat")
  82. token, err := tokenCache.Token()
  83. if err != nil {
  84. if *writeObject != "" {
  85. log.Fatalf("Can't use --write_object without a valid token.dat file already cached.")
  86. }
  87. log.Printf("Error getting token from %s: %v", string(tokenCache), err)
  88. log.Printf("Get auth code from %v", config.AuthCodeURL("my-state"))
  89. fmt.Print("\nEnter auth code: ")
  90. sc := bufio.NewScanner(os.Stdin)
  91. sc.Scan()
  92. authCode := strings.TrimSpace(sc.Text())
  93. token, err = tr.Exchange(authCode)
  94. if err != nil {
  95. log.Fatalf("Error exchanging auth code for a token: %v", err)
  96. }
  97. tokenCache.PutToken(token)
  98. }
  99. tr.Token = token
  100. oauthClient := &http.Client{Transport: tr}
  101. if *writeObject != "" {
  102. writeCloudStorageObject(oauthClient)
  103. return
  104. }
  105. computeService, _ := compute.New(oauthClient)
  106. natIP := *staticIP
  107. if natIP == "" {
  108. // Try to find it by name.
  109. aggAddrList, err := computeService.Addresses.AggregatedList(*proj).Do()
  110. if err != nil {
  111. log.Fatal(err)
  112. }
  113. // http://godoc.org/code.google.com/p/google-api-go-client/compute/v1#AddressAggregatedList
  114. IPLoop:
  115. for _, asl := range aggAddrList.Items {
  116. for _, addr := range asl.Addresses {
  117. if addr.Name == *instName+"-ip" && addr.Status == "RESERVED" {
  118. natIP = addr.Address
  119. break IPLoop
  120. }
  121. }
  122. }
  123. }
  124. cloudConfig := baseConfig
  125. if *sshPub != "" {
  126. key := strings.TrimSpace(readFile(*sshPub))
  127. cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", key)
  128. }
  129. if os.Getenv("USER") == "bradfitz" {
  130. cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwks9dwWKlRC+73gRbvYtVg0vdCwDSuIlyt4z6xa/YU/jTDynM4R4W10hm2tPjy8iR1k8XhDv4/qdxe6m07NjG/By1tkmGpm1mGwho4Pr5kbAAy/Qg+NLCSdAYnnE00FQEcFOC15GFVMOW2AzDGKisReohwH9eIzHPzdYQNPRWXE= bradfitz@papag.bradfitz.com")
  131. }
  132. const maxCloudConfig = 32 << 10 // per compute API docs
  133. if len(cloudConfig) > maxCloudConfig {
  134. log.Fatalf("cloud config length of %d bytes is over %d byte limit", len(cloudConfig), maxCloudConfig)
  135. }
  136. instance := &compute.Instance{
  137. Name: *instName,
  138. Description: "Go Builder",
  139. MachineType: machType,
  140. Disks: []*compute.AttachedDisk{instanceDisk(computeService)},
  141. Tags: &compute.Tags{
  142. Items: []string{"http-server", "https-server"},
  143. },
  144. Metadata: &compute.Metadata{
  145. Items: []*compute.MetadataItems{
  146. {
  147. Key: "user-data",
  148. Value: cloudConfig,
  149. },
  150. },
  151. },
  152. NetworkInterfaces: []*compute.NetworkInterface{
  153. &compute.NetworkInterface{
  154. AccessConfigs: []*compute.AccessConfig{
  155. &compute.AccessConfig{
  156. Type: "ONE_TO_ONE_NAT",
  157. Name: "External NAT",
  158. NatIP: natIP,
  159. },
  160. },
  161. Network: prefix + "/global/networks/default",
  162. },
  163. },
  164. ServiceAccounts: []*compute.ServiceAccount{
  165. {
  166. Email: "default",
  167. Scopes: []string{
  168. compute.DevstorageFull_controlScope,
  169. compute.ComputeScope,
  170. },
  171. },
  172. },
  173. }
  174. log.Printf("Creating instance...")
  175. op, err := computeService.Instances.Insert(*proj, *zone, instance).Do()
  176. if err != nil {
  177. log.Fatalf("Failed to create instance: %v", err)
  178. }
  179. opName := op.Name
  180. log.Printf("Created. Waiting on operation %v", opName)
  181. OpLoop:
  182. for {
  183. time.Sleep(2 * time.Second)
  184. op, err := computeService.ZoneOperations.Get(*proj, *zone, opName).Do()
  185. if err != nil {
  186. log.Fatalf("Failed to get op %s: %v", opName, err)
  187. }
  188. switch op.Status {
  189. case "PENDING", "RUNNING":
  190. log.Printf("Waiting on operation %v", opName)
  191. continue
  192. case "DONE":
  193. if op.Error != nil {
  194. for _, operr := range op.Error.Errors {
  195. log.Printf("Error: %+v", operr)
  196. }
  197. log.Fatalf("Failed to start.")
  198. }
  199. log.Printf("Success. %+v", op)
  200. break OpLoop
  201. default:
  202. log.Fatalf("Unknown status %q: %+v", op.Status, op)
  203. }
  204. }
  205. inst, err := computeService.Instances.Get(*proj, *zone, *instName).Do()
  206. if err != nil {
  207. log.Fatalf("Error getting instance after creation: %v", err)
  208. }
  209. ij, _ := json.MarshalIndent(inst, "", " ")
  210. log.Printf("Instance: %s", ij)
  211. }
  212. func instanceDisk(svc *compute.Service) *compute.AttachedDisk {
  213. const imageURL = "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-stable-445-5-0-v20141016"
  214. diskName := *instName + "-coreos-stateless-pd"
  215. return &compute.AttachedDisk{
  216. AutoDelete: true,
  217. Boot: true,
  218. Type: "PERSISTENT",
  219. InitializeParams: &compute.AttachedDiskInitializeParams{
  220. DiskName: diskName,
  221. SourceImage: imageURL,
  222. DiskSizeGb: 50,
  223. },
  224. }
  225. }
  226. func writeCloudStorageObject(httpClient *http.Client) {
  227. content := os.Stdin
  228. const maxSlurp = 1 << 20
  229. var buf bytes.Buffer
  230. n, err := io.CopyN(&buf, content, maxSlurp)
  231. if err != nil && err != io.EOF {
  232. log.Fatalf("Error reading from stdin: %v, %v", n, err)
  233. }
  234. contentType := http.DetectContentType(buf.Bytes())
  235. req, err := http.NewRequest("PUT", "https://storage.googleapis.com/"+*writeObject, io.MultiReader(&buf, content))
  236. if err != nil {
  237. log.Fatal(err)
  238. }
  239. req.Header.Set("x-goog-api-version", "2")
  240. if *publicObject {
  241. req.Header.Set("x-goog-acl", "public-read")
  242. }
  243. req.Header.Set("Content-Type", contentType)
  244. res, err := httpClient.Do(req)
  245. if err != nil {
  246. log.Fatal(err)
  247. }
  248. if res.StatusCode != 200 {
  249. res.Write(os.Stderr)
  250. log.Fatalf("Failed.")
  251. }
  252. log.Printf("Success.")
  253. os.Exit(0)
  254. }