├── Dockerfile ├── LICENSE ├── README.md ├── deployment.yaml └── service.yaml /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM quay.io/pires/docker-jre:8u151 2 | 3 | label maintainer Paulo Pires 4 | 5 | ENV VERSION 3.12.3 6 | 7 | RUN \ 8 | apk add --update curl ca-certificates; apk upgrade; \ 9 | curl -Lskj https://github.com/pires/hazelcast-kubernetes-bootstrapper/releases/download/hazelcast-kubernetes-bootstrapper-$VERSION/hazelcast-kubernetes-bootstrapper-$VERSION.jar \ 10 | -o /bootstrapper.jar;\ 11 | apk del curl wget; \ 12 | rm /var/cache/apk/* 13 | 14 | CMD java -jar /bootstrapper.jar 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | hazelcast-kubernetes 2 | ==================== 3 | 4 | Hazelcast clustering for Kubernetes made easy. 5 | It includes a lean Hazelcast container image, based on Alpine Linux, with Kubernetes discovery support. 6 | 7 | [![Docker Repository on Quay](https://quay.io/repository/pires/hazelcast-kubernetes/status "Docker Repository on Quay")](https://quay.io/repository/pires/hazelcast-kubernetes) 8 | 9 | ## Software 10 | 11 | * JRE 8u151 12 | * Hazelcast 3.12.3 13 | 14 | ## Pre-requisites 15 | 16 | * Kubernetes cluster, version 1.4 or newer 17 | 18 | ## Kubernetes cluster 19 | 20 | You can test with a local cluster. Check [this other repository from yours truly](https://github.com/pires/kubernetes-vagrant-coreos-cluster). 21 | 22 | ## Docker image 23 | 24 | The image is already available at [quay.io/pires](https://quay.io/repository/pires/hazelcast-kubernetes) 25 | 26 | ## Cloud Native Deployments of Hazelcast using Kubernetes 27 | 28 | The following document describes the development of a _cloud native_ [Hazelcast](http://hazelcast.org/) deployment on Kubernetes. When we say _cloud native_ we mean an application which understands that it is running within a cluster manager, and uses this cluster management infrastructure to help implement the application. In particular, in this instance, a custom Hazelcast `bootstrapper` is used to enable Hazelcast to dynamically discover Hazelcast nodes that have already joined the cluster. 29 | 30 | Any topology changes are communicated and handled by Hazelcast nodes themselves. 31 | 32 | This document also attempts to describe the core components of Kubernetes, _Pods_, _Services_ and _Replication Controllers_. 33 | 34 | ### Prerequisites 35 | This example assumes that you have a Kubernetes cluster installed and running, and that you have installed the `kubectl` command line tool somewhere in your path. Please see the [getting started](https://github.com/GoogleCloudPlatform/kubernetes/tree/master/docs/getting-started-guides) for installation instructions for your platform. 36 | 37 | ### A note for the impatient 38 | This is a somewhat long tutorial. If you want to jump straight to the "do it now" commands, please see the [tl; dr](#tl-dr) at the end. 39 | 40 | ### Sources 41 | 42 | Source is freely available at: 43 | * Hazelcast Discovery - https://github.com/pires/hazelcast-kubernetes-bootstrapper 44 | * Dockerfile - https://github.com/pires/hazelcast-kubernetes 45 | * Docker Trusted Build - https://registry.hub.docker.com/u/pires/hazelcast-k8s 46 | 47 | ### Simple Single Pod Hazelcast Node 48 | In Kubernetes, the atomic unit of an application is a [_Pod_](http://docs.k8s.io/pods.md). A Pod is one or more containers that _must_ be scheduled onto the same host. All containers in a pod share a network namespace, and may optionally share mounted volumes. 49 | 50 | In this case, we shall not run a single Hazelcast pod, because the discovery mechanism now relies on a service definition. 51 | 52 | 53 | ### Adding a Hazelcast Service 54 | In Kubernetes a _Service_ describes a set of Pods that perform the same task. For example, the set of nodes in a Hazelcast cluster. An important use for a Service is to create a load balancer which distributes traffic across members of the set. But a _Service_ can also be used as a standing query which makes a dynamically changing set of Pods available via the Kubernetes API. This is actually how our discovery mechanism works, by relying on the service to discover other Hazelcast pods. 55 | 56 | Here is the service description: 57 | ```yaml 58 | apiVersion: v1 59 | kind: Service 60 | metadata: 61 | labels: 62 | name: hazelcast 63 | name: hazelcast 64 | spec: 65 | ports: 66 | - port: 5701 67 | selector: 68 | name: hazelcast 69 | ``` 70 | 71 | The important thing to note here is the `selector`. It is a query over labels, that identifies the set of _Pods_ contained by the _Service_. In this case the selector is `name: hazelcast`. If you look at the Replication Controller specification below, you'll see that the pod has the corresponding label, so it will be selected for membership in this Service. 72 | 73 | Create this service as follows: 74 | ```sh 75 | $ kubectl create -f service.yaml 76 | ``` 77 | 78 | ### Adding replicated nodes 79 | The real power of Kubernetes and Hazelcast lies in easily building a replicated, resizable Hazelcast cluster. 80 | 81 | In Kubernetes a _Deployment_ is responsible for replicating sets of identical pods. Like a _Service_ it has a selector query which identifies the members of its set. Unlike a _Service_ it also has a desired number of replicas, and it will create or delete _Pods_ to ensure that the number of _Pods_ matches up with its desired state. 82 | 83 | Deployments will "adopt" existing pods that match their selector query, so let's create a Deployment with a single replica to adopt our existing Hazelcast Pod. 84 | 85 | ```yaml 86 | apiVersion: extensions/v1beta1 87 | kind: Deployment 88 | metadata: 89 | name: hazelcast 90 | labels: 91 | name: hazelcast 92 | spec: 93 | template: 94 | metadata: 95 | labels: 96 | name: hazelcast 97 | spec: 98 | containers: 99 | - name: hazelcast 100 | image: quay.io/pires/hazelcast-kubernetes:3.9.3 101 | imagePullPolicy: Always 102 | env: 103 | - name: "DNS_DOMAIN" 104 | value: "cluster.local" 105 | ports: 106 | - name: hazelcast 107 | containerPort: 5701 108 | ``` 109 | 110 | You may note that we tell Kubernetes that the container exposes the `hazelcast` port. Finally, we tell the cluster manager that we need 1 cpu core. 111 | 112 | The bulk of the replication controller config is actually identical to the Hazelcast pod declaration above, it simply gives the controller a recipe to use when creating new pods. The other parts are the `selector` which contains the controller's selector query, and the `replicas` parameter which specifies the desired number of replicas, in this case 1. 113 | 114 | Last but not least, we set `DNS_DOMAIN` environment variable according to your Kubernetes clusters DNS configuration. 115 | 116 | Create this controller: 117 | 118 | ```sh 119 | $ kubectl create -f deployment.yaml 120 | ``` 121 | 122 | After the controller provisions successfully the pod, you can query the service endpoints: 123 | ```sh 124 | $ kubectl get endpoints hazelcast -o yaml 125 | apiVersion: v1 126 | kind: Endpoints 127 | metadata: 128 | creationTimestamp: 2017-11-23T07:30:15Z 129 | labels: 130 | name: hazelcast 131 | name: hazelcast 132 | namespace: default 133 | resourceVersion: "19163" 134 | selfLink: /api/v1/namespaces/default/endpoints/hazelcast 135 | uid: 0dd49c6a-96c3-11e7-a6db-0800274ecb11 136 | subsets: 137 | - addresses: 138 | - ip: 172.17.0.4 139 | nodeName: minikube 140 | targetRef: 141 | kind: Pod 142 | name: hazelcast-414548760-fb5bh 143 | namespace: default 144 | resourceVersion: "19161" 145 | uid: 0f98fd6a-96c3-11e7-a6db-0800274ecb11 146 | ports: 147 | - port: 5701 148 | protocol: TCP 149 | ``` 150 | 151 | You can see that the _Service_ has found the pod created by the replication controller. 152 | 153 | Now it gets even more interesting. Let's scale our cluster to 2 pods: 154 | ```sh 155 | $ kubectl scale deployment hazelcast --replicas 2 156 | ``` 157 | 158 | Now if you list the pods in your cluster, you should see two Hazelcast pods: 159 | 160 | ```sh 161 | $ kubectl get deployment,pods 162 | NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE 163 | deploy/hazelcast 2 2 2 2 1d 164 | 165 | 166 | NAME READY STATUS RESTARTS AGE 167 | po/hazelcast-414548760-fb5bh 1/1 Running 0 1d 168 | po/hazelcast-414548760-qntg7 1/1 Running 0 10s 169 | ``` 170 | 171 | To prove that this all works, you can use the `log` command to examine the logs of one pod, for example: 172 | 173 | ```sh 174 | $ kubectl logs po/hazelcast-414548760-fb5bh 175 | 2018-02-19 07:14:43.728 INFO 5 --- [ main] com.github.pires.hazelcast.Application : Starting Application on hazelcast-69df7cd6c-ghxgq with PID 5 (/bootstrapper.jar started by root in /) 176 | 2018-02-19 07:14:43.751 INFO 5 --- [ main] com.github.pires.hazelcast.Application : No active profile set, falling back to default profiles: default 177 | 2018-02-19 07:14:43.841 INFO 5 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5f4da5c3: startup date [Mon Feb 19 07:14:43 GMT 2018]; root of context hierarchy 178 | 2018-02-19 07:14:44.636 INFO 5 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 179 | 2018-02-19 07:14:44.647 INFO 5 --- [ main] c.g.p.h.HazelcastDiscoveryController : Asking k8s registry at https://kubernetes.default.svc.cluster.local.. 180 | 2018-02-19 07:14:44.993 INFO 5 --- [ main] c.g.p.h.HazelcastDiscoveryController : Found 2 pods running Hazelcast. 181 | 2018-02-19 07:14:45.060 INFO 5 --- [ main] com.hazelcast.instance.AddressPicker : [LOCAL] [someGroup] [3.9.3] Interfaces is disabled, trying to pick one address from TCP-IP config addresses: [172.17.0.4, 172.17.0.5] 182 | 2018-02-19 07:14:45.060 INFO 5 --- [ main] com.hazelcast.instance.AddressPicker : [LOCAL] [someGroup] [3.9.3] Prefer IPv4 stack is true. 183 | 2018-02-19 07:14:45.065 INFO 5 --- [ main] com.hazelcast.instance.AddressPicker : [LOCAL] [someGroup] [3.9.3] Picked [172.17.0.5]:5701, using socket ServerSocket[addr=/0.0.0.0,localport=5701], bind any local is true 184 | 2018-02-19 07:14:45.105 INFO 5 --- [ main] com.hazelcast.system : [172.17.0.5]:5701 [someGroup] [3.9.3] Hazelcast 3.9.3 (20180216 - 539b124) starting at [172.17.0.5]:5701 185 | 2018-02-19 07:14:45.105 INFO 5 --- [ main] com.hazelcast.system : [172.17.0.5]:5701 [someGroup] [3.9.3] Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. 186 | 2018-02-19 07:14:45.105 INFO 5 --- [ main] com.hazelcast.system : [172.17.0.5]:5701 [someGroup] [3.9.3] Configured Hazelcast Serialization version: 1 187 | 2018-02-19 07:14:45.370 INFO 5 --- [ main] c.h.s.i.o.impl.BackpressureRegulator : [172.17.0.5]:5701 [someGroup] [3.9.3] Backpressure is disabled 188 | 2018-02-19 07:14:46.712 INFO 5 --- [ main] com.hazelcast.instance.Node : [172.17.0.5]:5701 [someGroup] [3.9.3] Creating TcpIpJoiner 189 | 2018-02-19 07:14:47.218 INFO 5 --- [ main] c.h.s.i.o.impl.OperationExecutorImpl : [172.17.0.5]:5701 [someGroup] [3.9.3] Starting 2 partition threads and 3 generic threads (1 dedicated for priority tasks) 190 | 2018-02-19 07:14:47.221 INFO 5 --- [ main] c.h.internal.diagnostics.Diagnostics : [172.17.0.5]:5701 [someGroup] [3.9.3] Diagnostics disabled. To enable add -Dhazelcast.diagnostics.enabled=true to the JVM arguments. 191 | 2018-02-19 07:14:47.227 INFO 5 --- [ main] com.hazelcast.core.LifecycleService : [172.17.0.5]:5701 [someGroup] [3.9.3] [172.17.0.5]:5701 is STARTING 192 | 2018-02-19 07:14:47.274 INFO 5 --- [cached.thread-3] com.hazelcast.nio.tcp.TcpIpConnector : [172.17.0.5]:5701 [someGroup] [3.9.3] Connecting to /172.17.0.4:5701, timeout: 0, bind-any: true 193 | 2018-02-19 07:14:47.283 INFO 5 --- [cached.thread-3] c.h.nio.tcp.TcpIpConnectionManager : [172.17.0.5]:5701 [someGroup] [3.9.3] Established socket connection between /172.17.0.5:34227 and /172.17.0.4:5701 194 | 2018-02-19 07:14:54.177 INFO 5 --- [thread-Acceptor] com.hazelcast.nio.tcp.TcpIpAcceptor : [172.17.0.5]:5701 [someGroup] [3.9.3] Accepting socket connection from /172.17.0.7:59967 195 | 2018-02-19 07:14:54.200 INFO 5 --- [cached.thread-3] c.h.nio.tcp.TcpIpConnectionManager : [172.17.0.5]:5701 [someGroup] [3.9.3] Established socket connection between /172.17.0.5:5701 and /172.17.0.7:59967 196 | 2018-02-19 07:14:54.411 INFO 5 --- [ration.thread-0] com.hazelcast.system : [172.17.0.5]:5701 [someGroup] [3.9.3] Cluster version set to 3.9 197 | 2018-02-19 07:14:54.429 INFO 5 --- [ration.thread-0] c.h.internal.cluster.ClusterService : [172.17.0.5]:5701 [someGroup] [3.9.3] 198 | 199 | Members {size:2, ver:2} [ 200 | Member [172.17.0.4]:5701 - 59045d20-faf3-4a73-b4de-e8036f4b7caa 201 | Member [172.17.0.5]:5701 - e737cd89-cbf1-4358-8d5a-f5b06a464c4a this 202 | ] 203 | 204 | ``` 205 | 206 | Now let's scale our cluster to 4 nodes: 207 | ```sh 208 | $ kubectl scale deployment hazelcast --replicas 4 209 | ``` 210 | 211 | Examine the status again by checking a node's logs and you should see the 4 members connected. Something like: 212 | ``` 213 | (...) 214 | 215 | Members [4] { 216 | Member [172.17.0.4]:5701 - 929e9148-870d-4f43-ba1d-fcc8ff973ab3 this 217 | Member [172.17.0.7]:5701 - 6d05a83b-2960-48b3-8dd2-63f6720115f5 218 | Member [172.17.0.8]:5701 - 50ddeb59-8f06-43c6-91a8-c36fd86f825c 219 | Member [172.17.0.9]:5701 - e79a9a26-971d-4b67-8a46-1a78fee94324 220 | } 221 | ``` 222 | 223 | ### tl; dr; 224 | For those of you who are impatient, here is the summary of the commands we ran in this tutorial. 225 | 226 | ```sh 227 | kubectl create -f service.yaml 228 | kubectl create -f deployment.yaml 229 | kubectl scale deployment hazelcast --replicas 2 230 | kubectl scale deployment hazelcast --replicas 4 231 | ``` 232 | 233 | ### Hazelcast Discovery Source 234 | 235 | ```java 236 | /** 237 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not 238 | * use this file except in compliance with the License. You may obtain a copy of 239 | * the License at 240 | * http://www.apache.org/licenses/LICENSE-2.0 241 | * 242 | * Unless required by applicable law or agreed to in writing, software 243 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 244 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 245 | * License for the specific language governing permissions and limitations under 246 | * the License. 247 | */ 248 | package com.github.pires.hazelcast; 249 | 250 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 251 | import com.fasterxml.jackson.databind.ObjectMapper; 252 | import com.hazelcast.config.*; 253 | import com.hazelcast.core.Hazelcast; 254 | import org.slf4j.Logger; 255 | import org.slf4j.LoggerFactory; 256 | import org.springframework.boot.CommandLineRunner; 257 | import org.springframework.stereotype.Controller; 258 | 259 | import javax.net.ssl.*; 260 | import java.io.IOException; 261 | import java.net.URL; 262 | import java.nio.file.Files; 263 | import java.nio.file.Paths; 264 | import java.security.KeyManagementException; 265 | import java.security.NoSuchAlgorithmException; 266 | import java.security.SecureRandom; 267 | import java.security.cert.X509Certificate; 268 | import java.util.List; 269 | import java.util.UUID; 270 | import java.util.concurrent.CopyOnWriteArrayList; 271 | 272 | /** 273 | * Read from Kubernetes API all Hazelcast service bound pods, get their IP and connect to them. 274 | */ 275 | @Controller 276 | public class HazelcastDiscoveryController implements CommandLineRunner { 277 | 278 | private static final Logger log = LoggerFactory.getLogger(HazelcastDiscoveryController.class); 279 | 280 | @JsonIgnoreProperties(ignoreUnknown = true) 281 | static class Address { 282 | public String ip; 283 | } 284 | 285 | @JsonIgnoreProperties(ignoreUnknown = true) 286 | static class Subset { 287 | public List
addresses; 288 | public List
notReadyAddresses; 289 | } 290 | 291 | @JsonIgnoreProperties(ignoreUnknown = true) 292 | static class Endpoints { 293 | public List subsets; 294 | } 295 | 296 | private static String getServiceAccountToken() throws IOException { 297 | String file = "/var/run/secrets/kubernetes.io/serviceaccount/token"; 298 | return new String(Files.readAllBytes(Paths.get(file))); 299 | } 300 | 301 | private static String getEnvOrDefault(String var, String def) { 302 | final String val = System.getenv(var); 303 | return (val == null || val.isEmpty()) 304 | ? def 305 | : val; 306 | } 307 | 308 | // TODO: Load the CA cert when it is available on all platforms. 309 | private static TrustManager[] trustAll = new TrustManager[]{ 310 | new X509TrustManager() { 311 | public void checkServerTrusted(X509Certificate[] certs, String authType) { 312 | } 313 | 314 | public void checkClientTrusted(X509Certificate[] certs, String authType) { 315 | } 316 | 317 | public X509Certificate[] getAcceptedIssuers() { 318 | return null; 319 | } 320 | } 321 | }; 322 | private static HostnameVerifier trustAllHosts = new HostnameVerifier() { 323 | public boolean verify(String hostname, SSLSession session) { 324 | return true; 325 | } 326 | }; 327 | 328 | @Override 329 | public void run(String... args) { 330 | final String serviceName = getEnvOrDefault("HAZELCAST_SERVICE", "hazelcast"); 331 | final String namespace = getEnvOrDefault("POD_NAMESPACE", "default"); 332 | final String path = String.format("/api/v1/namespaces/%s/endpoints/", namespace); 333 | final String domain = getEnvOrDefault("DNS_DOMAIN", "cluster.local"); 334 | final String host = getEnvOrDefault("KUBERNETES_MASTER", "https://kubernetes.default.svc.".concat(domain)); 335 | log.info("Asking k8s registry at {}..", host); 336 | 337 | final List hazelcastEndpoints = new CopyOnWriteArrayList<>(); 338 | try { 339 | final String token = getServiceAccountToken(); 340 | 341 | final SSLContext ctx = SSLContext.getInstance("SSL"); 342 | ctx.init(null, trustAll, new SecureRandom()); 343 | 344 | final URL url = new URL(host + path + serviceName); 345 | final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 346 | // TODO: remove this when and replace with CA cert loading, when the CA is propogated 347 | // to all nodes on all platforms. 348 | conn.setSSLSocketFactory(ctx.getSocketFactory()); 349 | conn.setHostnameVerifier(trustAllHosts); 350 | conn.addRequestProperty("Authorization", "Bearer " + token); 351 | 352 | final ObjectMapper mapper = new ObjectMapper(); 353 | final Endpoints endpoints = mapper.readValue(conn.getInputStream(), Endpoints.class); 354 | if (endpoints != null) { 355 | if (endpoints.subsets != null && !endpoints.subsets.isEmpty()) { 356 | endpoints.subsets.forEach(subset -> { 357 | if (subset.addresses != null && !subset.addresses.isEmpty()) { 358 | subset.addresses.forEach( 359 | addr -> hazelcastEndpoints.add(addr.ip)); 360 | } else if (subset.notReadyAddresses != null && !subset.notReadyAddresses.isEmpty()) { 361 | // in case of a full cluster restart 362 | // no address might be ready, in order to allow the cluster 363 | // to start initially, we will use the not ready addresses 364 | // as fallback 365 | subset.notReadyAddresses.forEach( 366 | addr -> hazelcastEndpoints.add(addr.ip)); 367 | } else { 368 | log.warn("Could not find any hazelcast nodes."); 369 | } 370 | }); 371 | } 372 | } 373 | } catch (IOException | NoSuchAlgorithmException | KeyManagementException ex) { 374 | log.warn("Request to Kubernetes API failed", ex); 375 | } 376 | 377 | log.info("Found {} pods running Hazelcast.", hazelcastEndpoints.size()); 378 | 379 | runHazelcast(hazelcastEndpoints); 380 | } 381 | 382 | private void runHazelcast(final List nodes) { 383 | // configure Hazelcast instance 384 | final Config cfg = new Config(); 385 | cfg.setInstanceName(UUID.randomUUID().toString()); 386 | // group configuration 387 | final String HC_GROUP_NAME = getEnvOrDefault("HC_GROUP_NAME", "someGroup"); 388 | final String HC_GROUP_PASSWORD = getEnvOrDefault("HC_GROUP_PASSWORD", 389 | "someSecret"); 390 | final int HC_PORT = Integer.parseInt(getEnvOrDefault("HC_PORT", "5701")); 391 | final String HC_REST_ENABLED = getEnvOrDefault("HC_REST_ENABLED", "false"); 392 | cfg.setGroupConfig(new GroupConfig(HC_GROUP_NAME, HC_GROUP_PASSWORD)); 393 | cfg.setProperty("hazelcast.rest.enabled", HC_REST_ENABLED); 394 | // network configuration initialization 395 | final NetworkConfig netCfg = new NetworkConfig(); 396 | netCfg.setPortAutoIncrement(false); 397 | netCfg.setPort(HC_PORT); 398 | // multicast 399 | final MulticastConfig mcCfg = new MulticastConfig(); 400 | mcCfg.setEnabled(false); 401 | // tcp 402 | final TcpIpConfig tcpCfg = new TcpIpConfig(); 403 | nodes.forEach(tcpCfg::addMember); 404 | tcpCfg.setEnabled(true); 405 | // network join configuration 406 | final JoinConfig joinCfg = new JoinConfig(); 407 | joinCfg.setMulticastConfig(mcCfg); 408 | joinCfg.setTcpIpConfig(tcpCfg); 409 | netCfg.setJoin(joinCfg); 410 | // ssl 411 | netCfg.setSSLConfig(new SSLConfig().setEnabled(false)); 412 | // set it all 413 | cfg.setNetworkConfig(netCfg); 414 | // run 415 | Hazelcast.newHazelcastInstance(cfg); 416 | } 417 | 418 | } 419 | ``` 420 | -------------------------------------------------------------------------------- /deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: hazelcast 5 | labels: 6 | name: hazelcast 7 | spec: 8 | template: 9 | metadata: 10 | labels: 11 | name: hazelcast 12 | spec: 13 | containers: 14 | - name: hazelcast 15 | image: quay.io/pires/hazelcast-kubernetes:3.12.3 16 | imagePullPolicy: Always 17 | env: 18 | - name: "DNS_DOMAIN" 19 | value: "cluster.local" 20 | ports: 21 | - name: hazelcast 22 | containerPort: 5701 23 | -------------------------------------------------------------------------------- /service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | labels: 5 | name: hazelcast 6 | name: hazelcast 7 | spec: 8 | ports: 9 | - port: 5701 10 | selector: 11 | name: hazelcast 12 | --------------------------------------------------------------------------------