├── .gitignore ├── Dockerfile ├── package.json ├── haproxy.cfg.template ├── README.md ├── LICENSE └── start.js /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | node_modules 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mhart/alpine-node:5 2 | 3 | RUN apk add --update haproxy 4 | 5 | COPY package.json /src/ 6 | 7 | RUN cd /src; npm install 8 | 9 | COPY start.js haproxy.cfg.template /src/ 10 | 11 | CMD ["node", "/src/start.js"] -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "haproxy-srv", 3 | "version": "0.0.2", 4 | "description": "HAProxy autoconfiguration template based on DNS SRV records", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "elastic.io GmbH", 10 | "license": "Apache-2.0", 11 | "dependencies": { 12 | "debug": "^2.2.0", 13 | "diff": "^2.2.1", 14 | "handlebars": "^4.0.5", 15 | "haproxy": "^0.2.0", 16 | "ip": "^1.1.0", 17 | "rsvp": "^3.1.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /haproxy.cfg.template: -------------------------------------------------------------------------------- 1 | global 2 | user root 3 | group root 4 | 5 | # Default SSL material locations 6 | ca-base /etc/ssl/certs 7 | crt-base /etc/ssl/private 8 | 9 | # Default ciphers to use on SSL-enabled listening sockets. 10 | # For more information, see ciphers(1SSL). 11 | ssl-default-bind-ciphers kEECDH+aRSA+AES:kRSA+AES:+AES256:RC4-SHA:!kEDH:!LOW:!EXP:!MD5:!aNULL:!eNULL 12 | 13 | # Stats required for this module to work 14 | # https://github.com/observing/haproxy#haproxycfg 15 | stats socket /tmp/haproxy.sock level admin 16 | 17 | defaults 18 | mode http 19 | timeout connect 5000 20 | timeout client 50000 21 | timeout server 50000 22 | 23 | 24 | frontend stats 25 | bind 0.0.0.0:8081 26 | mode http 27 | stats enable 28 | stats hide-version 29 | stats uri / 30 | 31 | {{#dns-srv "_frontend._tcp.marathon.mesos"}} 32 | frontend sample 33 | bind 0.0.0.0:8080 34 | mode http 35 | balance roundrobin 36 | option http-server-close 37 | option forwardfor 38 | {{#each this}} 39 | server frontend-{{@index}} {{ip}}:{{port}} check weight {{weight}} 40 | {{/each}} 41 | {{/dns-srv}} 42 | 43 | {{#dns-a "cluster.example.com"}} 44 | frontend sample2 45 | bind 0.0.0.0:8081 46 | mode http 47 | backend sample2 48 | balance leastconn 49 | {{#each this}} 50 | server {{name}} {{ip}}:80 check 51 | {{/each}} 52 | {{/dns-a}} 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HAProxy SRV 2 | 3 | HAProxy-SRV is a templating solution that can flexibly reconfigure HAProxy based on the regular polling of the 4 | service data from DNS (e.g. SkyDNS or Mesos-DNS) using SRV records. 5 | 6 | HAProxy-SRV also works with Round-Robin DNS A records, like Docker Swarm Mode. 7 | 8 | It has a very simple logic - HA Proxy is configured based on the Handlebars template that is re-evaluated every time changes in DNS are detecting. Script is polling DNS and trigger a HA Proxy configuration refresh after changes. 9 | 10 | Made by [elastic.io](http://www.elastic.io) in Germany. 11 | 12 | # Quick start 13 | 14 | Simplest way to start it with Docker: 15 | 16 | ``` 17 | docker run -d -p 8080:8080 -p 80:80 -v $PWD/haproxy.cfg.template:/src/haproxy.cfg.template elasticio/haproxy-srv:latest 18 | ``` 19 | 20 | if you want to see more DEBUG output then just add ``-e "DEBUG=*"`` 21 | 22 | # How it works 23 | 24 | Script works very simple - after docker container started script parse and validates template, create a HAProxy configuration file in ``/src/haproxy.cfg`` and start HAProxy as a daemon. Every second (by default, can be configured via ``REFRESH_TIMEOUT`` env variable, default 1000) scirpt will execute a DNS lookup and re-evaluate the template, if result of evaluation is different from original configuration, original config will be overwritten and HAProxy reload will be triggered. HAProxy reload will not affect existing connections. 25 | 26 | # How to use it 27 | 28 | Recommended way to deploy is is to use [a Docker image](https://hub.docker.com/r/elasticio/haproxy-srv/). You would need to place your configuration file template, the simples way to do it is to build an image based on ``haproxy-srv`` image. 29 | 30 | Create a new ``Dockerfile`` content like this: 31 | 32 | ``` 33 | FROM elasticio/haproxy-srv:latest 34 | 35 | COPY haproxy.cfg.template /src/ 36 | 37 | EXPOSE 80 8880 38 | ``` 39 | 40 | Note the ``EXPOSE`` part here, don't forget to specify exposed ports if your HAProxy configuration listens on any port different from ``80``. 41 | 42 | As a next step create a template file, it should be placed under ``/src/haproxy.cfg.template`` in resulting Docker container and should have a [Handlebars](http://handlebarsjs.com/) syntax with one little extension (see below). Here is the sample: 43 | 44 | ```hbs 45 | global 46 | user root 47 | group root 48 | 49 | # Stats required for this module to work 50 | # https://github.com/observing/haproxy#haproxycfg 51 | stats socket /tmp/haproxy.sock level admin 52 | 53 | defaults 54 | mode http 55 | timeout connect 5000 56 | timeout client 50000 57 | timeout server 50000 58 | 59 | {{#dns-srv "_frontend._tcp.marathon.mesos"}} 60 | frontend sample 61 | bind 0.0.0.0:80 62 | balance roundrobin 63 | option http-server-close 64 | option forwardfor 65 | {{#each this}} 66 | server frontend-{{@index}} {{ip}}:{{port}} check weight {{weight}} 67 | {{/each}} 68 | {{/dns-srv}} 69 | 70 | # Standard DNS Round-Robin 71 | {{#dns-a "cluster.example.com"}} 72 | frontend sample2 73 | bind 0.0.0.0:8080 74 | {{#each this}} 75 | server {{name}} {{ip}}:80 check 76 | {{/each}} 77 | {{/dns-a}} 78 | 79 | # Docker Swarm Mode example 80 | {{#dns-a "tasks.myservice"}} 81 | frontend sample3 82 | bind 0.0.0.0:8081 83 | {{#each this}} 84 | server {{name}} {{ip}}:80 check 85 | {{/each}} 86 | {{/dns-a}} 87 | ``` 88 | 89 | It could be any valid HAProxy configuration with one mandatory addition: 90 | 91 | ``` 92 | stats socket /tmp/haproxy.sock level admin 93 | ``` 94 | 95 | to trigger HAProxy restart the script inside the file will communicate with HAProxy daemon via socket ```/tmp/haproxy.sock```. 96 | 97 | # Template 98 | 99 | Configuration template is a normal [Handlebars](http://handlebarsjs.com/) so that you could use any of the feature of this template language. There is however one additional helper ``dns-srv`` implemented. This helper takes one string parameter and will execute a [DNS SRV lookup](https://nodejs.org/api/dns.html#dns_dns_resolvesrv_hostname_callback) to fetch an SRV record(s). After SRV Record lookup, for each SRV record a [DNS resolution](https://nodejs.org/api/dns.html#dns_dns_resolve_hostname_rrtype_callback) to find the IP will be made. 100 | 101 | This template will give you an idea how to use it: 102 | 103 | ```hbs 104 | # Your usual configuration is here 105 | {{#dns-srv "_frontend._tcp.marathon.mesos"}} 106 | # This block will only be rendered when _frontend._tcp.marathon.mesos was found in DNS 107 | {{#each this}} 108 | # This piece will be rendered for each SRV entry from DNS 109 | SRV Name is {{name}} 110 | SRV Weight is {{weight}} 111 | SRV Port is {{port}} 112 | IP for SRV Name is {{ip}} 113 | {{/each}} 114 | {{/dns-srv}} 115 | # rest of your configuration 116 | ``` 117 | 118 | Typical use-case for Msos-DNS you can see above. 119 | 120 | # Docker Swarm Mode Guide 121 | 122 | First, create a network, and web service: 123 | 124 | ``` 125 | $ docker network create -d overlay --subnet 10.1.1.0/24 my_net 126 | $ docker service create --replicas 2 --name my_web --network my_net nginx 127 | ``` 128 | 129 | By default, services are created as `--endpoint-mode vip`. If you use VIP mode, 130 | then the Round-Robin DNS name is `tasks.my_web`. If you use `--endpoint-mode dnsrr` 131 | then the `my_web` DNS name will work in the HAProxy `dns-a` template. 132 | 133 | Follow the **How to use it** section above on creating a new proxy image using 134 | a custom haproxy.cfg.template. For the `dns-a` section use: 135 | 136 | ``` 137 | {{#dns-a "tasks.my_web"}} 138 | # other configs 139 | backend my_web 140 | {{#each this}} 141 | server {{name}} {{ip}}:80 check 142 | {{/each}} 143 | {{/dns-a}} 144 | ``` 145 | 146 | ``` 147 | $ mkdir my_proxy ; cd my_proxy 148 | # (make a new Dockerfile) 149 | $ docker build -t my_proxy_image . 150 | ``` 151 | 152 | Fire up a new proxy, publishing port 80 to something unique on each docker host node 153 | 154 | ``` 155 | $ docker service create --name my_proxy --network my_net -p 8081:80 my_proxy_image 156 | ``` 157 | 158 | Optionally, use some other method for sharing & binding the haproxy.cfg.template file 159 | into the `elasticio/haproxy-srv` image. 160 | 161 | # Debugging 162 | 163 | Just set the ``DEBUG`` environment variable into ``*`` to see detailed logging. 164 | 165 | # TODOs 166 | 167 | PRs are welcome for 168 | * Bug fixes 169 | * Unit tests 170 | * Gulp or Grunt-based builds 171 | * CircleCI config for continous integration 172 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /start.js: -------------------------------------------------------------------------------- 1 | // Enable info by default 2 | process.env.DEBUG = (process.env.DEBUG ? process.env.DEBUG + ',' : '') + 'configurator:info'; 3 | var dns = require('dns'); 4 | var debug = require('debug')('configurator:debug'); 5 | var info = require('debug')('configurator:info'); 6 | var child_process = require('child_process'); 7 | var HAProxy = require('haproxy'); 8 | var handlebars = require('handlebars'); 9 | var fs = require("fs"); 10 | var jsdiff = require('diff'); 11 | var RSVP = require('rsvp'); 12 | var ip = require('ip'); 13 | 14 | const CONFIG_REFRESH_TIMEOUT_MILLS = process.env.REFRESH_TIMEOUT || "1000"; 15 | 16 | var configurationFile = "/etc/haproxy.cfg"; 17 | 18 | var haproxy = new HAProxy({ 19 | config: configurationFile, 20 | socket: "/tmp/haproxy.sock" 21 | }); 22 | 23 | /** 24 | * Cache that is used for discovery of the required properties 25 | * and storage of the data used by handlebar helper 26 | * 27 | * @type {Map} 28 | */ 29 | var dnsCache = { 30 | srv: new Map(), 31 | a: new Map() 32 | }; 33 | 34 | /** 35 | * Here we will store result of handlebars.compile() 36 | */ 37 | var template; 38 | 39 | var haproxyRunning = false; 40 | 41 | /** 42 | * Promise that will verify configuration 43 | * 44 | * @type {Promise} 45 | */ 46 | var verifyConfiguration = () => new Promise(function (resolve, reject) { 47 | info('Verifying configuration'); 48 | if (!fs.existsSync(configurationFile)) return reject('Configuration file can not be found file=' + configurationFile); 49 | haproxy.verify(function (err, working) { 50 | if (err) { 51 | return reject(err); 52 | } 53 | if (!working) { 54 | info('Configuration have warnings'); 55 | } else { 56 | info('Configuration verified successfully'); 57 | } 58 | resolve(); 59 | }); 60 | }); 61 | 62 | /** 63 | * Promise that will start the HAProxy child process 64 | * @type {Promise} 65 | */ 66 | var startHAProxy = () => new Promise(function (resolve, reject) { 67 | info('Starting the HAPRoxy daemon process'); 68 | haproxy.start(function started(err) { 69 | if (err) { 70 | console.error('Failed to start the HAProxy process'); 71 | return reject(err) 72 | } 73 | haproxyRunning = true; 74 | resolve(); 75 | }); 76 | }); 77 | 78 | /** 79 | * This function returns a promise that transforms this 80 | * 81 | * {"name":"api-42873-s1.marathon.mesos","port":8090,"priority":0,"weight":0} 82 | * 83 | * into 84 | * 85 | * {"name":"api-42873-s1.marathon.mesos","ip":"10.0.0.2","port":8090,"priority":0,"weight":0} 86 | * 87 | * @type {Promise} 88 | */ 89 | var resolveIP = entry => new Promise((resolve, reject) => { 90 | var name = entry.name; 91 | if (ip.isV4Format(name) || ip.isV6Format(name)) { 92 | entry.ip = name; 93 | debug('Added IP information to the entry entry=%j', entry); 94 | resolve(entry) 95 | } else { 96 | dns.resolve(name, function (err, address) { 97 | if (err) { 98 | debug('DNS Lookup failed entry=%s error=%j', name, err); 99 | return reject(err); 100 | } 101 | debug('DNS Lookup succeeded entry=%s address=%s', name, address); 102 | entry.ip = address[0]; 103 | debug('Added IP information to the entry entry=%j', entry); 104 | resolve(entry); 105 | }); 106 | } 107 | }); 108 | 109 | /** 110 | * This function returns a promise that transforms 111 | * {"ip": "192.168.1.1" } 112 | * into 113 | * {"ip": "192.168.1.1", "name": "server1.example.com"} 114 | * 115 | * @type {Promise} 116 | */ 117 | var reverseLookup = entry => new Promise((resolve, reject) => { 118 | if ( ! ( ip.isV4Format(entry.ip) && ip.isV6Format(entry.ip) ) ) 119 | return reject("Invalid entry address format"); 120 | 121 | dns.reverse(entry.ip, function (err, hostnames) { 122 | if (err) { 123 | debug("DNS Reverse lookup failed for %j: %j", entry, err); 124 | return reject(err); 125 | } 126 | debug("DNS Reverse lookup succeeded: %j => %j", entry, hostnames); 127 | // pick the first one 128 | entry.name = hostnames[0]; 129 | resolve( entry ); 130 | }); 131 | }); 132 | /** 133 | * This function returns a promise that resolves the string 134 | * as an array of IP addresess for multiple A records 135 | * 136 | * @param dnsName 137 | * @returns {Promise} 138 | */ 139 | var resolveA = dnsName => new Promise((resolve, reject) => { 140 | debug("resolveA: doing DNS lookup for %s", dnsName); 141 | dns.resolve(dnsName, function (err, addresses) { 142 | if (err) { 143 | debug('DNS Lookup failed entry=%s error=%j', dnsName, err); 144 | return reject(err); 145 | } 146 | if ( addresses.length == 0 ) 147 | return resolve([]); 148 | 149 | // sort IP addresses 150 | addresses.sort(); 151 | 152 | debug('DNS Lookup succeeded entry=%s address=%j', dnsName, addresses); 153 | /* map the address array into something that looks similar 154 | * to the resolveSRV return 155 | */ 156 | addresses = addresses.map(function(a) { return {'ip': a } }); 157 | 158 | // add a 'name' key using reverseLookup 159 | Promise.all(addresses.map(reverseLookup)) 160 | .then(resolved => resolve(resolved)) 161 | .catch(error => reject(error)); 162 | }); 163 | }); 164 | 165 | /** 166 | * This function returns a promise that resolve the string as SRV DNS Name 167 | * 168 | * @param dnsName 169 | * @returns {Promise} 170 | */ 171 | var resolveSRV = dnsName => new Promise((resolve, reject) => { 172 | debug('Sending SRV request for entry=%s', dnsName); 173 | dns.resolveSrv(dnsName, function (err, result) { 174 | if (err) { 175 | debug('DNS SRV record failed to be resolved entry=%s error=', dnsName, err); 176 | return reject(err); 177 | } 178 | debug('DNS Name SRV resolved entry=%s resolved=%j', dnsName, result); 179 | if (result.length > 0) { 180 | // Sort items by name to make sure we do not detect false changes 181 | result = result.sort((a,b) => a.name.localeCompare(b.name)); 182 | Promise.all(result.map(resolveIP)) 183 | .then(resolved => resolve(resolved)) 184 | .catch(error => reject(error)); 185 | } else { 186 | resolve([]); 187 | } 188 | }); 189 | }); 190 | 191 | 192 | /** 193 | * Function that retuns a promise that will resolve into the context 194 | * for template rendering 195 | * 196 | * @returns {Promise} 197 | */ 198 | function generateContext() { 199 | var services = dnsCache.srv; 200 | var a_records = dnsCache.a; 201 | var promises = {}; 202 | services.forEach((value, dnsName) => promises[dnsName] = resolveSRV(dnsName)); 203 | a_records.forEach((value, dnsName) => promises[dnsName] = resolveA(dnsName)); 204 | 205 | debug('Starting DNS lookups for keys=%j', Object.keys(promises)); 206 | return RSVP.hashSettled(promises).then(function (result) { 207 | debug('DNS lookup completed'); 208 | var context = {}; 209 | Object.keys(result).map(key => { 210 | var promiseResult = result[key]; 211 | if (promiseResult && promiseResult.state === 'fulfilled') { 212 | // A record lookups do not have ports 213 | if ( typeof(promiseResult.value[0]['port']) == "undefined" ) 214 | a_records.set(key, promiseResult.value); 215 | else 216 | services.set(key, promiseResult.value); 217 | } else { 218 | // Set key as undefined but do not delete it 219 | services.set(key); 220 | a_records.set(key); 221 | } 222 | }); 223 | return context; 224 | }); 225 | } 226 | 227 | /** 228 | * This function will do a dry run of the template to see which DNS records we need and validate HBS template syntax 229 | * @param template 230 | */ 231 | function checkTemplate() { 232 | var templateSource = fs.readFileSync(__dirname + "/haproxy.cfg.template", "utf8"); 233 | template = handlebars.compile(templateSource); 234 | 235 | // Validate configuration and gather required SRV records 236 | // we need to do that because hanlebars does not support async helpers 237 | // we will do the first dry-run to see which DNS records we need 238 | // then fetch them and will be using them later 239 | debug('Doing the template dry-run to gather dns values') 240 | // That's a dry-run helper 241 | handlebars.registerHelper({ 242 | 'dns-srv': function gatherDataHelper(dnsName) { 243 | debug('Found dns-srv helper with parameter=%s', dnsName); 244 | dnsCache.srv.set(dnsName); 245 | }, 246 | 'dns-a': function gatherDataHelper(dnsName) { 247 | debug('Found dns-a helper with parameter=%s', dnsName); 248 | dnsCache.a.set(dnsName); 249 | } 250 | }); 251 | 252 | // Run! 253 | template(); 254 | debug('Dry-run completed, found values records srv=%s a=%s', dnsCache.srv.size, dnsCache.a.size); 255 | // Restoring the dns-srv helper to it's productive state 256 | handlebars.registerHelper({ 257 | 'dns-srv': function gatherDataHelper(dnsName, options) { 258 | debug('Looking-up dns-srv value dnsName=%s', dnsName); 259 | var map = dnsCache.srv; 260 | if (!map.get(dnsName)) { 261 | debug('DNS-SRV value was not found, block will be ignored dnsName=%s', dnsName); 262 | } else { 263 | return options.fn(map.get(dnsName)); 264 | } 265 | }, 266 | 'dns-a': function gatherDataHelper(dnsName, options) { 267 | debug('Looking-up dns-a value dnsName=%s', dnsName); 268 | var map = dnsCache.a; 269 | if (!map.get(dnsName)) { 270 | debug('DNS-A value was not found, block will be ignored dnsName=%s', dnsName); 271 | } else { 272 | return options.fn(map.get(dnsName)); 273 | } 274 | 275 | } 276 | }); 277 | return Promise.resolve(dnsCache); 278 | } 279 | 280 | /** 281 | * Promise that will do the configuration refresh of the HAProxy (if required) 282 | * 283 | * @param reload - if true and configuration changed HAProxy config reload will be triggered 284 | * @returns {Promise} 285 | */ 286 | function regenerateConfiguration() { 287 | return generateContext().then(function (context) { 288 | return new Promise(function (resolve, reject) { 289 | var originalConfig = fs.existsSync(configurationFile) ? fs.readFileSync(configurationFile, 'utf8') : ''; 290 | debug('Merging template'); 291 | var newConfig = template(context); 292 | var diff = jsdiff.diffTrimmedLines(originalConfig, newConfig, {ignoreWhitespace: true}); 293 | if (diff.length > 1 || (diff[0].added || diff[0].removed)) { 294 | info('Configuration changes detected, diff follows'); 295 | info(jsdiff.createPatch(configurationFile, originalConfig, newConfig, 'previous', 'new')); 296 | info('Writing configuration file filename=%s', configurationFile); 297 | ; 298 | fs.writeFileSync(configurationFile, newConfig, 'utf8'); 299 | info('Configuration file updated filename=%s', configurationFile); 300 | if (haproxyRunning) { 301 | info('Configuration changes were detected reloading the HAProxy'); 302 | haproxy.reload(function (err, reloaded, cmd) { 303 | if (err) { 304 | info("HAProxy reload failed error=%s cmd=%s", err, cmd); 305 | return reject(err); 306 | } 307 | info('Triggered configuration reload reloaded=%s cmd=%s', reloaded, cmd); 308 | resolve(); 309 | }); 310 | } else { 311 | info('Configuration changes were detected but HAProxy is not running yet'); 312 | resolve(); 313 | } 314 | } else { 315 | debug('No configuration changes detected'); 316 | } 317 | }); 318 | }); 319 | } 320 | 321 | 322 | /** 323 | * Promise that schedule refresh of the HAProxy config 324 | * 325 | * @returns {Promise} 326 | */ 327 | var scheduleRefresh = () => new Promise(function (resolve) { 328 | setInterval(function () { 329 | try { 330 | debug('Starting refresh cycle'); 331 | regenerateConfiguration(true) 332 | .then(()=> debug('Refresh cycle completed successfully')) 333 | .catch(onFailure); 334 | } catch (error) { 335 | onFailure(error); 336 | } 337 | }, CONFIG_REFRESH_TIMEOUT_MILLS); 338 | resolve(); 339 | }); 340 | 341 | /** 342 | * Promise that will be executed on after all is done 343 | * 344 | * @returns {Promise} 345 | */ 346 | function reportSuccess() { 347 | return new Promise(function (resolve) { 348 | info('HAProxy and configuration script successfully started'); 349 | resolve(); 350 | }); 351 | } 352 | 353 | /** 354 | * Failure handler 355 | * @param error 356 | */ 357 | function onFailure(error) { 358 | console.error('Failure happened in the process of configuration', error); 359 | process.exit(-1); 360 | } 361 | 362 | // Main sequence 363 | checkTemplate() 364 | .then(regenerateConfiguration) 365 | .then(verifyConfiguration) 366 | .then(startHAProxy) 367 | .then(scheduleRefresh) 368 | .then(reportSuccess) 369 | .catch(onFailure); 370 | --------------------------------------------------------------------------------