├── LICENSE ├── README.md └── swarm-cluster-state-manager ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── api.go ├── cluster_state_manager.go ├── docker-compose.yml └── main.go /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # code-snippets 2 | 3 | Random code snippets for talks and blogs. 4 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## How to become a contributor and submit your own code 2 | 3 | ### Contributor License Agreements 4 | 5 | We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles. 6 | 7 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 8 | 9 | * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). 10 | * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). 11 | 12 | Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests. 13 | 14 | ***NOTE***: Only original source code from you and other people that have signed the CLA can be accepted into the main repository. This policy does not apply to [third_party](https://github.com/kubernetes/kubernetes/tree/master/third_party). 15 | 16 | ### Contributing A Patch 17 | 18 | 1. Submit an issue describing your proposed change to the repo in question. 19 | 1. The repo owner will respond to your issue promptly. 20 | 1. If your proposed change is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above). 21 | 1. Fork the desired repo, develop and test your code changes. 22 | 1. Submit a pull request. 23 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM scratch 2 | MAINTAINER Kelsey Hightower 3 | COPY swarm-cluster-state-manager /swarm-cluster-state-manager 4 | ENTRYPOINT ["/swarm-cluster-state-manager"] 5 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/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 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/README.md: -------------------------------------------------------------------------------- 1 | # Docker Swarm Cluster State Manager 2 | 3 | This is not an official Google product. 4 | 5 | ## Overview 6 | 7 | The Swarm cluster state manager is a simple prototype that demonstrates how cluster state could be managed for Docker Swarm. The ideas for this prototype are based on the Kubernetes pod replication controller. 8 | 9 | ## Usage 10 | 11 | The following tutorial assumes you have [created a Docker Swarm cluster using Docker Machine](https://docs.docker.com/swarm/install-w-machine). 12 | 13 | ### Start the swarm cluster state manager 14 | 15 | Edit the `docker-compose.yml` file and replace `SWARM_MASTER_IP` with the swarm-master IP address. 16 | 17 | ``` 18 | $ sed -i -e "s/SWARM_MASTER_IP/$(docker-machine ip swarm-master)/g" docker-compose.yml 19 | ``` 20 | 21 | Launch the `swarm-cluster-state-manager` service on the same Docker host as the `swarm-master` service. 22 | 23 | Use the `eval` command to ensure your are pointing to the same Docker host where the `swarm-master` service 24 | is running: 25 | 26 | ``` 27 | $ eval $(docker-machine env swarm-master) 28 | ``` 29 | 30 | Use the `docker-compose up` command to start the `swarm-cluster-state-manager` service: 31 | 32 | ``` 33 | $ docker-compose up -d 34 | ``` 35 | 36 | ### Reusing the Docker machine client certs 37 | 38 | #### OS X 39 | 40 | On OS X you'll need to create a pkcs12 bundle of the PEM encoded client certs in order 41 | to use them with cURL. 42 | 43 | ``` 44 | $ openssl pkcs12 -export \ 45 | -in ~/.docker/machine/certs/cert.pem \ 46 | -inkey ~/.docker/machine/certs/key.pem \ 47 | -out ~/.docker/machine/certs/cert.pfx 48 | ``` 49 | 50 | At the follow prompt set the export password to protect the cert and key: 51 | 52 | ``` 53 | Enter Export Password: 54 | Verifying - Enter Export Password: 55 | ``` 56 | 57 | Later examples assume the word `swarm` was used for the password. 58 | 59 | ### Submit a new cluster state object 60 | 61 | Use the `eval` command to ensure you are pointing to the swarm-master endpoint: 62 | 63 | ``` 64 | $ eval $(docker-machine env swarm-master --swarm) 65 | ``` 66 | 67 | The following command submits a cluster state object named nginx and will ensure 5 68 | containers are started from the `nginx:1.9.6` Docker image. 69 | 70 | ``` 71 | $ curl https://$(docker-machine ip swarm-master):3476/submit \ 72 | -d '{"Name": "nginx", "Image": "nginx:1.9.6", "Count": 5}' \ 73 | --cacert ~/.docker/machine/certs/ca.pem \ 74 | --cert ~/.docker/machine/certs/cert.pfx \ 75 | --pass swarm 76 | ``` 77 | 78 | Review the logs for the `swarm-cluster-state-manager` service: 79 | 80 | ``` 81 | $ docker logs swarm-cluster-state-manager 82 | ``` 83 | 84 | ``` 85 | Starting Swarm cluster state manager... 86 | 2015/11/19 17:55:46 updating nginx cluster state 87 | 2015/11/19 17:55:50 creating 5 nginx containers 88 | 2015/11/19 17:55:50 created nginx container: f7ca99588905796b9a0fd6dcaf057e433170e876fd9500352770bd8d8096cc79 89 | 2015/11/19 17:55:51 created nginx container: 1406e27db94b792906e4c86e76cf9c4ba703b3aefc4ee651ecc10826cd18c612 90 | 2015/11/19 17:55:51 created nginx container: 7307b5221fb30f3373ecda4a9595774fcb8e673782b8ab73a4bc6053efb15749 91 | 2015/11/19 17:55:51 created nginx container: c17f8163e375736a30c16a2b5ca58b70e5330908ae238d0f43e8c99049622514 92 | 2015/11/19 17:55:51 created nginx container: 55b49c75914153603998e9e40687424d8a46890d392abd75b0f6276dc36c6b23 93 | ``` 94 | 95 | ### Automatically replace deleted containers 96 | 97 | Use the `eval` command to ensure you are pointing to the swarm-master endpoint: 98 | 99 | ``` 100 | $ eval $(docker-machine env swarm-master --swarm) 101 | ``` 102 | 103 | All containers created by the `swarm-cluster-state-manager` service include a 104 | `swarm.cluster.state` label with the service name as the value. 105 | 106 | Run the following command to delete all containers defined by the nginx cluster 107 | state entry: 108 | 109 | ``` 110 | $ docker rm -f $(docker ps -f label=swarm.cluster.state=nginx -q) 111 | ``` 112 | 113 | Observe the `swarm-cluster-state-manager` service logs 114 | 115 | ``` 116 | $ docker logs swarm-cluster-state-manager 117 | ``` 118 | 119 | ``` 120 | Starting Swarm cluster state manager... 121 | 2015/11/19 17:55:46 updating nginx cluster state 122 | 2015/11/19 17:55:50 creating 5 nginx containers 123 | 2015/11/19 17:55:50 created nginx container: f7ca99588905796b9a0fd6dcaf057e433170e876fd9500352770bd8d8096cc79 124 | .... 125 | 2015/11/19 18:00:01 creating 5 nginx containers 126 | 2015/11/19 18:00:01 created nginx container: 67532a34aa04f346d1d0cae7947c4f64361da9058ba0b84ec4d4b57f9b443337 127 | 2015/11/19 18:00:01 created nginx container: b3204f60b3d0130d357bcd429a46af54cb640e9068abed4ef281b9eba7969761 128 | 2015/11/19 18:00:02 created nginx container: 88e00433c5c0e72c280f0af8ee9b5e1c73f1609d93d69665a8e175a4f958c67b 129 | 2015/11/19 18:00:02 created nginx container: ad6ac5a04167bd5f81f61f547c91403ec93f3869c8174960d49a732959092b29 130 | 2015/11/19 18:00:02 created nginx container: 7cc9afea05027875fc4100b30fe0fd65ef2bad9a68012c58b65b581ccddf4805 131 | ``` 132 | 133 | ### Update the Cluster state 134 | 135 | Reduce the number of desired running nginx containers to 3: 136 | 137 | ``` 138 | $ curl https://$(docker-machine ip swarm-master):3476/submit \ 139 | -d '{"Name": "nginx", "Image": "nginx:1.9.6", "Count": 3}' \ 140 | --cacert ~/.docker/machine/certs/ca.pem \ 141 | --cert ~/.docker/machine/certs/cert.pfx \ 142 | --pass swarm 143 | ``` 144 | 145 | Observe the swarm-cluster-state-manager service logs 146 | 147 | ``` 148 | $ docker logs swarm-cluster-state-manager 149 | ``` 150 | 151 | ``` 152 | ... 153 | 2015/11/19 18:03:05 updating nginx cluster state 154 | 2015/11/19 18:03:12 removing 2 nginx containers 155 | 2015/11/19 18:03:12 removed nginx container: b3204f60b3d0130d357bcd429a46af54cb640e9068abed4ef281b9eba7969761 156 | 2015/11/19 18:03:12 removed nginx container: 67532a34aa04f346d1d0cae7947c4f64361da9058ba0b84ec4d4b57f9b443337 157 | ``` 158 | 159 | ### Get the current status 160 | 161 | The following command retrieves the cluster status from the Swarm cluster state manager. 162 | 163 | ``` 164 | $ curl https://$(docker-machine ip swarm-master):3476/status \ 165 | --cacert ~/.docker/machine/certs/ca.pem \ 166 | --cert ~/.docker/machine/certs/cert.pfx \ 167 | --pass swarm 168 | ``` 169 | 170 | ``` 171 | { 172 | ... 173 | "CurrentCount": 5, 174 | "DesiredCount": 5, 175 | "Image": "nginx:1.9.6", 176 | "Name": "nginx" 177 | } 178 | ... 179 | ``` 180 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/api.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google, Inc All rights reserved. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // 5 | // You may obtain a copy of the License at 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | package main 14 | 15 | import ( 16 | "encoding/json" 17 | "log" 18 | "net/http" 19 | ) 20 | 21 | func GetClusterState(w http.ResponseWriter, r *http.Request) { 22 | clusterStatus, err := clusterStateManager.ClusterStatus() 23 | if err != nil { 24 | log.Print(err) 25 | w.WriteHeader(500) 26 | } 27 | data, err := json.MarshalIndent(clusterStatus, "", " ") 28 | if err != nil { 29 | log.Print(err) 30 | w.WriteHeader(500) 31 | } 32 | w.Write(data) 33 | } 34 | 35 | func SubmitClusterState(w http.ResponseWriter, r *http.Request) { 36 | decoder := json.NewDecoder(r.Body) 37 | var cs ClusterState 38 | err := decoder.Decode(&cs) 39 | if err != nil { 40 | log.Print(err) 41 | w.WriteHeader(500) 42 | } 43 | if err := clusterStateManager.Submit(&cs); err != nil { 44 | log.Print(err) 45 | w.WriteHeader(500) 46 | } 47 | } 48 | 49 | func RemoveClusterState(w http.ResponseWriter, r *http.Request) { 50 | name := r.FormValue("name") 51 | if name == "" { 52 | log.Println("error removing cluster state: missing name parameter") 53 | w.WriteHeader(http.StatusBadRequest) 54 | return 55 | } 56 | clusterStateManager.Remove(name) 57 | } 58 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/cluster_state_manager.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google, Inc All rights reserved. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // 5 | // You may obtain a copy of the License at 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | package main 14 | 15 | import ( 16 | "crypto/tls" 17 | "encoding/json" 18 | "fmt" 19 | "log" 20 | "sync" 21 | "time" 22 | 23 | "github.com/samalba/dockerclient" 24 | ) 25 | 26 | // ClusterState holds the Swarm cluster state declaration. 27 | type ClusterState struct { 28 | Count int 29 | Image string 30 | Name string 31 | 32 | // filters specifies an JSON encoded value of the filters used when 33 | // processing containers list via the Docker API. 34 | filters string 35 | } 36 | 37 | // ClusterStateStatus holds the Swarm cluster status status. 38 | type ClusterStateStatus struct { 39 | Containers []dockerclient.Container 40 | CurrentCount int 41 | DesiredCount int 42 | Image string 43 | Name string 44 | } 45 | 46 | // A ClusterStateManager defines parameters for running a Swarm cluster state manager server. 47 | type ClusterStateManager struct { 48 | // DockerClient specifies the Docker client by which individual 49 | // Swarm requests are made. 50 | DockerClient *dockerclient.DockerClient 51 | 52 | // Store specifies the in-memory data store for cluster state by name. 53 | Store map[string]*ClusterState 54 | sync.RWMutex 55 | } 56 | 57 | func newClusterStateManager(daemonUrl string, tlsConfig *tls.Config) (*ClusterStateManager, error) { 58 | store := make(map[string]*ClusterState) 59 | client, err := dockerclient.NewDockerClient(daemonUrl, tlsConfig) 60 | if err != nil { 61 | return nil, err 62 | } 63 | return &ClusterStateManager{DockerClient: client, Store: store}, nil 64 | } 65 | 66 | func (csm *ClusterStateManager) Submit(cs *ClusterState) error { 67 | csm.Lock() 68 | defer csm.Unlock() 69 | 70 | log.Printf("updating %s cluster state", cs.Name) 71 | filters, err := json.Marshal(map[string][]string{ 72 | "label": []string{fmt.Sprintf("swarm.cluster.state=%s", cs.Name)}, 73 | }) 74 | if err != nil { 75 | return err 76 | } 77 | cs.filters = string(filters) 78 | csm.Store[cs.Name] = cs 79 | return nil 80 | } 81 | 82 | func (csm *ClusterStateManager) Remove(name string) { 83 | csm.Lock() 84 | defer csm.Unlock() 85 | log.Printf("removing %s cluster state", name) 86 | delete(csm.Store, name) 87 | } 88 | 89 | func (csm *ClusterStateManager) ClusterStatus() ([]*ClusterStateStatus, error) { 90 | csm.RLock() 91 | defer csm.RUnlock() 92 | 93 | cs := make([]*ClusterStateStatus, 0) 94 | for _, desiredState := range csm.Store { 95 | containers, err := csm.DockerClient.ListContainers(false, false, desiredState.filters) 96 | if err != nil { 97 | log.Println(err) 98 | continue 99 | } 100 | 101 | cs = append(cs, &ClusterStateStatus{ 102 | Containers: containers, 103 | CurrentCount: len(containers), 104 | DesiredCount: desiredState.Count, 105 | Image: desiredState.Image, 106 | Name: desiredState.Name, 107 | }) 108 | } 109 | 110 | return cs, nil 111 | } 112 | 113 | func (csm *ClusterStateManager) Sync() { 114 | for { 115 | clusterStatus, err := csm.ClusterStatus() 116 | if err != nil { 117 | log.Print(err) 118 | time.Sleep(5 * time.Second) 119 | continue 120 | } 121 | 122 | for _, status := range clusterStatus { 123 | delta := status.DesiredCount - status.CurrentCount 124 | 125 | if delta == 0 { 126 | continue 127 | } 128 | 129 | if delta > 0 { 130 | log.Printf("creating %d %s containers", delta, status.Name) 131 | 132 | labels := make(map[string]string) 133 | labels["swarm.cluster.state"] = status.Name 134 | 135 | for i := 0; i < delta; i++ { 136 | c := dockerclient.ContainerConfig{ 137 | Image: status.Image, 138 | Labels: labels, 139 | } 140 | id, err := csm.DockerClient.CreateContainer(&c, "") 141 | if err != nil { 142 | log.Print(err) 143 | continue 144 | } 145 | err = csm.DockerClient.StartContainer(id, nil) 146 | if err != nil { 147 | log.Print(err) 148 | continue 149 | } 150 | log.Printf("created %s container: %s", status.Name, id) 151 | } 152 | 153 | continue 154 | } 155 | 156 | log.Printf("removing %d %s containers", -delta, status.Name) 157 | for _, container := range status.Containers[status.DesiredCount:] { 158 | err = csm.DockerClient.RemoveContainer(container.Id, true, true) 159 | if err != nil { 160 | log.Print(err) 161 | continue 162 | } 163 | log.Printf("removed %s container: %s", status.Name, container.Id) 164 | } 165 | } 166 | 167 | time.Sleep(10 * time.Second) 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/docker-compose.yml: -------------------------------------------------------------------------------- 1 | swarm-cluster-state-manager: 2 | container_name: swarm-cluster-state-manager 3 | image: kelseyhightower/swarm-cluster-state-manager 4 | volumes: 5 | - /etc/docker:/etc/docker 6 | command: | 7 | --addr=0.0.0.0:3476 8 | --swarm-manager="tcp://SWARM_MASTER_IP:3376" 9 | --tlscacert="/etc/docker/ca.pem" 10 | --tlscert="/etc/docker/server.pem" 11 | --tlskey="/etc/docker/server-key.pem" 12 | ports: 13 | - "3476:3476" 14 | -------------------------------------------------------------------------------- /swarm-cluster-state-manager/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google, Inc All rights reserved. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // 5 | // You may obtain a copy of the License at 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | package main 14 | 15 | import ( 16 | "crypto/tls" 17 | "crypto/x509" 18 | "flag" 19 | "fmt" 20 | "io/ioutil" 21 | "log" 22 | "net/http" 23 | ) 24 | 25 | var ( 26 | clusterStateManager *ClusterStateManager 27 | 28 | addr string 29 | swarmManager string 30 | tlscacert string 31 | tlscert string 32 | tlskey string 33 | insecureSkipVerify bool 34 | ) 35 | 36 | func init() { 37 | flag.StringVar(&addr, "addr", "127.0.0.1:2476", "HTTP listen address") 38 | flag.StringVar(&swarmManager, "swarm-manager", "tcp://127.0.0.1:2376", "Docker Swarm manager address") 39 | flag.BoolVar(&insecureSkipVerify, "insecure-skip-verify", false, "Skip server certificate verification") 40 | flag.StringVar(&tlscacert, "tlscacert", "", "Trust certs signed only by this CA") 41 | flag.StringVar(&tlscert, "tlscert", "", "Path to TLS certificate file") 42 | flag.StringVar(&tlskey, "tlskey", "", "Path to TLS key file") 43 | } 44 | 45 | func main() { 46 | flag.Parse() 47 | 48 | clientCert, err := tls.LoadX509KeyPair(tlscert, tlskey) 49 | if err != nil { 50 | log.Fatal(err) 51 | } 52 | certPool := x509.NewCertPool() 53 | caCert, err := ioutil.ReadFile(tlscacert) 54 | if err != nil { 55 | log.Fatal(err) 56 | } 57 | certPool.AppendCertsFromPEM(caCert) 58 | 59 | // TLS and TLS client authentication is required. 60 | tlsConfig := &tls.Config{ 61 | ClientAuth: tls.RequireAndVerifyClientCert, 62 | ClientCAs: certPool, 63 | Certificates: []tls.Certificate{clientCert}, 64 | RootCAs: certPool, 65 | InsecureSkipVerify: insecureSkipVerify, 66 | } 67 | 68 | clusterStateManager, err = newClusterStateManager(swarmManager, tlsConfig) 69 | if err != nil { 70 | log.Fatal(err) 71 | } 72 | 73 | // Start the background job to sync desired state with Docker Swarm. 74 | go clusterStateManager.Sync() 75 | 76 | server := &http.Server{ 77 | Addr: addr, 78 | TLSConfig: tlsConfig, 79 | } 80 | http.HandleFunc("/submit", SubmitClusterState) 81 | http.HandleFunc("/status", GetClusterState) 82 | http.HandleFunc("/remove", RemoveClusterState) 83 | 84 | fmt.Println("Starting Swarm cluster state manager...") 85 | log.Fatal(server.ListenAndServeTLS("", "")) 86 | } 87 | --------------------------------------------------------------------------------