PageRenderTime 48ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/go4.org/cloud/cloudlaunch/cloudlaunch.go

http://github.com/bradfitz/camlistore
Go | 457 lines | 366 code | 40 blank | 51 comment | 81 complexity | e741ab21f72c20d24c67627e4b715e7f MD5 | raw file
Possible License(s): CC0-1.0, MIT, BSD-3-Clause, 0BSD, MPL-2.0-no-copyleft-exception, BSD-2-Clause, Apache-2.0
  1. /*
  2. Copyright 2015 The Perkeep Authors
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package cloudlaunch helps binaries run themselves on The Cloud, copying
  14. // themselves to GCE.
  15. package cloudlaunch // import "go4.org/cloud/cloudlaunch"
  16. import (
  17. "encoding/json"
  18. "flag"
  19. "fmt"
  20. "io"
  21. "io/ioutil"
  22. "log"
  23. "net/http"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "runtime"
  28. "strings"
  29. "time"
  30. "go4.org/cloud/google/gceutil"
  31. "cloud.google.com/go/compute/metadata"
  32. "cloud.google.com/go/storage"
  33. "golang.org/x/net/context"
  34. "golang.org/x/oauth2"
  35. "golang.org/x/oauth2/google"
  36. compute "google.golang.org/api/compute/v1"
  37. "google.golang.org/api/googleapi"
  38. "google.golang.org/api/option"
  39. storageapi "google.golang.org/api/storage/v1"
  40. )
  41. func readFile(v string) string {
  42. slurp, err := ioutil.ReadFile(v)
  43. if err != nil {
  44. log.Fatalf("Error reading %s: %v", v, err)
  45. }
  46. return strings.TrimSpace(string(slurp))
  47. }
  48. const baseConfig = `#cloud-config
  49. coreos:
  50. update:
  51. group: stable
  52. reboot-strategy: $REBOOT
  53. units:
  54. - name: $NAME.service
  55. command: start
  56. content: |
  57. [Unit]
  58. Description=$NAME service
  59. After=network.target
  60. [Service]
  61. Type=simple
  62. ExecStartPre=/bin/sh -c 'mkdir -p /opt/bin && /usr/bin/curl --silent -f -o /opt/bin/$NAME $URL?$(date +%s) && chmod +x /opt/bin/$NAME'
  63. ExecStart=/opt/bin/$NAME
  64. RestartSec=10
  65. Restart=always
  66. StartLimitInterval=0
  67. [Install]
  68. WantedBy=network-online.target
  69. `
  70. // RestartPolicy controls whether the binary automatically restarts.
  71. type RestartPolicy int
  72. const (
  73. RestartOnUpdates RestartPolicy = iota
  74. RestartNever
  75. // TODO: more graceful restarts; make systemd own listening on network sockets,
  76. // don't break connections.
  77. )
  78. type Config struct {
  79. // Name is the name of a service to run.
  80. // This is the name of the systemd service (without .service)
  81. // and the name of the GCE instance.
  82. Name string
  83. // RestartPolicy controls whether the binary automatically restarts
  84. // on updates. The zero value means automatic.
  85. RestartPolicy RestartPolicy
  86. // UpdateStrategy sets the CoreOS automatic update strategy, and the
  87. // associated reboots. Possible values are "best-effort", "etcd-lock",
  88. // "reboot", "off", with "best-effort" being the default. See
  89. // https://coreos.com/os/docs/latest/update-strategies.html
  90. UpdateStrategy string
  91. // BinaryBucket and BinaryObject are the GCS bucket and object
  92. // within that bucket containing the Linux binary to download
  93. // on boot and occasionally run. This binary must be public
  94. // (at least for now).
  95. BinaryBucket string
  96. BinaryObject string // defaults to Name
  97. GCEProjectID string
  98. Zone string // defaults to us-central1-f
  99. SSD bool
  100. Scopes []string // any additional scopes
  101. MachineType string
  102. InstanceName string
  103. }
  104. // cloudLaunch is a launch of a Config.
  105. type cloudLaunch struct {
  106. *Config
  107. oauthClient *http.Client
  108. computeService *compute.Service
  109. }
  110. func (c *Config) binaryURL() string {
  111. return "https://storage.googleapis.com/" + c.BinaryBucket + "/" + c.binaryObject()
  112. }
  113. func (c *Config) instName() string { return c.Name } // for now
  114. func (c *Config) zone() string { return strDefault(c.Zone, "us-central1-f") }
  115. func (c *Config) machineType() string { return strDefault(c.MachineType, "g1-small") }
  116. func (c *Config) binaryObject() string { return strDefault(c.BinaryObject, c.Name) }
  117. func (c *Config) updateStrategy() string { return strDefault(c.UpdateStrategy, "best-effort") }
  118. func (c *Config) projectAPIURL() string {
  119. return "https://www.googleapis.com/compute/v1/projects/" + c.GCEProjectID
  120. }
  121. func (c *Config) machineTypeURL() string {
  122. return c.projectAPIURL() + "/zones/" + c.zone() + "/machineTypes/" + c.machineType()
  123. }
  124. func strDefault(a, b string) string {
  125. if a != "" {
  126. return a
  127. }
  128. return b
  129. }
  130. var (
  131. doLaunch = flag.Bool("cloudlaunch", false, "Deploy or update this binary to the cloud. Must be on Linux, for now.")
  132. )
  133. func (c *Config) MaybeDeploy() {
  134. flag.Parse()
  135. if !*doLaunch {
  136. go c.restartLoop()
  137. return
  138. }
  139. defer os.Exit(1) // backup, in case we return without Fatal or os.Exit later
  140. if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
  141. log.Fatal("Can only use --cloudlaunch on linux/amd64, for now.")
  142. }
  143. if c.GCEProjectID == "" {
  144. log.Fatal("cloudconfig.GCEProjectID is empty")
  145. }
  146. filename := filepath.Join(os.Getenv("HOME"), "keys", c.GCEProjectID+".key.json")
  147. log.Printf("Using OAuth config from JSON service file: %s", filename)
  148. jwtConf, err := google.JWTConfigFromJSON([]byte(readFile(filename)), append([]string{
  149. storageapi.DevstorageFullControlScope,
  150. compute.ComputeScope,
  151. "https://www.googleapis.com/auth/cloud-platform",
  152. }, c.Scopes...)...)
  153. if err != nil {
  154. log.Fatalf("ConfigFromJSON: %v", err)
  155. }
  156. cl := &cloudLaunch{
  157. Config: c,
  158. oauthClient: jwtConf.Client(oauth2.NoContext),
  159. }
  160. cl.computeService, _ = compute.New(cl.oauthClient)
  161. cl.uploadBinary()
  162. cl.createInstance()
  163. os.Exit(0)
  164. }
  165. func (c *Config) restartLoop() {
  166. if !metadata.OnGCE() {
  167. return
  168. }
  169. if c.RestartPolicy == RestartNever {
  170. return
  171. }
  172. url := c.binaryURL()
  173. var lastEtag string
  174. for {
  175. res, err := http.Head(url + "?" + fmt.Sprint(time.Now().Unix()))
  176. if err != nil {
  177. log.Printf("Warning: %v", err)
  178. time.Sleep(15 * time.Second)
  179. continue
  180. }
  181. etag := res.Header.Get("Etag")
  182. if etag == "" {
  183. log.Printf("Warning, no ETag in response: %v", res)
  184. time.Sleep(15 * time.Second)
  185. continue
  186. }
  187. if lastEtag != "" && etag != lastEtag {
  188. log.Printf("Binary updated; restarting.")
  189. // TODO: more graceful restart, letting systemd own the network connections.
  190. // Then we can finish up requests here.
  191. os.Exit(0)
  192. }
  193. lastEtag = etag
  194. time.Sleep(15 * time.Second)
  195. }
  196. }
  197. // uploadBinary uploads the currently-running Linux binary.
  198. // It crashes if it fails.
  199. func (cl *cloudLaunch) uploadBinary() {
  200. ctx := context.Background()
  201. if cl.BinaryBucket == "" {
  202. log.Fatal("cloudlaunch: Config.BinaryBucket is empty")
  203. }
  204. stoClient, err := storage.NewClient(ctx, option.WithHTTPClient(cl.oauthClient))
  205. if err != nil {
  206. log.Fatal(err)
  207. }
  208. w := stoClient.Bucket(cl.BinaryBucket).Object(cl.binaryObject()).NewWriter(ctx)
  209. if err != nil {
  210. log.Fatal(err)
  211. }
  212. w.ACL = []storage.ACLRule{
  213. // If you don't give the owners access, the web UI seems to
  214. // have a bug and doesn't have access to see that it's public, so
  215. // won't render the "Shared Publicly" link. So we do that, even
  216. // though it's dumb and unnecessary otherwise:
  217. {
  218. Entity: storage.ACLEntity("project-owners-" + cl.GCEProjectID),
  219. Role: storage.RoleOwner,
  220. },
  221. // Public, so our systemd unit can get it easily:
  222. {
  223. Entity: storage.AllUsers,
  224. Role: storage.RoleReader,
  225. },
  226. }
  227. w.CacheControl = "no-cache"
  228. selfPath := getSelfPath()
  229. log.Printf("Uploading %q to %v", selfPath, cl.binaryURL())
  230. f, err := os.Open(selfPath)
  231. if err != nil {
  232. log.Fatal(err)
  233. }
  234. defer f.Close()
  235. n, err := io.Copy(w, f)
  236. if err != nil {
  237. log.Fatal(err)
  238. }
  239. if err := w.Close(); err != nil {
  240. log.Fatal(err)
  241. }
  242. log.Printf("Uploaded %d bytes", n)
  243. }
  244. func getSelfPath() string {
  245. if runtime.GOOS != "linux" {
  246. panic("TODO")
  247. }
  248. v, err := os.Readlink("/proc/self/exe")
  249. if err != nil {
  250. log.Fatal(err)
  251. }
  252. return v
  253. }
  254. func zoneInRegion(zone, regionURL string) bool {
  255. if zone == "" {
  256. panic("empty zone")
  257. }
  258. if regionURL == "" {
  259. panic("empty regionURL")
  260. }
  261. // zone is like "us-central1-f"
  262. // regionURL is like "https://www.googleapis.com/compute/v1/projects/camlistore-website/regions/us-central1"
  263. region := path.Base(regionURL) // "us-central1"
  264. if region == "" {
  265. panic("empty region")
  266. }
  267. return strings.HasPrefix(zone, region)
  268. }
  269. // findIP finds an IP address to use, or returns the empty string if none is found.
  270. // It tries to find a reserved one in the same region where the name of the reserved IP
  271. // is "NAME-ip" and the IP is not in use.
  272. func (cl *cloudLaunch) findIP() string {
  273. // Try to find it by name.
  274. aggAddrList, err := cl.computeService.Addresses.AggregatedList(cl.GCEProjectID).Do()
  275. if err != nil {
  276. log.Fatal(err)
  277. }
  278. // https://godoc.org/google.golang.org/api/compute/v1#AddressAggregatedList
  279. var ip string
  280. IPLoop:
  281. for _, asl := range aggAddrList.Items {
  282. for _, addr := range asl.Addresses {
  283. log.Printf(" addr: %#v", addr)
  284. if addr.Name == cl.Name+"-ip" && addr.Status == "RESERVED" && zoneInRegion(cl.zone(), addr.Region) {
  285. ip = addr.Address
  286. break IPLoop
  287. }
  288. }
  289. }
  290. return ip
  291. }
  292. func (cl *cloudLaunch) createInstance() {
  293. inst := cl.lookupInstance()
  294. if inst != nil {
  295. log.Printf("Instance exists; not re-creating.")
  296. return
  297. }
  298. log.Printf("Instance doesn't exist; creating...")
  299. ip := cl.findIP()
  300. log.Printf("Found IP: %v", ip)
  301. cloudConfig := strings.NewReplacer(
  302. "$NAME", cl.Name,
  303. "$URL", cl.binaryURL(),
  304. "$REBOOT", cl.updateStrategy(),
  305. ).Replace(baseConfig)
  306. instance := &compute.Instance{
  307. Name: cl.instName(),
  308. Description: cl.Name,
  309. MachineType: cl.machineTypeURL(),
  310. Disks: []*compute.AttachedDisk{cl.instanceDisk()},
  311. Tags: &compute.Tags{
  312. Items: []string{"http-server", "https-server"},
  313. },
  314. Metadata: &compute.Metadata{
  315. Items: []*compute.MetadataItems{
  316. {
  317. Key: "user-data",
  318. Value: googleapi.String(cloudConfig),
  319. },
  320. },
  321. },
  322. NetworkInterfaces: []*compute.NetworkInterface{
  323. &compute.NetworkInterface{
  324. AccessConfigs: []*compute.AccessConfig{
  325. &compute.AccessConfig{
  326. Type: "ONE_TO_ONE_NAT",
  327. Name: "External NAT",
  328. NatIP: ip,
  329. },
  330. },
  331. Network: cl.projectAPIURL() + "/global/networks/default",
  332. },
  333. },
  334. ServiceAccounts: []*compute.ServiceAccount{
  335. {
  336. Email: "default",
  337. Scopes: cl.Scopes,
  338. },
  339. },
  340. }
  341. log.Printf("Creating instance...")
  342. op, err := cl.computeService.Instances.Insert(cl.GCEProjectID, cl.zone(), instance).Do()
  343. if err != nil {
  344. log.Fatalf("Failed to create instance: %v", err)
  345. }
  346. opName := op.Name
  347. log.Printf("Created. Waiting on operation %v", opName)
  348. OpLoop:
  349. for {
  350. time.Sleep(2 * time.Second)
  351. op, err := cl.computeService.ZoneOperations.Get(cl.GCEProjectID, cl.zone(), opName).Do()
  352. if err != nil {
  353. log.Fatalf("Failed to get op %s: %v", opName, err)
  354. }
  355. switch op.Status {
  356. case "PENDING", "RUNNING":
  357. log.Printf("Waiting on operation %v", opName)
  358. continue
  359. case "DONE":
  360. if op.Error != nil {
  361. for _, operr := range op.Error.Errors {
  362. log.Printf("Error: %+v", operr)
  363. }
  364. log.Fatalf("Failed to start.")
  365. }
  366. log.Printf("Success. %+v", op)
  367. break OpLoop
  368. default:
  369. log.Fatalf("Unknown status %q: %+v", op.Status, op)
  370. }
  371. }
  372. inst, err = cl.computeService.Instances.Get(cl.GCEProjectID, cl.zone(), cl.instName()).Do()
  373. if err != nil {
  374. log.Fatalf("Error getting instance after creation: %v", err)
  375. }
  376. ij, _ := json.MarshalIndent(inst, "", " ")
  377. log.Printf("%s", ij)
  378. log.Printf("Instance created.")
  379. os.Exit(0)
  380. }
  381. // returns nil if instance doesn't exist.
  382. func (cl *cloudLaunch) lookupInstance() *compute.Instance {
  383. inst, err := cl.computeService.Instances.Get(cl.GCEProjectID, cl.zone(), cl.instName()).Do()
  384. if ae, ok := err.(*googleapi.Error); ok && ae.Code == 404 {
  385. return nil
  386. } else if err != nil {
  387. log.Fatalf("Instances.Get: %v", err)
  388. }
  389. return inst
  390. }
  391. func (cl *cloudLaunch) instanceDisk() *compute.AttachedDisk {
  392. imageURL, err := gceutil.CoreOSImageURL(cl.oauthClient)
  393. if err != nil {
  394. log.Fatalf("error looking up latest CoreOS stable image: %v", err)
  395. }
  396. diskName := cl.instName() + "-coreos-stateless-pd"
  397. var diskType string
  398. if cl.SSD {
  399. diskType = cl.projectAPIURL() + "/zones/" + cl.zone() + "/diskTypes/pd-ssd"
  400. }
  401. return &compute.AttachedDisk{
  402. AutoDelete: true,
  403. Boot: true,
  404. Type: "PERSISTENT",
  405. InitializeParams: &compute.AttachedDiskInitializeParams{
  406. DiskName: diskName,
  407. SourceImage: imageURL,
  408. DiskSizeGb: 50,
  409. DiskType: diskType,
  410. },
  411. }
  412. }