[
  {
    "path": ".gitignore",
    "content": "*.pem\n*.csr\n*.srl\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# kubernetes-nats-cluster\nNATS cluster on top of Kubernetes made easy.\n\n**THIS PROJECT HAS BEEN ARCHIVED. SEE https://github.com/nats-io/nats-operator**\n\n**NOTE:** This repository provides a configurable way to deploy secure, available\nand scalable NATS clusters. However, [a _smarter_ solution](https://github.com/pires/nats-operator)\nin on the way (see [#5](https://github.com/pires/kubernetes-nats-cluster/issues/5)).\n\n## Pre-requisites\n\n* Kubernetes cluster v1.8+ - tested with v1.9.0 on top of [Vagrant + CoreOS](https://github.com/pires/kubernetes-vagrant-coreos-cluster)\n* At least 3 nodes available (see [Pod anti-affinity](#pod-anti-affinity))\n* `kubectl` configured to access your cluster master API Server\n* `openssl` for TLS certificate generation\n\n## Deploy\n\nWe will be deploying a cluster of 3 NATS instances, with the following set-up:\n- TLS on for clients, but not clustering because peer-auth requires real SANS DNS in certificate\n- NATS client credentials: `nats_client_user:nats_client_pwd`\n- NATS route/cluster credentials: `nats_route_user:nats_route_pwd`\n- Logging: `debug:false`, `trace:true`, `logtime:true`\n\nFirst, make sure to change `nats.conf` according to your needs.\nThen create a Kubernetes configmap to store it:\n```bash\nkubectl create configmap nats-config --from-file nats.conf\n```\n\nNext, we need to generate valid TLS artifacts:\n```bash\nopenssl genrsa -out ca-key.pem 2048\nopenssl req -x509 -new -nodes -key ca-key.pem -days 10000 -out ca.pem -subj \"/CN=kube-ca\"\nopenssl genrsa -out nats-key.pem 2048\nopenssl req -new -key nats-key.pem -out nats.csr -subj \"/CN=kube-nats\" -config ssl.cnf\nopenssl x509 -req -in nats.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out nats.pem -days 3650 -extensions v3_req -extfile ssl.cnf\n```\n\nThen, it's time to create a couple Kubernetes secrets to store the TLS artifacts:\n- `tls-nats-server` for the NATS server TLS setup\n- `tls-nats-client` for NATS client apps setup - one will need it to validate the self-signed certificate\nused to secure NATS server\n```bash\nkubectl create secret generic tls-nats-server --from-file nats.pem --from-file nats-key.pem --from-file ca.pem\nkubectl create secret generic tls-nats-client --from-file ca.pem\n```\n\n**ATTENTION:** Both using self-signed certificates and using the same certificates for securing\nclient and cluster connections is a significant security compromise. But for the sake of showing\nhow it can be done, I'm fine with doing just that.\nIn an ideal scenario, there should be:\n- One centralized PKI/CA\n- One certificate for securing NATS route/cluster connections\n- One certificate for securing NATS client connections\n- TLS route/cluster authentication should be enforced, so one TLS certificate per route/cluster peer\n- TLS client authentication should be enforced, so one TLS certificate per client\n\nAnd finally, we deploy NATS:\n```bash\nkubectl create -f nats.yml\n```\n\nLogs should be enough to make sure everything is working as expected:\n```\n$ kubectl logs -f nats-0\n[1] 2017/12/17 12:38:37.801139 [INF] Starting nats-server version 1.0.4\n[1] 2017/12/17 12:38:37.801449 [INF] Starting http monitor on 0.0.0.0:8222\n[1] 2017/12/17 12:38:37.801580 [INF] Listening for client connections on 0.0.0.0:4242\n[1] 2017/12/17 12:38:37.801772 [INF] TLS required for client connections\n[1] 2017/12/17 12:38:37.801778 [INF] Server is ready\n[1] 2017/12/17 12:38:37.802078 [INF] Listening for route connections on 0.0.0.0:6222\n[1] 2017/12/17 12:38:38.874497 [TRC] 10.244.1.3:33494 - rid:1 - ->> [CONNECT {\"verbose\":false,\"pedantic\":false,\"user\":\"nats_route_user\",\"pass\":\"nats_route_pwd\",\"tls_required\":true,\"name\":\"KGMPnL89We3gFLEjmp8S5J\"}]\n[1] 2017/12/17 12:38:38.956806 [TRC] 10.244.74.2:46018 - rid:3 - ->> [CONNECT {\"verbose\":false,\"pedantic\":false,\"user\":\"nats_route_user\",\"pass\":\"nats_route_pwd\",\"tls_required\":true,\"name\":\"Skc5mx9enWrGPIQhyE7uzR\"}]\n[1] 2017/12/17 12:38:39.951160 [TRC] 10.244.1.4:46242 - rid:4 - ->> [CONNECT {\"verbose\":false,\"pedantic\":false,\"user\":\"nats_route_user\",\"pass\":\"nats_route_pwd\",\"tls_required\":true,\"name\":\"0kaCfF3BU8g92snOe34251\"}]\n[1] 2017/12/17 12:40:38.956203 [TRC] 10.244.74.2:46018 - rid:3 - <<- [PING]\n[1] 2017/12/17 12:40:38.958279 [TRC] 10.244.74.2:46018 - rid:3 - ->> [PING]\n[1] 2017/12/17 12:40:38.958300 [TRC] 10.244.74.2:46018 - rid:3 - <<- [PONG]\n[1] 2017/12/17 12:40:38.961791 [TRC] 10.244.74.2:46018 - rid:3 - ->> [PONG]\n[1] 2017/12/17 12:40:39.951421 [TRC] 10.244.1.4:46242 - rid:4 - <<- [PING]\n[1] 2017/12/17 12:40:39.952578 [TRC] 10.244.1.4:46242 - rid:4 - ->> [PONG]\n[1] 2017/12/17 12:40:39.952594 [TRC] 10.244.1.4:46242 - rid:4 - ->> [PING]\n[1] 2017/12/17 12:40:39.952598 [TRC] 10.244.1.4:46242 - rid:4 - <<- [PONG]\n```\n\n## Scale\n\n**WARNING:** Due to the [Pod anti-affinity](#pod-anti-affinity) rule, for scaling up to _n_ NATS\ninstances, one needs _n_ available Kubernetes nodes.\n\n```\nkubectl scale statefulsets nats --replicas 5\n```\n\nDid it work?\n\n```\nNAME             TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)                      AGE\nsvc/kubernetes   ClusterIP   10.100.0.1   <none>        443/TCP                      1h\nsvc/nats         ClusterIP   None         <none>        4222/TCP,6222/TCP,8222/TCP   4m\n\nNAME        READY     STATUS    RESTARTS   AGE\npo/nats-0   1/1       Running   0          4m\npo/nats-1   1/1       Running   0          4m\npo/nats-2   1/1       Running   0          4m\npo/nats-3   1/1       Running   0          7s\npo/nats-4   1/1       Running   0          6s\n```\n\n## Access the service\n\n*Don't forget* that services in Kubernetes are only acessible from containers in the cluster.\n\nIn this case, we're using a [`headless service`](http://kubernetes.io/v1.1/docs/user-guide/services.html#headless-services).\n\nJust point your client apps to:\n```\nnats:4222\n```\n\n<a id=\"pod-anti-affinity\">\n\n## Pod anti-affinity\n\n\nOne of the main advantages of running NATS on top of Kubernetes is how resilient the cluster becomes,\nparticularly during node restarts. However if all NATS pods are scheduled onto the same node(s), this\nadvantage decreases significantly and may even result in service downtime.\n\nIt is then **highly recommended** that one adopts [pod anti-affinity](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#inter-pod-affinity-and-anti-affinity-beta-feature)\nin order to increase availability. This is enabled by default (see `nats.yml`).\n"
  },
  {
    "path": "nats.conf",
    "content": "listen: 0.0.0.0:4222\nhttp: 0.0.0.0:8222\n\ntls {\n  cert_file:  \"/etc/nats/tls/nats.pem\"\n  key_file:   \"/etc/nats/tls/nats-key.pem\"\n  timeout:    2\n}\n\n# Authorization for client connections\nauthorization {\n    user:     nats_client_user\n    # ./util/mkpasswd -p T0pS3cr3t\n    password: nats_client_pwd\n    timeout:  1\n}\n\n# Cluster definition\ncluster {\n    listen: 0.0.0.0:6222\n\n    # Disabled this because peer-auth requires real SANS DNS in certificate\n    #tls {\n    #    cert_file:  \"/etc/nats/tls/nats.pem\"\n    #    key_file:   \"/etc/nats/tls/nats-key.pem\"\n    #    ca_file:    \"/etc/nats/tls/ca.pem\"\n    #    timeout:    5\n    #}\n\n    # Authorization for route connections\n    authorization {\n        user: nats_route_user\n        password: nats_route_pwd\n        timeout: 0.5\n    }\n\n    # Routes are actively solicited and connected to from this server.\n    # Other servers can connect to us if they supply the correct credentials\n    # in their routes definitions from above.\n    routes = [\n        nats://nats_route_user:nats_route_pwd@nats:6222\n    ]\n}\n\n# logging options\ndebug:   false\ntrace:   true\nlogtime: true\n\n# Some system overides\n\n# max_connections\nmax_connections: 100\n\n# maximum protocol control line\nmax_control_line: 512\n\n# maximum payload\nmax_payload: 65536\n\n# Duration the server can block on a socket write to a client.  Exceeding the\n# deadline will designate a client as a slow consumer.\nwrite_deadline: \"2s\""
  },
  {
    "path": "nats.yml",
    "content": "apiVersion: v1\nkind: Service\nmetadata:\n  name: nats\n  labels:\n    component: nats\nspec:\n  selector:\n    component: nats\n  clusterIP: None\n  ports:\n  - name: client\n    port: 4222\n  - name: cluster\n    port: 6222\n  - name: monitor\n    port: 8222\n---\napiVersion: apps/v1beta1\nkind: StatefulSet\nmetadata:\n  name: nats\n  labels:\n    component: nats\nspec:\n  serviceName: nats\n  replicas: 3\n  template:\n    metadata:\n      labels:\n        component: nats\n    spec:\n      affinity:\n        podAntiAffinity:\n          requiredDuringSchedulingIgnoredDuringExecution:\n          - labelSelector:\n              matchExpressions:\n                - key: component\n                  operator: In\n                  values:\n                    - nats\n            topologyKey: kubernetes.io/hostname\n      containers:\n      - name: nats\n        image: nats:1.0.4\n        args: [ \"--config\", \"/etc/nats/config/nats.conf\"]\n        volumeMounts:\n          - name: tls-volume\n            mountPath: /etc/nats/tls\n          - name: config-volume\n            mountPath: /etc/nats/config\n        ports:\n        - containerPort: 4222\n          name: client\n        - containerPort: 6222\n          name: cluster\n        - containerPort: 8222\n          name: monitor\n        livenessProbe:\n          httpGet:\n            path: /\n            port: 8222\n          initialDelaySeconds: 10\n          timeoutSeconds: 5\n      volumes:\n      - name: tls-volume\n        secret:\n          secretName: tls-nats-server\n      - name: config-volume\n        configMap:\n          name: nats-config\n"
  },
  {
    "path": "route_checker/main.go",
    "content": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"flag\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n)\n\nvar (\n\tlookupName = flag.String(\"lookup\", \"nats\", \"Lookup name\")\n\tserver     = flag.String(\"server\", \"http://localhost:8222\", \"NATS URL to query\")\n)\n\ntype routez struct {\n\tRoutesCount int `json:\"num_routes\"`\n}\n\nfunc countInstancesInCluster(lookupName string) (int, error) {\n\t_, srvRecords, err := net.LookupSRV(\"\", \"\", lookupName)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn len(srvRecords), nil\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t// if we're the only instance in the cluster, we're good to go\n\t// otherwise, we need to check if there are any routes established\n\t// and if not, exit with error.\n\tinstances, err := countInstancesInCluster(*lookupName)\n\tif err != nil {\n\t\tlog.Fatalf(\"There was an error while verifiying if this is the first instance in the cluster: %s\\n\", err.Error())\n\t} else {\n\t\tlog.Printf(\"There are %d instances in the cluster.\", instances)\n\t}\n\n\tif instances > 1 {\n\t\t// query NATS monitoring endpoint\n\t\turl := *server + \"/routez\"\n\t\tlog.Printf(\"Querying server %s..\\n\", url)\n\t\tres, err := http.Get(url)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"There was an error while querying %s: %s\\n\", url, err.Error())\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"There was an error while reading response: %s\\n\", err.Error())\n\t\t}\n\n\t\tvar data routez\n\t\tif err := json.Unmarshal(body, &data); err != nil {\n\t\t\tlog.Fatalf(\"There was an error while decoding response: %s\\n\", err.Error())\n\t\t}\n\n\t\t// if enough routes aren't established, exit with error\n\t\tif data.RoutesCount < instances-1 {\n\t\t\tlog.Fatalf(\"There aren't enough routes established. Only %d out of %d.\", data.RoutesCount, instances-1)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "ssl.cnf",
    "content": "[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @alt_names\n[alt_names]\nDNS.1 = nats\n\n"
  }
]