├── .gocfg ├── gopaths └── vendor.json ├── .gitignore ├── misc ├── prevmtable-cvm.yaml ├── create-hook.bash ├── GUIDE.md ├── prevmtable-up.bash └── prevmtable-config.rjson ├── Dockerfile ├── CONTRIBUTING ├── src └── prevmtable │ ├── main.go │ └── vmtable │ ├── config.go │ └── vmtable.go ├── run_deploy.bash ├── README.md └── LICENSE /.gocfg/gopaths: -------------------------------------------------------------------------------- 1 | vendor 2 | . 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | pkg 3 | tmp 4 | *.sublime-workspace 5 | vendor 6 | -------------------------------------------------------------------------------- /misc/prevmtable-cvm.yaml: -------------------------------------------------------------------------------- 1 | version: v1beta2 2 | containers: 3 | - name: prevmtable 4 | image: skelterjohn/prevmtable 5 | -------------------------------------------------------------------------------- /misc/create-hook.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | gcloud compute target-pools add-instances us-central1/prevmtable-pool \ 4 | --instances /$PROJECT/$ZONE/$NAME 5 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM google/cloud-sdk 2 | 3 | RUN apt-get update -q && apt-get install -qyy ca-certificates 4 | 5 | COPY bin/prevmtable /bin/prevmtable 6 | ENTRYPOINT ["/bin/prevmtable"] 7 | -------------------------------------------------------------------------------- /misc/GUIDE.md: -------------------------------------------------------------------------------- 1 | #user's guide# 2 | 3 | The easiest way to put prevmtable into action does not involve building any code. The dockerhub skelterjohn/prevmtable image will be kept reasonably up to date, and at some point may be on autobuild. 4 | 5 | If you have base a real system on prevmtable, you should build the image yourself. 6 | 7 | The `prevmtable-up.bash` script will maintain 3 preemptible f1-micro VMs in us-central1-b or us-central1-c, and that VM run a very simple "Hello, world!" web server. 8 | 9 | Along with the preemptible VMs, it will also create the prevmtable-master, using kubernetes to keep it going. The prevmtable master runs the prevmtable service, and will create and delete VMs as needed. 10 | 11 | A firewall rule is created to allow TCP on :8080 to connect to those VMs, and a forwarding rule and target pool are created for load balancing. A prevmtable post-create hook adds new instances to the target pool, creating an accessible load-balanced cluster. 12 | -------------------------------------------------------------------------------- /misc/prevmtable-up.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -x 4 | 5 | 6 | gcloud compute forwarding-rules delete -q us-central1/prevmtable-rule 7 | 8 | gcloud compute target-pools delete -q us-central1/prevmtable-pool 9 | gcloud compute target-pools create us-central1/prevmtable-pool || exit 10 | 11 | gcloud compute forwarding-rules create us-central1/prevmtable-rule \ 12 | --target-pool us-central1/prevmtable-pool || exit 13 | 14 | gcloud compute firewall-rules create prevmtable-http \ 15 | --target-tags prevmtable-http \ 16 | --source-ranges 0.0.0.0/0 \ 17 | --allow tcp:8080 18 | 19 | gcloud compute project-info add-metadata \ 20 | --metadata-from-file prevmtable=prevmtable-config.rjson || exit 21 | gcloud compute project-info add-metadata \ 22 | --metadata-from-file prevmtable-create-hook=create-hook.bash || exit 23 | 24 | gcloud compute instances create us-central1-b/prevmtable-master \ 25 | --image container-vm \ 26 | --metadata-from-file google-container-manifest=prevmtable-cvm.yaml \ 27 | --machine-type f1-micro \ 28 | --scopes https://www.googleapis.com/auth/cloud-platform || exit 29 | -------------------------------------------------------------------------------- /.gocfg/vendor.json: -------------------------------------------------------------------------------- 1 | { 2 | "GitRepos": { 3 | "vendor/src/github.com/rogpeppe/rjson": { 4 | "URI": "https://github.com/rogpeppe/rjson", 5 | "Ref": "6637e5c2627a5f098523b71a450a8fb72e6e3261" 6 | }, 7 | "vendor/src/github.com/satori/go.uuid": { 8 | "URI": "https://github.com/satori/go.uuid", 9 | "Ref": "7c7f2020c4c9491594b85767967f4619c2fa75f9" 10 | }, 11 | "vendor/src/golang.org/x/net": { 12 | "URI": "https://go.googlesource.com/net", 13 | "Ref": "72bfdce4720b8edba5098bb04136d3d6afa992b3" 14 | }, 15 | "vendor/src/golang.org/x/oauth2": { 16 | "URI": "https://go.googlesource.com/oauth2", 17 | "Ref": "f98d0160877ab4712b906626425ed8b0b320907c" 18 | }, 19 | "vendor/src/google.golang.org/api": { 20 | "URI": "https://code.googlesource.com/google-api-go-client", 21 | "Ref": "d56f328dc27a4097cd0fc535e7c77807f48a2e84" 22 | }, 23 | "vendor/src/google.golang.org/cloud": { 24 | "URI": "https://code.googlesource.com/gocloud", 25 | "Ref": "ff3a09588427c2aaf64d56ad3bb8e8e24bdb52ac" 26 | }, 27 | "vendor/src/gopkg.in/yaml.v2": { 28 | "URI": "https://gopkg.in/yaml.v2", 29 | "Ref": "49c95bdc21843256fb6c4e0d370a05f24a0bf213" 30 | } 31 | }, 32 | "MercurialRepos": {} 33 | } 34 | -------------------------------------------------------------------------------- /CONTRIBUTING: -------------------------------------------------------------------------------- 1 | Want to contribute? Great! First, read this page (including the small print at the end). 2 | 3 | ### Before you contribute 4 | Before we can use your code, you must sign the 5 | [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) 6 | (CLA), which you can do online. The CLA is necessary mainly because you own the 7 | copyright to your changes, even after your contribution becomes part of our 8 | codebase, so we need your permission to use and distribute your code. We also 9 | need to be sure of various other things—for instance that you'll tell us if you 10 | know that your code infringes on other people's patents. You don't have to sign 11 | the CLA until after you've submitted your code for review and a member has 12 | approved it, but you must do it before we can put your code into our codebase. 13 | Before you start working on a larger contribution, you should get in touch with 14 | us first through the issue tracker with your idea so that we can help out and 15 | possibly guide you. Coordinating up front makes it much easier to avoid 16 | frustration later on. 17 | 18 | ### Code reviews 19 | All submissions, including submissions by project members, require review. We 20 | use Github pull requests for this purpose. 21 | 22 | ### The small print 23 | Contributions made by corporations are covered by a different agreement than 24 | the one above, the Software Grant and Corporate Contributor License Agreement. 25 | -------------------------------------------------------------------------------- /misc/prevmtable-config.rjson: -------------------------------------------------------------------------------- 1 | { 2 | secondsToRest: 30 3 | secondsForExhaustion: 120 4 | prefix: "delete-" 5 | allowedzones: [ 6 | "us-central1-b" 7 | "us-central1-c" 8 | ] 9 | hooks: { 10 | create: "prevmtable-create-hook" 11 | } 12 | targetVMCount: 3 13 | instance: { 14 | metadata: { 15 | items: [ 16 | { 17 | key: "startup-script" 18 | value: "docker run --rm -p 8080:8080 skelterjohn/http" 19 | } 20 | ] 21 | } 22 | tags: { 23 | items: [ 24 | "prevmtable-http" 25 | ] 26 | } 27 | machineType: "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/machineTypes/f1-micro" 28 | name: "{name}" 29 | disks: [ 30 | { 31 | autoDelete: true 32 | boot: true 33 | initializeParams: { 34 | sourceImage: "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-stable-647-0-0-v20150512" 35 | } 36 | mode: "READ_WRITE" 37 | type: "PERSISTENT" 38 | } 39 | ] 40 | networkInterfaces: [ 41 | { 42 | accessConfigs: [ 43 | { 44 | name: "external-nat" 45 | type: "ONE_TO_ONE_NAT" 46 | } 47 | ] 48 | network: "https://www.googleapis.com/compute/v1/projects/{project}/global/networks/default" 49 | } 50 | ] 51 | scheduling: { 52 | automaticRestart: false 53 | preemptible: true 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/prevmtable/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 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 | // http://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 | "fmt" 19 | "log" 20 | "os" 21 | "time" 22 | 23 | "prevmtable/vmtable" 24 | ) 25 | 26 | func orExit(err error) { 27 | if err == nil { 28 | return 29 | } 30 | fmt.Fprintln(os.Stderr, err) 31 | os.Exit(1) 32 | } 33 | 34 | func main() { 35 | t, err := vmtable.NewVMTable() 36 | orExit(err) 37 | 38 | if t.Config.SecondsToRest == 0 { 39 | t.Config.SecondsToRest = 5 40 | } 41 | 42 | ticker := time.Tick(time.Duration(int(time.Second) * t.Config.SecondsToRest)) 43 | for { 44 | select { 45 | case <-ticker: 46 | fmt.Fprintf(os.Stderr, "\r[%v] ", time.Now().Format("2006-01-02 15:04:05 -0700")) 47 | if err := t.RefreshConfig(); err != nil { 48 | log.Printf("error refreshing config: %v", err) 49 | continue 50 | } 51 | t.RefreshVMs() 52 | t.RightSize() 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/prevmtable/vmtable/config.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 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 | // http://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 vmtable 16 | 17 | import ( 18 | "errors" 19 | "io/ioutil" 20 | "log" 21 | "os" 22 | "os/exec" 23 | "strings" 24 | 25 | "github.com/rogpeppe/rjson" 26 | compute_v1 "google.golang.org/api/compute/v1" 27 | "google.golang.org/cloud/compute/metadata" 28 | ) 29 | 30 | var ( 31 | NotPreemtibleError = errors.New("instance template in config is not preemptible") 32 | ) 33 | 34 | type Config struct { 35 | // Seconds between updates. 36 | SecondsToRest int 37 | 38 | // Seconds to wait before retrying a zone that got exhausted. 39 | SecondsForExhaustion int 40 | 41 | // Prefix to put on the name of each VM. 42 | Prefix string 43 | 44 | // The zones to create VMs in. 45 | AllowedZones []string 46 | 47 | // Project metadata attributes containing script hooks. 48 | Hooks struct { 49 | Create string 50 | Delete string 51 | Vanished string 52 | Exhausted string 53 | } 54 | 55 | // Number of VMs to maintain. If there are more, delete. If there are fewer, create. 56 | TargetVMCount int 57 | 58 | // Template to use for instance creation. 59 | Instance rjson.RawMessage 60 | } 61 | 62 | func ConfigFromMetadata() (Config, error) { 63 | attrName := os.Getenv("PREVMTABLE_ATTRIBUTE") 64 | if attrName == "" { 65 | attrName = "prevmtable" 66 | } 67 | 68 | cfgData, err := metadata.ProjectAttributeValue(attrName) 69 | if err != nil { 70 | return Config{}, err 71 | } 72 | 73 | var cfg Config 74 | 75 | if err := rjson.NewDecoder(strings.NewReader(cfgData)).Decode(&cfg); err != nil { 76 | return Config{}, err 77 | } 78 | 79 | i := &compute_v1.Instance{} 80 | instanceData := string(cfg.Instance) 81 | instanceData = strings.Replace(instanceData, "{project}", "proj", -1) 82 | instanceData = strings.Replace(instanceData, "{zone}", "zone", -1) 83 | instanceData = strings.Replace(instanceData, "{name}", "name", -1) 84 | 85 | if err := rjson.Unmarshal([]byte(instanceData), i); err != nil { 86 | return cfg, err 87 | } 88 | 89 | if !i.Scheduling.Preemptible { 90 | return cfg, NotPreemtibleError 91 | } 92 | 93 | return cfg, nil 94 | } 95 | 96 | func (c Config) CreateHook(project, zone, name string) error { 97 | return c.execHook( 98 | "create", 99 | c.Hooks.Create, 100 | []string{ 101 | "PROJECT=" + project, 102 | "ZONE=" + zone, 103 | "NAME=" + name, 104 | }) 105 | } 106 | 107 | func (c Config) DeleteHook(project, zone, name string) error { 108 | return c.execHook( 109 | "delete", 110 | c.Hooks.Delete, 111 | []string{ 112 | "PROJECT=" + project, 113 | "ZONE=" + zone, 114 | "NAME=" + name, 115 | }) 116 | } 117 | 118 | func (c Config) VanishedHook(project, zone, name string) error { 119 | return c.execHook( 120 | "vanished", 121 | c.Hooks.Vanished, 122 | []string{ 123 | "PROJECT=" + project, 124 | "ZONE=" + zone, 125 | "NAME=" + name, 126 | }) 127 | } 128 | 129 | func (c Config) ExhaustedHook(project, zone string) error { 130 | return c.execHook( 131 | "exhausted", 132 | c.Hooks.Exhausted, 133 | []string{ 134 | "PROJECT=" + project, 135 | "ZONE=" + zone, 136 | }) 137 | } 138 | 139 | func (c Config) execHook(hookType, scriptAttribute string, env []string) error { 140 | if scriptAttribute == "" { 141 | return nil 142 | } 143 | script, err := metadata.ProjectAttributeValue(scriptAttribute) 144 | if err != nil { 145 | return err 146 | } 147 | 148 | scriptFile, err := ioutil.TempFile("", "hook-") 149 | if err != nil { 150 | return err 151 | } 152 | scriptPath := scriptFile.Name() 153 | if _, err := scriptFile.WriteString(script); err != nil { 154 | return err 155 | } 156 | scriptFile.Close() 157 | if err := os.Chmod(scriptPath, 0755); err != nil { 158 | return err 159 | } 160 | log.Printf("executing %s hook with %q: %s", hookType, scriptPath, env) 161 | cmd := exec.Command(scriptPath) 162 | cmd.Env = append(env, os.Environ()...) 163 | cmd.Stdout = os.Stdout 164 | cmd.Stderr = os.Stderr 165 | return cmd.Run() 166 | } 167 | 168 | func Project() (string, error) { 169 | return metadata.ProjectID() 170 | } 171 | -------------------------------------------------------------------------------- /run_deploy.bash: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # Copyright 2015 Google Inc. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | echo "compiling the binary..." 18 | wgo install prevmtable || exit 19 | 20 | echo "building the container..." 21 | docker build -t deploy . &> /dev/null || exit 22 | 23 | project=$(gcloud config list core/project --format=text | cut -d ' ' -f 2) 24 | 25 | echo "running the faux metadata container..." 26 | metadata=$(mktemp) 27 | cat > $metadata << EOM 28 | computeMetadata: 29 | v1: &V1 30 | project: 31 | projectId: &PROJECT-ID 32 | $project 33 | numericProjectId: 1234 34 | attributes: 35 | prevmtable-post-create: | 36 | #!/bin/bash 37 | echo "VM created: /\$PROJECT/\$ZONE/\$NAME" 38 | prevmtable-post-delete: | 39 | #!/bin/bash 40 | echo "VM deleted: /\$PROJECT/\$ZONE/\$NAME" 41 | prevmtable-vanished: | 42 | #!/bin/bash 43 | echo "VM vanished: /\$PROJECT/\$ZONE/\$NAME" 44 | prevmtable-exhausted: | 45 | #!/bin/bash 46 | echo "Zone exhausted: /\$PROJECT/\$ZONE" 47 | prevmtable: | 48 | { 49 | secondsToRest: 30 50 | secondsForExhaustion: 120 51 | prefix: "delete-" 52 | allowedzones: [ 53 | "us-central1-b" 54 | ] 55 | hooks: { 56 | create: "prevmtable-post-create" 57 | delete: "prevmtable-post-delete" 58 | vanished: "prevmtable-vanished" 59 | exhausted: "prevmtable-exhausted" 60 | } 61 | targetVMCount: 1 62 | instance: { 63 | metadata: { 64 | items: [ 65 | { 66 | key: "startup-script" 67 | value: "docker run --rm -p 8080:8080 skelterjohn/http" 68 | } 69 | ] 70 | } 71 | tags: { 72 | items: [ 73 | "prevmtable-http" 74 | ] 75 | } 76 | machineType: "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/machineTypes/f1-micro" 77 | name: "{name}" 78 | disks: [ 79 | { 80 | autoDelete: true 81 | boot: true 82 | initializeParams: { 83 | sourceImage: "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-stable-647-0-0-v20150512" 84 | } 85 | mode: "READ_WRITE" 86 | type: "PERSISTENT" 87 | } 88 | ] 89 | networkInterfaces: [ 90 | { 91 | accessConfigs: [ 92 | { 93 | name: "external-nat" 94 | type: "ONE_TO_ONE_NAT" 95 | } 96 | ] 97 | network: "https://www.googleapis.com/compute/v1/projects/{project}/global/networks/default" 98 | } 99 | ] 100 | scheduling: { 101 | automaticRestart: false 102 | preemptible: true 103 | } 104 | } 105 | } 106 | instance: 107 | projectId: *PROJECT-ID 108 | hostname: deploy_machine 109 | machineType: n1-standard-1 110 | maintenanceEvent: NONE 111 | serviceAccounts: 112 | default: *DEFAULT 113 | prevmtable@googleserviceaccount.com: &DEFAULT 114 | email: prevmtable@googleserviceaccount.com 115 | scopes: 116 | - https://www.googleapis.com/auth/cloud-platform 117 | zone: us-central1-a 118 | EOM 119 | 120 | metadata_id=$(docker run \ 121 | -d \ 122 | --name metadata \ 123 | -v $metadata:/prevmtable/manifest.yaml \ 124 | gcr.io/_b_containers_qa/faux-metadata:latest \ 125 | -manifest_file=/prevmtable/manifest.yaml \ 126 | -refresh_token=$(gcloud auth print-refresh-token)) 127 | 128 | docker run \ 129 | --rm \ 130 | --link metadata:metadata.google.internal \ 131 | --env GCE_METADATA_HOST=metadata.google.internal \ 132 | --env PREVMTABLE_ATTRIBUTE=prevmtable \ 133 | deploy 134 | 135 | docker rm -f metadata &> /dev/null 136 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #prevmtable# 2 | 3 | Because not having enough VMs is preventable. 4 | 5 | Prevmtable manages a pool of preemptible Google Compute Engine (GCE) VMs across zones. The VMs are created from a provided template, and prevmtable will balance them (round-robin style) across zones. 6 | 7 | If a zone's preemptible machines are exhausted, prevmtable will leave that zone alone for a set amount of time, and create new VMs in the remaining zones in the meantime. 8 | 9 | Prevmtable is effectively stateless. If it goes down, you can bring it up and it will continue on as before. The only loss is that VMs killed while prevmtable was not running will not be reported. 10 | 11 | ##test drive## 12 | cd into the misc directory and run prevmtable-up.bash to create a small load-balanced cluster of preemptible VMs serving http. 13 | 14 | ##configuration## 15 | 16 | Configuration of the pool is managed through GCE project metadata. The project metadata can be updated at any time to dynamically change prevmtable's configuration - it will be checked again during the next poll cycle. 17 | 18 | The project metadata attribute "prevmtable" (overridable with the environment variable PREVMTABLE_ATTRIBUTE) must be an rjson (https://github.com/rogpeppe/rjson) document that matches the following structure. 19 | 20 | type Config struct { 21 | // Seconds between updates. 22 | SecondsToRest int 23 | 24 | // Seconds to wait before retrying a zone that got exhausted. 25 | SecondsForExhaustion int 26 | 27 | // Prefix to put on the name of each VM. 28 | Prefix string 29 | 30 | // The zones in which VMs may be created. 31 | AllowedZones []string 32 | 33 | // Project metadata attributes containing script hooks. 34 | Hooks struct { 35 | Create string 36 | Delete string 37 | Vanished string 38 | Exhausted string 39 | } 40 | 41 | // Number of VMs to maintain. If there are more, delete. If there are fewer, create. 42 | TargetVMCount int 43 | 44 | // Template to use for instance creation. 45 | Instance rjson.RawMessage 46 | } 47 | 48 | If the Hooks are given values, prevmtable will look in project metadata attributes for scripts to run. 49 | 50 | The `Instance` component will be decoded into an instance of type http://godoc.org/google.golang.org/api/compute/v1#Instance. 51 | 52 | If the strings "{project}", "{zone}", and "{name}" are somewhere in the instance template, they will be replaced with the appropriate project, zone, and name during individual instance creation. See the "example config" section below for a starting point. 53 | 54 | ###hooks### 55 | 56 | Prevmtable currently has four hooks, for instance creation, deletion, loss, and for zone exhaustion. Put a script (don't forget, eg, the "#!/bin/bash" at the top) in a project metadata attribute pointed to by the hooks in the config. 57 | 58 | The script hook will be downloaded and run each time the hook fires, so the project metadata can be safely changed during prevmtable operation. 59 | 60 | ####Create#### 61 | 62 | $PROJECT: The GCP project. 63 | $ZONE: The GCE zone. 64 | $NAME: The GCE instance name. 65 | 66 | The create hook is called whenever prevmtable creates a new instance. 67 | 68 | ####Delete#### 69 | 70 | $PROJECT: The GCP project. 71 | $ZONE: The GCE zone. 72 | $NAME: The GCE instance name. 73 | 74 | The delete hook is called whenever prevmtable deletes an old instance. 75 | 76 | ####Vanished#### 77 | 78 | $PROJECT: The GCP project. 79 | $ZONE: The GCE zone. 80 | $NAME: The GCE instance name. 81 | 82 | The vanished hook is called whenever prevmtable notices that an instance disappeared from one update to the next, and it was not deleted by prevmtable. 83 | 84 | ####Exhausted#### 85 | 86 | $PROJECT: The GCP project. 87 | $ZONE: The GCE zone. 88 | 89 | The exhausted hook is called whenever prevmtable tries to create an instance in a zone, but the operation fails with ZONE_RESOURCE_POOL_EXHAUSTED. 90 | 91 | ##building## 92 | 93 | Revision pinning is done with https://github.com/skelterjohn/wgo. Run `wgo restore` in the cloned github repo to fetch dependencies, and `wgo install prevmtable` to build. 94 | 95 | Or, set GOPATH to be the root of this repository, and test your luck with `go get prevmtable`. Maybe it will work? 96 | 97 | ###docker integration### 98 | 99 | After building the binary for linux 64bit (GOOS=linux, GOARCH=amd64, rebuild go, rebuild the binary), the Dockerfile can be used to create a container that will run prevmtable. 100 | 101 | ##running## 102 | 103 | Running either the binary or the container in context with GCE metadata and metadata-provided credentials will allow prevmtable to manage a VM pool. 104 | 105 | The `run_deploy.bash` script demonstrates a way to have GCE metadata context without running from GCE, using a false metadata container that is linked with the prevmtable container. But, for something reliable, you'd probably want kubernetes (or something) to keep the prevmtable container going on a GCE VM. 106 | 107 | ###example config### 108 | 109 | The config below will keep one preemptible f1-micro coreos instance running in either us-central1-b or us-central1-f. Additionally, it has a startup script that runs a very simple "Hello, world!" http server, and a tag that can be used to manage its firewall status. 110 | 111 | { 112 | secondsToRest: 30 113 | secondsForExhaustion: 120 114 | prefix: "delete-" 115 | allowedzones: [ 116 | "us-central1-b" 117 | ] 118 | targetVMCount: 1 119 | instance: { 120 | metadata: { 121 | items: [ 122 | { 123 | key: "startup-script" 124 | value: "docker run --rm -p 8080:8080 skelterjohn/http" 125 | } 126 | ] 127 | } 128 | tags: { 129 | items: [ 130 | "prevmtable-http" 131 | ] 132 | } 133 | machineType: "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/machineTypes/f1-micro" 134 | name: "{name}" 135 | disks: [ 136 | { 137 | autoDelete: true 138 | boot: true 139 | initializeParams: { 140 | sourceImage: "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-stable-647-0-0-v20150512" 141 | } 142 | mode: "READ_WRITE" 143 | type: "PERSISTENT" 144 | } 145 | ] 146 | networkInterfaces: [ 147 | { 148 | accessConfigs: [ 149 | { 150 | name: "external-nat" 151 | type: "ONE_TO_ONE_NAT" 152 | } 153 | ] 154 | network: "https://www.googleapis.com/compute/v1/projects/{project}/global/networks/default" 155 | } 156 | ] 157 | scheduling: { 158 | automaticRestart: false 159 | preemptible: true 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/prevmtable/vmtable/vmtable.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 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 | // http://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 vmtable 16 | 17 | import ( 18 | "fmt" 19 | "log" 20 | "math/rand" 21 | "strings" 22 | "sync" 23 | "time" 24 | 25 | "github.com/rogpeppe/rjson" 26 | "github.com/satori/go.uuid" 27 | "golang.org/x/net/context" 28 | "golang.org/x/oauth2" 29 | "golang.org/x/oauth2/google" 30 | compute_v1 "google.golang.org/api/compute/v1" 31 | ) 32 | 33 | type VMTable struct { 34 | sync.Mutex 35 | 36 | Config Config 37 | compute *compute_v1.Service 38 | project string 39 | 40 | previousZoneInstances map[string][]*compute_v1.Instance 41 | ZoneInstances map[string][]*compute_v1.Instance 42 | 43 | ZoneExhaustions map[string]time.Time 44 | } 45 | 46 | func NewVMTable() (*VMTable, error) { 47 | t := &VMTable{ 48 | ZoneInstances: map[string][]*compute_v1.Instance{}, 49 | ZoneExhaustions: map[string]time.Time{}, 50 | } 51 | 52 | tokenSource := google.ComputeTokenSource("") 53 | client := oauth2.NewClient(context.Background(), tokenSource) 54 | var err error 55 | if t.compute, err = compute_v1.New(client); err != nil { 56 | return nil, err 57 | } 58 | if t.project, err = Project(); err != nil { 59 | return nil, err 60 | } 61 | return t, nil 62 | } 63 | 64 | func (t *VMTable) FreshZones() []string { 65 | // technically we don't need to lock/unlock here, but it doesn't hurt. 66 | t.Lock() 67 | defer t.Unlock() 68 | 69 | now := time.Now() 70 | var zones []string 71 | for _, z := range t.Config.AllowedZones { 72 | exhaustionTime, ok := t.ZoneExhaustions[z] 73 | if !ok { 74 | zones = append(zones, z) 75 | continue 76 | } 77 | diff := now.Sub(exhaustionTime) 78 | if int(diff.Seconds()) > t.Config.SecondsForExhaustion { 79 | delete(t.ZoneExhaustions, z) 80 | zones = append(zones, z) 81 | } 82 | } 83 | return zones 84 | } 85 | 86 | func (t *VMTable) RefreshConfig() error { 87 | var err error 88 | t.Config, err = ConfigFromMetadata() 89 | return err 90 | } 91 | 92 | func (t *VMTable) RefreshVMs() { 93 | t.previousZoneInstances = t.ZoneInstances 94 | t.ZoneInstances = map[string][]*compute_v1.Instance{} 95 | for _, zone := range t.Config.AllowedZones { 96 | if err := t.RefreshVMsInZone(zone); err != nil { 97 | log.Printf("error refreshing zone %s: %v", zone, err) 98 | } 99 | } 100 | for pz, pzis := range t.previousZoneInstances { 101 | if len(pzis) == 0 { 102 | continue 103 | } 104 | zis, _ := t.ZoneInstances[pz] 105 | currentNames := map[string]bool{} 106 | for _, zi := range zis { 107 | currentNames[zi.Name] = true 108 | } 109 | anyInZone := false 110 | for _, pzi := range pzis { 111 | if _, ok := currentNames[pzi.Name]; !ok { 112 | log.Printf("/%s/%s/%s went down", t.project, pz, pzi.Name) 113 | if err := t.Config.VanishedHook(t.project, pz, pzi.Name); err != nil { 114 | log.Printf("error calling vanished hook: %v", err) 115 | } 116 | } else { 117 | anyInZone = true 118 | } 119 | } 120 | if !anyInZone { 121 | log.Printf("all instances in /%s/%s went down", t.project, pz) 122 | } 123 | } 124 | } 125 | 126 | func (t *VMTable) RefreshVMsInZone(zone string) error { 127 | result, err := t.compute.Instances.List(t.project, zone).Do() 128 | if err != nil { 129 | return err 130 | } 131 | for _, item := range result.Items { 132 | // skip instances we don't know about 133 | if !strings.HasPrefix(item.Name, t.Config.Prefix) { 134 | continue 135 | } 136 | 137 | // skip instances that aren't running or won't be running 138 | if item.Status == "STOPPING" || item.Status == "TERMINATED" { 139 | continue 140 | } 141 | zis, _ := t.ZoneInstances[zone] 142 | zis = append(zis, item) 143 | t.ZoneInstances[zone] = zis 144 | } 145 | return nil 146 | } 147 | 148 | func (t *VMTable) RightSize() { 149 | activeVMs := 0 150 | for _, zis := range t.ZoneInstances { 151 | activeVMs += len(zis) 152 | } 153 | 154 | if activeVMs == t.Config.TargetVMCount { 155 | return 156 | } 157 | 158 | if activeVMs < t.Config.TargetVMCount { 159 | t.createVMs(t.Config.TargetVMCount - activeVMs) 160 | } else { 161 | t.deleteVMs(activeVMs - t.Config.TargetVMCount) 162 | } 163 | } 164 | 165 | func (t *VMTable) createVMs(count int) { 166 | var wg sync.WaitGroup 167 | wg.Add(count) 168 | offset := rand.Int() 169 | zones := t.FreshZones() 170 | if len(zones) == 0 { 171 | log.Print("all zones exhausted") 172 | return 173 | } 174 | for i := 0; i < count; i++ { 175 | zone := zones[(offset+i)%len(zones)] 176 | go func(zone string) { 177 | t.createVM(zone) 178 | wg.Done() 179 | }(zone) 180 | } 181 | wg.Wait() 182 | } 183 | 184 | func (t *VMTable) deleteVMs(count int) { 185 | type nz struct { 186 | name string 187 | zone string 188 | } 189 | 190 | var allInstances []nz 191 | for z, zis := range t.ZoneInstances { 192 | for _, i := range zis { 193 | allInstances = append(allInstances, nz{i.Name, z}) 194 | } 195 | } 196 | var wg sync.WaitGroup 197 | wg.Add(count) 198 | for count > 0 { 199 | i := rand.Intn(len(allInstances)) 200 | go func(i nz) { 201 | t.deleteVM(i.zone, i.name) 202 | wg.Done() 203 | }(allInstances[i]) 204 | allInstances = append(allInstances[:i], allInstances[i+1:]...) 205 | count-- 206 | } 207 | 208 | wg.Wait() 209 | } 210 | 211 | func (t *VMTable) createVM(zone string) { 212 | id := uuid.NewV4() 213 | name := fmt.Sprintf("%s%s", t.Config.Prefix, id) 214 | 215 | i := &compute_v1.Instance{} 216 | instanceData := string(t.Config.Instance) 217 | instanceData = strings.Replace(instanceData, "{project}", t.project, -1) 218 | instanceData = strings.Replace(instanceData, "{zone}", zone, -1) 219 | instanceData = strings.Replace(instanceData, "{name}", name, -1) 220 | 221 | if err := rjson.Unmarshal([]byte(instanceData), i); err != nil { 222 | log.Printf("error decoding instance template: %s", err) 223 | return 224 | } 225 | 226 | log.Printf("inserting instance /%s/%s/%s", t.project, zone, i.Name) 227 | op, err := t.compute.Instances.Insert(t.project, zone, i).Do() 228 | if err != nil { 229 | log.Printf("error inserting instance: %s", err) 230 | return 231 | } 232 | 233 | for range time.Tick(2 * time.Second) { 234 | op, err = t.compute.ZoneOperations.Get(t.project, zone, op.Name).Do() 235 | if err != nil { 236 | log.Printf("error fetching operation: %v", err) 237 | return 238 | } 239 | 240 | if op.Status == "RUNNING" || op.Status == "PENDING" { 241 | continue 242 | } 243 | if op.Status == "DONE" { 244 | break 245 | } 246 | } 247 | if op.Error != nil { 248 | for _, opError := range op.Error.Errors { 249 | if opError.Code == "ZONE_RESOURCE_POOL_EXHAUSTED" { 250 | t.Lock() 251 | t.ZoneExhaustions[zone] = time.Now() 252 | t.Unlock() 253 | log.Printf("zone %s exhausted", zone) 254 | if err := t.Config.ExhaustedHook(t.project, zone); err != nil { 255 | log.Printf("error calling exhausted hook: %v", err) 256 | } 257 | return 258 | } 259 | log.Printf("op error inserting instance: %s", opError.Code) 260 | } 261 | } 262 | if err := t.Config.CreateHook(t.project, zone, name); err != nil { 263 | log.Printf("error calling create hook: %v", err) 264 | } 265 | } 266 | 267 | func (t *VMTable) deleteVM(zone, name string) { 268 | log.Printf("deleting instance /%s/%s/%s", t.project, zone, name) 269 | op, err := t.compute.Instances.Delete(t.project, zone, name).Do() 270 | if err != nil { 271 | log.Printf("error deleting instance: %s", err) 272 | return 273 | } 274 | for range time.Tick(2 * time.Second) { 275 | op, err = t.compute.ZoneOperations.Get(t.project, zone, op.Name).Do() 276 | if err != nil { 277 | log.Printf("error fetching operation: %v", err) 278 | return 279 | } 280 | 281 | if op.Status == "RUNNING" || op.Status == "PENDING" { 282 | continue 283 | } 284 | if op.Status == "DONE" { 285 | break 286 | } 287 | } 288 | if op.Error != nil { 289 | for _, opError := range op.Error.Errors { 290 | log.Printf("op error inserting instance: %s", opError.Code) 291 | } 292 | } 293 | 294 | // remove the instance from the zone instance list, so it isn't reported as vanished. 295 | t.Lock() 296 | zis := t.ZoneInstances[zone] 297 | for i, n := range zis { 298 | if n.Name == name { 299 | zis = append(zis[:i], zis[i+1:]...) 300 | break 301 | } 302 | } 303 | t.ZoneInstances[zone] = zis 304 | t.Unlock() 305 | 306 | if err := t.Config.DeleteHook(t.project, zone, name); err != nil { 307 | log.Printf("error calling delete hook: %v", err) 308 | } 309 | } 310 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------