├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── deploy ├── publish.sh ├── pubring.gpg.enc ├── secring.gpg.enc └── settings.xml ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── rationaleemotions │ │ ├── config │ │ ├── ConfigReader.java │ │ └── MappingInfo.java │ │ ├── internal │ │ └── ProxiedTestSlot.java │ │ ├── proxy │ │ ├── GhostProxy.java │ │ └── package-info.java │ │ ├── server │ │ ├── DockerBasedSeleniumServer.java │ │ ├── DockerHelper.java │ │ ├── ISeleniumServer.java │ │ ├── JvmBasedSeleniumServer.java │ │ ├── SpawnedServer.java │ │ ├── docker │ │ │ ├── ContainerAttributes.java │ │ │ └── DeviceInfo.java │ │ └── package-info.java │ │ └── servlets │ │ ├── EnrollServlet.java │ │ └── package-info.java └── resources │ └── ondemand.json └── test ├── java └── com │ └── rationaleemotions │ └── DockerSample.java └── resources └── just-ask.json /.gitignore: -------------------------------------------------------------------------------- 1 | hs_err_pid* 2 | *.jar 3 | .settings/ 4 | .project 5 | .classpath 6 | test-output/ 7 | target/ 8 | *.swp 9 | bin/ 10 | logs/ 11 | *.DS_Store 12 | .idea/ 13 | *.iml 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | /*/build/ 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | language: java 3 | jdk: 4 | - oraclejdk8 5 | notifications: 6 | email: 7 | - krishnan.mahadevan1978@gmail.com 8 | branches: 9 | only: 10 | - master 11 | cache: 12 | directories: 13 | - "$HOME/.m2" 14 | after_success: 15 | - openssl aes-256-cbc -pass pass:$ENCRYPTION_PASSWORD -in $GPG_DIR/pubring.gpg.enc 16 | -out $GPG_DIR/pubring.gpg -d 17 | - openssl aes-256-cbc -pass pass:$ENCRYPTION_PASSWORD -in $GPG_DIR/secring.gpg.enc 18 | -out $GPG_DIR/secring.gpg -d 19 | - "$GPG_DIR/publish.sh" 20 | env: 21 | global: 22 | - GPG_DIR="`pwd`/deploy" 23 | - secure: PughDfl3usvB295Pn+GNEhAfWrs51SpNsTeQGjUQWxbzjygKOV39aFtkJfE8uPR4z1Rf4WCcvOBFpHBhgSzOH+RPv8U01f5baqWXrAPP+V2/XwmaTNH0XpR1ipeDl+huu4v9WnRrbOlG40i7HP49sCPl88SWxUIoZJUFXR1z3wj/D13YK5UW8SswYQsuqf11ze6buynl7i2/c+5W3sjeKVqOtoIkw+291JtNce/07y7DD2dt5/f3ScKWQ/s+OODHlImo3NxFeYjNYcvcKO1wpcA6O+Oiu2dSa/94EmytA1JkHnhmf2UJhVokmwLZKwGifSQM+sEc2wEY+jdUjZESpF789YtXOGvf1R2PO80xehDjW5cYihn03Zw7AWx99g0v+sAUF1qsPfff07/7dOO/pEWgij7KqazOxgmGN28ofHIrMOHho+QW/VaxpYBFyWYYRuEMwBNiAazJyQOtCihg6vthGfUHOdQdx9TifcilStiLnrt3JU4N+LSNtpfU2nRNPSPK0gF6jIaIvn1exjvxFgO3wDk98fL981mDILIOorOf6kJeTufuJJZemtIuveC8awLD/IX0BIh/DqikBp+/WAgDckKjNc9etLwRkdN3lWWtht66Qj1i2h/P/5ylfejsofimju+xPlG2xgbNhoZFb5rK4cmBBAIIVltTtxnm+xg= 24 | - secure: irIkiB5l9Q4x5h628jTmf0ZV6JGkNWwamQdRpiBzkZgqiIHuV1pYVUNFeIBiQ39iwY5Est0fjfaZ5DSy96VmnA6ZfHhcYngN9BnRRLLmARLcpTq9YVF9zrQtKjFFb/xVpAmKKsnFaczJQch4tBvZkSkP8O82gQzU9nMU7yCR1S80Pau8vNu3slRY1fV6l9IS2Qr96CIU8B3GAynR7AgVfSNrerjK2D32JBobdltd1Njhg0wqFA1lIn/MKLo4JZteYoU869aRPZliXVXYnK8TixvFQIPVUrAV3rpYrIzVgPeI5tTVgIDRBXt6JsuJy1tFT0JbxexdAzbrwxAWls7dg+hOtrW49ppdC2LZ0PhC6XHxyWB1RVX4g9DmjV3WattLscpESTRZXTKQ6wmm8eXhgLvbw6n8xr+xMRmjlp30y3/0HVwMqdXNOFqvotAOTEHyogld8GX6dACMC5ifbE5/WcKnoyA93Rzx0kUkWLR+jqNtN+711lNhVxbhzdXSKIOC2+WiOoXD3kGg0UU469IgMd9QZGHs1S924rC6Ff+FbROpm9GEfMdjyqGKpmATeJLTyjieacwvHviSktzN+eEC1HFvULYsDwUmAdtQC3Hsuxfo1AZo8g8pOypcu5sVwKkai3FyXgdbE9/s1ZeEBleHtmF9clFDfVtX1SDiryjyO4w= 25 | - secure: rCW+pYQ5P25uuWDjm9ekgJhX9M++hCZn53SaYo0xw9y2YUHYm3Ux70AK2eMAWmD8ng4tj7JIRI0gkxJ3yrrta5BQzmIQ0ixu//rKTnjqQ0Vj9lgQptNvO7wVqzILj9dfBQCrwtKqskncjNht+n7EDiEFYj94JL6UGeJDE1CGCYTRNcTgc3zx9YYz6hzI2Ae9iJRtWXwwb5KuKK9FNC5xXP0MSuqGS3fWWF7DDpc2gSMMyzq75ibBr7rfH8WD4aOCSw59JKCy6+Kp0aZPwef2n1/rW9g/Ok+A5Crhua1sOGCBVBPqmIqldI6sLPcBRhN+8hlHd1ejR8HQiASFIlgTIn9cHBKUJ9txp4Oa99OVzpcC7MTfKqDONDg3paQwAFkE1TCsniewR86Qj8k0eReTgk3uk5AbPLnffMM7xsjxONAOO+1u0rLZlltUxKbBHJJgtqtnzdccxktq8ndF2067z6QVuc+SYnhWYXhxQ3PesQytfrGZ/EoUAcXbdyDiCK082uOM0ficsoFOlxEZjGmUnuRt4fMmpo2GtKDN8hnLXamSt6LAYqbMVsaKjSHxNNtVGY9/y2rzrR1QQvskQgkoCjIZw7/2Y3TsG1gRYs9oGlB9BGOB70MB32dSli2HyNJ/fE6fSJfZYDD+mFCGjQfym69Gl0YvURMaehRhcwGt3dU= 26 | - secure: qMPwp8ipq2a9NHKbqzJ6Ca6Av958L8kRT8gp9aF5sJ11wXyAzBFdnQbcuZ+bMFRFo54arjvDJSz9Cqk6TExB+89RthU3LYUHQ7Y1b2DxYioqajMVrcno9yB7v6DMF7EbFoYv/xYDW46i30fGXS6EKpjEox7YgIsB/Q1zEkDn3Y3b/KXQJuR3SYRLQW9ZJX2jx0Aw4F/Qx9NNE5D3xYO8o2fTAZpQlMcYf0sZ1CH/tVz6kOmltiBmNyDAfI4V7OEpKwEs6mTabCaM11k59Mxn7GEQuLSG/N4ARzDUyS68jWDwbdaV9rLZZTDXqEcvYII53x5plCmG31Lo0WX2p/APDzeyh7v76PPHgxrrf4L1EKJH6SWizN2N/4g003Yrwc+vcc5QsdrVCgArO4YLZf7dboZLu2gFgXKDN02hhlZgP9jvuRJYrR++4Bo+mW5IaYTFXxTumjKsW65iFxJ4kAhIqQ8gz+JLC4n4K829avugpkszL2k2e9iIojtKfT+t7YMgIqDj6m5HCS7MjbJo1qDcagJXqp+DdRMA4SjS0KUVuZdCJ9aFLAhDdEJGsrcSwjoaIq2lwS0b57Zs9FD+TtUqErBNlw+hy8tdOoidt5oM/q2CzBcNrG7VQ24CyT1nNwItbX1xbLMDx/G0ze7EEFqS1Nq90Umm0p6FHRHvSsyT/ZI= 27 | - secure: IDkfb8h6+ZTGMpIEcvdm01w4nGVVs86KpKSYX4+tyUMNxS/jqahrjLJyeYCiuTTnwio6xwnh5xMzCfL2WbVTpMeCPi8OylB31mH7a36lil9juMiJRqb0NbPrEfTGxN7C5UAy77qTOWfrY/4fba1R09xSSLlvWdLCYHJQ2pSpicT+GfKy7qinMu5KX0DO0rg2cg1BhTwRgdr2GOkKBXohgbtU8bhQje1MOisHTFIeTHx78awrnQl1FHrZNg2aEAJiFHRmDysdPMGwFkSAIqbI687bnpfad5kj+ACpdBlB64sVNB2GJfWpN/tnzfejZARP6xb6y3X69vF01icOSv7hyeoVnQ5b18jFNiy2ePHxVP4kMuK5sQ8gBXzX0e3TZB+AhGTDByuIQtvTFYzbjEeYshwT59gcTU4RKDJVJmHWS/xhgV+jwJyoEV7ZYBFzRL58f4QojDPHxBK7oQ6T5QGbTB/90FPcJ88jYLpzocZfVvYNmcHjKBmWdEr9/8uzR5ObYppwzCh0Qtc0KvLW7AFMDw72r2t2jea/aF8C6qN70/VXcEkfbnh2+//0GKXE+akXWJIPVyOdoYhgT/aLqWOD8gZPV55KFelCH67xFFWIsMeXl5LiijpT5YvHVoUiimSjiUYpkBTx6jXNjY3vl3U9oMAikRekmEM5P9hB5U174yw= 28 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Build Status](https://travis-ci.org/RationaleEmotions/just-ask.svg?branch=master) 2 | 3 | ![JProfiler](https://www.ej-technologies.com/images/product_banners/jprofiler_large.png) Special thanks to [Java Profiler](https://www.ej-technologies.com/products/jprofiler/overview.html) for their encouragement on Open Source projects. 4 | 5 | # just-ask 6 | 7 | As the name suggests, this library is eventually going to end up becoming a simple prototype that can be enhanced to 8 | represent an "On-demand Grid" (which explains the reason behind the name **just-ask** ). 9 | 10 | ## Why an On-Demand Grid ? 11 | 12 | A static Grid (i.e., a hub and a fixed number of nodes) is a good start for setting up a remote execution infrastructure. 13 | But once the usage of the hub starts going up, problems start creeping up. 14 | Nodes go stale and start causing false failures for the tests and require constant maintenance (restart). 15 | 16 | Some of it can be solved by embedding a ["self healing"](https://rationaleemotions.wordpress.com/2013/01/28/building-a-self-maintaining-grid-environment/) mechanism into the hub, 17 | but when it comes to scaling the Grid infrastructure this also does not help a lot. 18 | 19 | **just-ask** is an on-demand grid, wherein there are no fixed nodes attached to the grid. 20 | As and when tests make hit the hub, a node is spun off, the test is routed to the node and after usage the node is 21 | cleaned up. The on-demand node can be a docker container that hosts a selenium node. 22 | 23 | ## Pre-requisites 24 | 25 | **just-ask** requires : 26 | 27 | * **JDK 8**. 28 | * A Selenium Grid of version **3.14.0** or higher. 29 | * If you would like to leverage docker based on demand solution 30 | * Access to default Docker unix socket 31 | * you can refer [here](https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option) 32 | * Or Docker Remote API enabled 33 | * For windows you can refer [here](http://scriptcrunch.com/enable-docker-remote-api/), 34 | * For UNIX refer [here](https://docs.docker.com/engine/admin/) and 35 | * For OSX refer [here](https://forums.docker.com/t/remote-api-with-docker-for-mac-beta/15639/2) 36 | 37 | 38 | ## How to use 39 | 40 | In order to consume **just-ask** for your straight forward on-demand grid needs, following instructions need to be 41 | followed: 42 | * First download the uber jar from [here](http://repo1.maven.org/maven2/com/rationaleemotions/just-ask/1.0.4/). Make sure 43 | you download the uber jar i.e., the jar name that ends with `jar-with-dependencies`. The latest released v 44 | * Download the latest Selenium standalone jar from [here](http://www.seleniumhq.org/download/). 45 | * Now create a configuration JSON file as shown below : 46 | 47 | ```json 48 | { 49 | "dockerRestApiUri": "http://192.168.43.130:2375", 50 | "localhost": "0.0.0.0", 51 | "dockerImagePort": "4444", 52 | "volume": "/dev/shm:/dev/shm", 53 | "maxSession": 5, 54 | "mapping": [ 55 | { 56 | "browser": "chrome", 57 | "target": "selenium/standalone-chrome:3.14.0", 58 | "implementation": "com.rationaleemotions.server.DockerBasedSeleniumServer" 59 | }, 60 | { 61 | "browser": "firefox", 62 | "target": "selenium/standalone-firefox:3.14.0", 63 | "implementation": "com.rationaleemotions.server.JvmBasedSeleniumServer" 64 | } 65 | ], 66 | "environment": { 67 | "SCREEN_WIDTH": 1280, 68 | "SCREEN_HEIGHT": 720 69 | } 70 | } 71 | ``` 72 | * Start the On-demand Grid using the below command (Here the JVM argument `-Dconfig.file` is used to specify the 73 | location of the JSON configuration file that we created above.) 74 | 75 | ``` 76 | java -Dconfig.file=config.json -cp selenium-server-standalone-3.14.0.jar:just-ask--jar-with-dependencies.jar \ 77 | org.openqa.grid.selenium.GridLauncherV3 -role hub -servlets com.rationaleemotions.servlets.EnrollServlet 78 | ``` 79 | 80 | * Now wire in the Ghost Proxy into this on-demand hub by loading the URL : 81 | **http://localhost:4444/grid/admin/EnrollServlet** 82 | 83 | * That's about it. The On-demand Grid is now ready for use. 84 | 85 | * To run tests against the On-demand Grid you just instantiate a `RemoteWebDriver` instance and then work with it. 86 | 87 | Here's a sample that shows using chrome browser: 88 | 89 | ```java 90 | URL url = new URL("http://localhost:4444/wd/hub"); 91 | RemoteWebDriver driver = new RemoteWebDriver(url, DesiredCapabilities.chrome()); 92 | ``` 93 | 94 | ## Understanding the JSON configuration file. 95 | The meaning of each of the attributes of the JSON file is as below : 96 | 97 | * `dockerRestApiUri` - Represents the Docker Rest API URI (could be `unix:///var/run/docker.sock` or `http://192.168.43.130:2375`). 98 | * `localhost` - Represents the hostname of the machine on which the Docker Daemon is running on (Its safe to leave 99 | its value as `0.0.0.0` ) 100 | * `dockerImagePort` - Represents the port number that is exposed inside the docker container. 101 | * `volume` - Represents a volume to be mounted. Can be left empty. 102 | * `maxSession` - Represents the maximum number of concurrent sessions that can be supported by the On-demand Hub 103 | after which new test session requests will be queued. 104 | * `mapping` - Represents a set of key-value pairs wherein `browser` represents the `browser flavor` and `target` 105 | represents the name of the docker image that is capable of supporting the respective `browser`. The `target` may not 106 | be relevant to all `implementation` values (for e.g., the `target` is currently relevant ONLY for `docker` based 107 | on-demand nodes.) 108 | * `environment` - Represents environmental variable key-value pairs to be passed to docker container 109 | 110 | ### Understanding the relevance of `implementation` 111 | **just-ask** currently supports two implementation flavors : 112 | 113 | * `com.rationaleemotions.server.DockerBasedSeleniumServer` - Indicates that for the browser in question, you would like 114 | to leverage the Docker way of spinning off nodes on demand. 115 | * `com.rationaleemotions.server.JvmBasedSeleniumServer` - Indicates that for the browser in question, you would like 116 | to leverage the JVM way of spinning off nodes on demand (i.e., the on-demand node would be a new JVM process.) 117 | 118 | ## How to customize and use. 119 | 120 | In-case you would like to wire in your own Custom Server implementation, following is how it can be done : 121 | 122 | **just-ask** is a [Maven](https://maven.apache.org/guides/getting-started/) artifact. In order to 123 | consume it, you merely need to add the following as a dependency in your pom file. 124 | 125 | ```xml 126 | 127 | com.rationaleemotions 128 | just-ask 129 | 1.0.5 130 | 131 | ``` 132 | 133 | Now that you have added the above as a maven dependency, you build your own implementation of the Server, by 134 | implementing the interface `com.rationaleemotions.server.ISeleniumServer`. 135 | 136 | After that, you can wire in your implementation via the `implementation` attribute in the JSON configuration file 137 | using the JVM argument `-Dconfig.file`. 138 | 139 | ## Building the code on your own 140 | 141 | In order to get started with using this library here are the set of instructions that can be followed : 142 | 143 | * Build the code using `mvn clean package` 144 | * Drop the built jar (you will find two jars, so please make sure you pick up the uber jar which would have its name 145 | around something like this `just-ask--jar-with-dependencies.jar` ) in the directory that contains the 146 | selenium server standalone. 147 | * Start the selenium hub using the command `java -cp selenium-server-standalone-3.14.0.jar:just-ask--jar-with-dependencies.jar org.openqa.grid.selenium.GridLauncherV3 -role hub -servlets com.rationaleemotions.servlets.EnrollServlet` 148 | * Explicitly register the *ghost node* by loading the URL `http://localhost:4444/grid/admin/EnrollServlet` in a browser. 149 | 150 | Now the **On-demand Grid** is ready for use. 151 | -------------------------------------------------------------------------------- /deploy/publish.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ $TRAVIS_PULL_REQUEST == "false" ]]; then 4 | mvn deploy --settings $GPG_DIR/settings.xml -DperformRelease=true -DskipTests=true 5 | exit $? 6 | fi -------------------------------------------------------------------------------- /deploy/pubring.gpg.enc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RationaleEmotions/just-ask/a9ad2e98bb05741407a6258015466fb087614bfb/deploy/pubring.gpg.enc -------------------------------------------------------------------------------- /deploy/secring.gpg.enc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RationaleEmotions/just-ask/a9ad2e98bb05741407a6258015466fb087614bfb/deploy/secring.gpg.enc -------------------------------------------------------------------------------- /deploy/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ossrh 5 | ${env.SONATYPE_USERNAME} 6 | ${env.SONATYPE_PASSWORD} 7 | 8 | 9 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.rationaleemotions 6 | just-ask 7 | 1.0.6-SNAPSHOT 8 | jar 9 | 10 | just-ask 11 | A simple on-demand Grid 12 | http://maven.apache.org 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | The Apache Software License, Version 2.0 21 | http://www.apache.org/licenses/LICENSE-2.0.txt 22 | repo 23 | 24 | 25 | 26 | 27 | scm:git:git@github.com:RationaleEmotions/just-ask.git 28 | scm:git:git@github.com:RationaleEmotions/just-ask.git 29 | https://github.com/RationaleEmotions/just-ask 30 | 31 | 32 | 33 | krmahadevan 34 | Krishnan Mahadevan 35 | https://github.com/krmahadevan 36 | 37 | Owner 38 | 39 | 40 | 41 | 42 | 43 | https://github.com/RationaleEmotions/just-ask/issues 44 | GitHub Issues 45 | 46 | 47 | 48 | org.seleniumhq.selenium 49 | selenium-server 50 | 3.141.59 51 | provided 52 | 53 | 54 | com.spotify 55 | docker-client 56 | 8.16.0 57 | 58 | 59 | org.slf4j 60 | slf4j-jdk14 61 | 1.7.21 62 | 63 | 64 | org.testng 65 | testng 66 | 6.10 67 | test 68 | 69 | 70 | com.google.code.gson 71 | gson 72 | 2.8.5 73 | 74 | 75 | 76 | 77 | 78 | org.apache.maven.plugins 79 | maven-compiler-plugin 80 | 3.0 81 | 82 | 1.8 83 | 1.8 84 | 85 | 86 | 87 | org.apache.maven.plugins 88 | maven-surefire-plugin 89 | 2.19.1 90 | 91 | 92 | org.apache.maven.plugins 93 | maven-assembly-plugin 94 | 2.4 95 | 96 | 97 | jar-with-dependencies 98 | 99 | 100 | 101 | 102 | make-assembly 103 | package 104 | 105 | single 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | ossrh 116 | https://oss.sonatype.org/content/repositories/snapshots 117 | 118 | 119 | ossrh 120 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 121 | 122 | 123 | 124 | 125 | 126 | release 127 | 128 | gpg 129 | ${env.GPG_KEYNAME} 130 | ${env.GPG_PASSPHRASE} 131 | false 132 | ${env.GPG_DIR}/pubring.gpg 133 | ${env.GPG_DIR}/secring.gpg 134 | 135 | 136 | 137 | performRelease 138 | true 139 | 140 | 141 | 142 | 143 | 144 | org.sonatype.plugins 145 | nexus-staging-maven-plugin 146 | 1.6.3 147 | true 148 | 149 | ossrh 150 | https://oss.sonatype.org/ 151 | true 152 | 153 | 154 | 155 | 156 | org.apache.maven.plugins 157 | maven-source-plugin 158 | 2.2.1 159 | 160 | 161 | attach-sources 162 | 163 | jar-no-fork 164 | 165 | 166 | 167 | 168 | 169 | 170 | org.apache.maven.plugins 171 | maven-javadoc-plugin 172 | 2.10.3 173 | 174 | 175 | attach-javadocs 176 | 177 | jar 178 | 179 | 180 | 181 | 182 | 183 | 184 | org.apache.maven.plugins 185 | maven-gpg-plugin 186 | 1.6 187 | 188 | 189 | sign-artifacts 190 | verify 191 | 192 | sign 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/config/ConfigReader.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.config; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.google.gson.Gson; 5 | import com.google.gson.stream.JsonReader; 6 | 7 | import java.io.File; 8 | import java.io.FileInputStream; 9 | import java.io.InputStream; 10 | import java.io.InputStreamReader; 11 | import java.net.URI; 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.logging.Logger; 17 | 18 | /** 19 | * A singleton instance that works as a configuration data source. 20 | */ 21 | public class ConfigReader { 22 | private static final String JVM_ARG = "config.file"; 23 | private static final String CONFIG = System.getProperty(JVM_ARG); 24 | private Configuration configuration; 25 | 26 | 27 | private interface Marker { 28 | } 29 | 30 | 31 | private static final Logger LOG = Logger.getLogger(Marker.class.getEnclosingClass().getName()); 32 | 33 | /** 34 | * @return - A {@link ConfigReader} that represents the configuration. 35 | */ 36 | public static ConfigReader getInstance() { 37 | return ReaderInstance.instance; 38 | } 39 | 40 | /** 41 | * @return - The docker rest api uri. 42 | */ 43 | public URI getDockerRestApiUri() { 44 | if (configuration == null) { 45 | return null; 46 | } 47 | return URI.create(configuration.getDockerRestApiUri().replaceAll("^unix:///", "unix://localhost/")); 48 | } 49 | 50 | /** 51 | * @return - The IP address of the machine wherein the docker daemon is running. It is typically left as 52 | * 0.0.0.0 53 | */ 54 | public String getLocalhost() { 55 | if (configuration == null) { 56 | return null; 57 | } 58 | return configuration.getLocalhost(); 59 | } 60 | 61 | /** 62 | * @return - The port number that is exposed in the docker image to which traffic is to be routed to. 63 | */ 64 | public String getDockerImagePort() { 65 | if (configuration == null) { 66 | return null; 67 | } 68 | return configuration.getDockerImagePort(); 69 | } 70 | 71 | /** 72 | * @return - The environmental variables to pass to container 73 | */ 74 | public Map getEnvironment() { 75 | return configuration.getEnvironment(); 76 | } 77 | 78 | /** 79 | * @return - The browser to target (target could for e.g., be docker image) mapping. 80 | */ 81 | public Map getMapping() { 82 | Map mapping = new HashMap<>(); 83 | for (MappingInfo each : configuration.getMapping()) { 84 | mapping.put(each.getBrowser(), each); 85 | } 86 | return mapping; 87 | } 88 | 89 | /** 90 | * @return - How many number of sessions are to be honoured at any given point in time. 91 | * This kind of resembles the threshold value after which new session requests would be put into the 92 | * Hub's wait queue. 93 | */ 94 | public int getMaxSession() { 95 | if (configuration == null) { 96 | return 10; 97 | } 98 | return configuration.getMaxSession(); 99 | } 100 | 101 | /** 102 | * @return - The volume to mount to a container 103 | */ 104 | public String getVolume() { 105 | if (configuration == null) { 106 | return ""; 107 | } 108 | return configuration.getVolume(); 109 | } 110 | 111 | private static class ReaderInstance { 112 | static final ConfigReader instance = new ConfigReader(); 113 | 114 | static { 115 | init(); 116 | } 117 | 118 | private ReaderInstance() { 119 | //Defeat instantiation. 120 | } 121 | 122 | private static void init() { 123 | InputStream stream = getStream(); 124 | Preconditions.checkState(stream != null, "Unable to load configuration file."); 125 | instance.configuration = new Gson().fromJson(new JsonReader(new InputStreamReader(stream)), Configuration 126 | .class); 127 | LOG.info(String.format("Working with the Configuration : %s", instance.configuration)); 128 | } 129 | } 130 | 131 | private static InputStream getStream() { 132 | try { 133 | LOG.fine(String.format("Attempting to read %s as resource.", CONFIG)); 134 | InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG); 135 | if (stream == null) { 136 | LOG.fine(String.format("Re-attempting to read %s as a local file.", CONFIG)); 137 | return new FileInputStream(new File(CONFIG)); 138 | } 139 | } catch (Exception e) { 140 | //Gobble exception 141 | } 142 | return null; 143 | } 144 | 145 | 146 | private static class Configuration { 147 | private String dockerRestApiUri; 148 | private String localhost; 149 | private String dockerImagePort; 150 | private int maxSession; 151 | private String volume; 152 | private List mapping = new ArrayList<>(); 153 | private Map environment = new HashMap<>(); 154 | 155 | public String getDockerRestApiUri() { 156 | return dockerRestApiUri; 157 | } 158 | 159 | public String getLocalhost() { 160 | return localhost; 161 | } 162 | 163 | public String getDockerImagePort() { 164 | return dockerImagePort; 165 | } 166 | 167 | public int getMaxSession() { 168 | return maxSession; 169 | } 170 | 171 | public String getVolume() { 172 | return volume; 173 | } 174 | 175 | public List getMapping() { 176 | return mapping; 177 | } 178 | 179 | public Map getEnvironment() { 180 | return environment; 181 | } 182 | 183 | @Override 184 | public String toString() { 185 | return "Configuration{" + 186 | "dockerRestApiUri='" + dockerRestApiUri + '\'' + 187 | ", localhost='" + localhost + '\'' + 188 | ", dockerImagePort='" + dockerImagePort + '\'' + 189 | ", maxSession=" + maxSession + 190 | ", volume=" + volume + 191 | ", environment=" + environment + 192 | ", mapping=" + mapping + 193 | '}'; 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/config/MappingInfo.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.config; 2 | 3 | /** 4 | * A simple POJO that represents the mapping 5 | */ 6 | public class MappingInfo { 7 | private String browser; 8 | private String target; 9 | private String implementation; 10 | 11 | public String getBrowser() { 12 | return browser; 13 | } 14 | 15 | public String getTarget() { 16 | return target; 17 | } 18 | 19 | public String getImplementation() { 20 | return implementation; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | return String.format("MappingInfo{browser='%s',target='%s', implementation='%s'}", 26 | browser, target,implementation); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/internal/ProxiedTestSlot.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.internal; 2 | 3 | import org.openqa.grid.common.SeleniumProtocol; 4 | import org.openqa.grid.common.exception.GridException; 5 | import org.openqa.grid.internal.RemoteProxy; 6 | import org.openqa.grid.internal.TestSlot; 7 | 8 | import java.net.MalformedURLException; 9 | import java.net.URL; 10 | import java.util.Map; 11 | 12 | /** 13 | * A proxied Test Slot that has the ability to delegate the calls to an actual proxy node. 14 | */ 15 | public class ProxiedTestSlot extends TestSlot { 16 | private URL remoteURL; 17 | 18 | public ProxiedTestSlot(RemoteProxy proxy, SeleniumProtocol protocol, Map capabilities) { 19 | super(proxy, protocol, capabilities); 20 | } 21 | 22 | @Override 23 | public URL getRemoteURL() { 24 | boolean isRemoteURLSet = remoteURL != null; 25 | String u = remoteURL + getPath(); 26 | try { 27 | return new URL(u); 28 | } catch (MalformedURLException e) { 29 | if (isRemoteURLSet) { 30 | throw new GridException("Configuration error for the node." + u + " isn't a valid URL"); 31 | } 32 | else { 33 | return super.getRemoteURL(); 34 | } 35 | } 36 | } 37 | 38 | public void setRemoteURL(URL remoteURL) { 39 | this.remoteURL = remoteURL; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/proxy/GhostProxy.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.proxy; 2 | 3 | import com.google.common.collect.MapMaker; 4 | import com.rationaleemotions.config.ConfigReader; 5 | import com.rationaleemotions.internal.ProxiedTestSlot; 6 | import com.rationaleemotions.server.SpawnedServer; 7 | import java.util.HashMap; 8 | import org.openqa.grid.common.RegistrationRequest; 9 | import org.openqa.grid.common.SeleniumProtocol; 10 | import org.openqa.grid.common.exception.GridException; 11 | import org.openqa.grid.internal.GridRegistry; 12 | import org.openqa.grid.internal.TestSession; 13 | import org.openqa.grid.internal.TestSlot; 14 | import org.openqa.grid.selenium.proxy.DefaultRemoteProxy; 15 | import org.openqa.grid.web.servlet.handler.RequestType; 16 | import org.openqa.grid.web.servlet.handler.SeleniumBasedRequest; 17 | import org.openqa.selenium.remote.CapabilityType; 18 | 19 | import javax.servlet.http.HttpServletRequest; 20 | import javax.servlet.http.HttpServletResponse; 21 | import java.net.URL; 22 | import java.util.Map; 23 | import java.util.concurrent.atomic.AtomicInteger; 24 | import java.util.logging.Level; 25 | import java.util.logging.Logger; 26 | 27 | import static org.openqa.grid.web.servlet.handler.RequestType.START_SESSION; 28 | 29 | /** 30 | * Represents a simple {@link DefaultRemoteProxy} implementation that relies on spinning off a server 31 | * and then routing the session traffic to the spawned server. 32 | */ 33 | public class GhostProxy extends DefaultRemoteProxy { 34 | private final AtomicInteger counter = new AtomicInteger(0); 35 | 36 | 37 | private interface Marker { 38 | } 39 | 40 | private static final Logger LOG = Logger.getLogger(Marker.class.getEnclosingClass().getName()); 41 | private Map servers = new MapMaker().initialCapacity(500).makeMap(); 42 | 43 | public GhostProxy(RegistrationRequest request, GridRegistry registry) { 44 | super(request, registry); 45 | LOG.info("Maximum sessions supported: " + ConfigReader.getInstance().getMaxSession()); 46 | } 47 | 48 | @Override 49 | public TestSlot createTestSlot(SeleniumProtocol protocol, Map capabilities) { 50 | return new ProxiedTestSlot(this, protocol, capabilities); 51 | } 52 | 53 | @Override 54 | public TestSession getNewSession(Map requestedCapability) { 55 | 56 | LOG.fine(String.format("Trying to create a new session on node %s", this)); 57 | 58 | if (!hasCapability(requestedCapability)) { 59 | LOG.fine("Node " + this + " has no matching capability"); 60 | return null; 61 | } 62 | 63 | if (counter.get() > ConfigReader.getInstance().getMaxSession()) { 64 | LOG.info("Waiting for remote nodes to be available"); 65 | return null; 66 | } 67 | 68 | // any slot left for the given app ? 69 | for (TestSlot testslot : getTestSlots()) { 70 | TestSession session = testslot.getNewSession(requestedCapability); 71 | if (session != null) { 72 | return session; 73 | } 74 | } 75 | return null; 76 | } 77 | 78 | @Override 79 | public void beforeRelease(TestSession session) { 80 | // release the resources remotely if the remote started a browser. 81 | if (session.getExternalKey() == null) { 82 | return; 83 | } 84 | boolean ok = session.sendDeleteSessionRequest(); 85 | if (ok && processTestSession(session)) { 86 | stopServerForTestSession(session); 87 | } 88 | if (!ok) { 89 | LOG.warning("Error releasing the resources on timeout for session " + session); 90 | } 91 | } 92 | 93 | @Override 94 | public void beforeCommand(TestSession session, HttpServletRequest request, HttpServletResponse response) { 95 | RequestType type = identifyRequestType(request); 96 | if (type == START_SESSION) { 97 | if (processTestSession(session)) { 98 | startServerForTestSession(session); 99 | } else { 100 | LOG.info("Missing target mapping. Available mappings are: " + ConfigReader.getInstance().getMapping()); 101 | } 102 | } 103 | super.beforeCommand(session, request, response); 104 | } 105 | 106 | @Override 107 | public void afterSession(TestSession session) { 108 | if (processTestSession(session)) { 109 | stopServerForTestSession(session); 110 | } 111 | } 112 | 113 | @Override 114 | public Map getProxyStatus() { 115 | return new HashMap<>(); 116 | } 117 | 118 | private RequestType identifyRequestType(HttpServletRequest request) { 119 | return SeleniumBasedRequest.createFromRequest(request, getRegistry()).extractRequestType(); 120 | } 121 | 122 | private boolean processTestSession(TestSession session) { 123 | Map requestedCapabilities = session.getRequestedCapabilities(); 124 | String browser = (String) requestedCapabilities.get(CapabilityType.BROWSER_NAME); 125 | return ConfigReader.getInstance().getMapping().containsKey(browser); 126 | } 127 | 128 | private void startServerForTestSession(TestSession session) { 129 | try { 130 | SpawnedServer server = SpawnedServer.spawnInstance(session); 131 | String key = "http://" + server.getHost() + ":" + server.getPort(); 132 | URL url = new URL(key); 133 | servers.put(key, server); 134 | ((ProxiedTestSlot) session.getSlot()).setRemoteURL(url); 135 | if (LOG.isLoggable(Level.INFO)) { 136 | LOG.info(String.format("Forwarding session to: %s", session.getSlot().getRemoteURL())); 137 | LOG.info(String.format("Counter value after incrementing: %d", counter.incrementAndGet())); 138 | } 139 | } catch (Exception e) { 140 | throw new GridException(e.getMessage(), e); 141 | } 142 | } 143 | 144 | private void stopServerForTestSession(TestSession session) { 145 | URL url = session.getSlot().getRemoteURL(); 146 | String key = String.format("%s://%s:%d", url.getProtocol(), url.getHost(), url.getPort()); 147 | SpawnedServer localServer = servers.get(key); 148 | if (localServer != null) { 149 | localServer.shutdown(); 150 | servers.remove(key); 151 | LOG.info(String.format("Counter value after decrementing: %d", counter.decrementAndGet())); 152 | } 153 | } 154 | 155 | } 156 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/proxy/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This package houses the proxy definitions. 3 | */ 4 | package com.rationaleemotions.proxy; 5 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/DockerBasedSeleniumServer.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.server; 2 | 3 | import com.rationaleemotions.config.ConfigReader; 4 | import com.rationaleemotions.server.docker.DeviceInfo; 5 | import com.spotify.docker.client.UnixConnectionSocketFactory; 6 | import com.spotify.docker.client.exceptions.DockerException; 7 | import org.openqa.grid.internal.TestSession; 8 | import org.openqa.selenium.remote.CapabilityType; 9 | 10 | import java.net.URI; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * Represents a {@link ISeleniumServer} implementation that is backed by a docker container which executes the 16 | * selenium server within a docker container. 17 | * 18 | */ 19 | public class DockerBasedSeleniumServer implements ISeleniumServer { 20 | protected DockerHelper.ContainerInfo containerInfo; 21 | 22 | @Override 23 | public int startServer(TestSession session) throws ServerException { 24 | try { 25 | String browser = (String) session.getRequestedCapabilities().get(CapabilityType.BROWSER_NAME); 26 | String image = ConfigReader.getInstance().getMapping().get(browser).getTarget(); 27 | containerInfo = DockerHelper.startContainerFor(image, isPrivileged(), getDeviceInfos()); 28 | return containerInfo.getPort(); 29 | } catch (DockerException | InterruptedException e) { 30 | throw new ServerException(e.getMessage(), e); 31 | } 32 | } 33 | 34 | @Override 35 | public int getPort() { 36 | return this.containerInfo.getPort(); 37 | } 38 | 39 | @Override 40 | public String getHost() { 41 | URI uri=ConfigReader.getInstance().getDockerRestApiUri(); 42 | if (uri.getScheme().equals(DockerHelper.UNIX_SCHEME)) { 43 | return UnixConnectionSocketFactory.sanitizeUri(uri).getHost(); 44 | } else { 45 | return uri.getHost(); 46 | } 47 | } 48 | 49 | @Override 50 | public void shutdownServer() throws ServerException { 51 | try { 52 | DockerHelper.killAndRemoveContainer(containerInfo.getContainerId()); 53 | } catch (DockerException | InterruptedException e) { 54 | throw new ServerException(e.getMessage(), e); 55 | } 56 | } 57 | 58 | public boolean isPrivileged() { 59 | return false; 60 | } 61 | public List getDeviceInfos() { 62 | return new ArrayList<>(); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/DockerHelper.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.server; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.rationaleemotions.config.ConfigReader; 5 | import com.rationaleemotions.config.MappingInfo; 6 | import com.rationaleemotions.server.docker.DeviceInfo; 7 | import com.spotify.docker.client.DefaultDockerClient; 8 | import com.spotify.docker.client.DockerClient; 9 | import com.spotify.docker.client.LoggingBuildHandler; 10 | import com.spotify.docker.client.ProgressHandler; 11 | import com.spotify.docker.client.exceptions.DockerException; 12 | import com.spotify.docker.client.messages.*; 13 | import java.util.stream.Collectors; 14 | import org.openqa.selenium.net.PortProber; 15 | 16 | import java.util.*; 17 | import java.util.logging.Level; 18 | import java.util.logging.Logger; 19 | 20 | import static com.rationaleemotions.config.ConfigReader.getInstance; 21 | 22 | /** 23 | * A Helper class that facilitates interaction with a Docker Daemon. 24 | */ 25 | class DockerHelper { 26 | private interface Marker { 27 | } 28 | 29 | 30 | private static final Logger LOG = Logger.getLogger(Marker.class.getEnclosingClass().getName()); 31 | 32 | public static final String UNIX_SCHEME = "unix"; 33 | 34 | private DockerHelper() { 35 | DockerClient client = getClient(); 36 | Runtime.getRuntime().addShutdownHook(new Thread(new DockerCleanup(client))); 37 | } 38 | 39 | /** 40 | * @param id - The ID of the container that is to be cleaned up. 41 | * @throws DockerException - In case of any issues. 42 | * @throws InterruptedException - In case of any issues. 43 | */ 44 | static void killAndRemoveContainer(String id) throws DockerException, InterruptedException { 45 | if (LOG.isLoggable(Level.FINE)) { 46 | LOG.fine("Killing the container : [" + id + "]."); 47 | } 48 | getClient().killContainer(id); 49 | getClient().removeContainer(id); 50 | } 51 | 52 | /** 53 | * @param image - The name of the image for which a docker container is to be spun off. For e.g., you could 54 | * specify the image name as selenium/standalone-chrome:3.0.1 to download the 55 | * standalone-chrome image with its tag as 3.0.1 56 | * @param isPrivileged - true if the container is to be run in privileged mode. 57 | * @param devices - A List of {@link DeviceInfo} objects 58 | * @return - A {@link ContainerInfo} object that represents the newly spun off container. 59 | * @throws DockerException - In case of any issues. 60 | * @throws InterruptedException - In case of any issues. 61 | */ 62 | static ContainerInfo startContainerFor(String image, boolean isPrivileged, List devices) 63 | throws DockerException, InterruptedException { 64 | if (LOG.isLoggable(Level.FINE)) { 65 | LOG.fine("Commencing starting of container for the image [" + image + "]."); 66 | } 67 | Preconditions.checkState("ok".equalsIgnoreCase(getClient().ping()), 68 | "Ensuring that the Docker Daemon is up and running."); 69 | DockerHelper.predownloadImagesIfRequired(); 70 | 71 | final Map> portBindings = new HashMap<>(); 72 | 73 | List randomPort = new ArrayList<>(); 74 | int port = PortProber.findFreePort(); 75 | String localHost = ConfigReader.getInstance().getLocalhost(); 76 | PortBinding binding = PortBinding.create(localHost, Integer.toString(port)); 77 | 78 | randomPort.add(binding); 79 | portBindings.put(ConfigReader.getInstance().getDockerImagePort(), randomPort); 80 | 81 | List deviceList = new LinkedList<>(); 82 | for (DeviceInfo each : devices) { 83 | deviceList.add(new Device() { 84 | @Override 85 | public String pathOnHost() { 86 | return each.getPathOnHost(); 87 | } 88 | 89 | @Override 90 | public String pathInContainer() { 91 | return each.getPathOnContainer(); 92 | } 93 | 94 | @Override 95 | public String cgroupPermissions() { 96 | return each.getGroupPermissions(); 97 | } 98 | }); 99 | } 100 | 101 | HostConfig.Builder hostConfigBuilder = HostConfig.builder() 102 | .portBindings(portBindings) 103 | .privileged(isPrivileged); 104 | String volume = ConfigReader.getInstance().getVolume(); 105 | if (volume != null && !volume.isEmpty()) { 106 | hostConfigBuilder = hostConfigBuilder.binds(ConfigReader.getInstance().getVolume()); 107 | } 108 | if (!deviceList.isEmpty()) { 109 | hostConfigBuilder = hostConfigBuilder.devices(deviceList); 110 | } 111 | 112 | final HostConfig hostConfig = hostConfigBuilder.build(); 113 | 114 | // add environmental variables 115 | List envVariables = ConfigReader.getInstance().getEnvironment() 116 | .entrySet().stream() 117 | .map(entry -> entry.getKey() + "=" + entry.getValue()) 118 | .collect(Collectors.toList()); 119 | 120 | final ContainerConfig containerConfig = ContainerConfig.builder() 121 | .hostConfig(hostConfig) 122 | .image(image).exposedPorts(ConfigReader.getInstance().getDockerImagePort()).env(envVariables) 123 | .build(); 124 | 125 | final ContainerCreation creation = getClient().createContainer(containerConfig); 126 | 127 | final String id = creation.id(); 128 | 129 | // Inspect container 130 | final com.spotify.docker.client.messages.ContainerInfo containerInfo = getClient().inspectContainer(id); 131 | if (LOG.isLoggable(Level.FINE)) { 132 | LOG.fine(String.format("Container Information %s", containerInfo)); 133 | String msg = "Checking to see if the container with id [" + id + "] and name [" + 134 | containerInfo.name() + "]..."; 135 | LOG.fine(msg); 136 | } 137 | 138 | if (!containerInfo.state().running()) { 139 | // Start container 140 | getClient().startContainer(id); 141 | if (LOG.isLoggable(Level.FINE)) { 142 | LOG.info(containerInfo.name() + " is now running."); 143 | } 144 | } else { 145 | if (LOG.isLoggable(Level.FINE)) { 146 | LOG.info(containerInfo.name() + " was already running."); 147 | } 148 | } 149 | ContainerInfo info = new ContainerInfo(id, port); 150 | if (LOG.isLoggable(Level.FINE)) { 151 | LOG.fine("******" + info + "******"); 152 | } 153 | return info; 154 | } 155 | 156 | private static void predownloadImagesIfRequired() throws DockerException, InterruptedException { 157 | 158 | DockerClient client = getClient(); 159 | LOG.warning("Commencing download of images."); 160 | Collection images = getInstance().getMapping().values(); 161 | 162 | ProgressHandler handler = new LoggingBuildHandler(); 163 | for (MappingInfo image : images) { 164 | List foundImages = client.listImages(DockerClient.ListImagesParam.byName(image.getTarget())); 165 | if (! foundImages.isEmpty()) { 166 | LOG.warning(String.format("Skipping download for Image [%s] because it's already available.", 167 | image.getTarget())); 168 | continue; 169 | } 170 | client.pull(image.getTarget(), handler); 171 | } 172 | } 173 | 174 | private static DockerClient getClient() { 175 | return DefaultDockerClient.builder().uri(getInstance().getDockerRestApiUri()).build(); 176 | } 177 | 178 | /** 179 | * A Simple POJO that represents the newly spun off container, encapsulating the container Id and the port on which 180 | * the container is running. 181 | */ 182 | public static class ContainerInfo { 183 | private int port; 184 | private String containerId; 185 | 186 | ContainerInfo(String containerId, int port) { 187 | this.port = port; 188 | this.containerId = containerId; 189 | } 190 | 191 | public int getPort() { 192 | return port; 193 | } 194 | 195 | public String getContainerId() { 196 | return containerId; 197 | } 198 | 199 | @Override 200 | public String toString() { 201 | return String.format("%s running on %d", containerId, port); 202 | } 203 | } 204 | 205 | 206 | private static class DockerCleanup implements Runnable { 207 | private DockerClient client; 208 | 209 | DockerCleanup(DockerClient client) { 210 | this.client = client; 211 | } 212 | 213 | @Override 214 | public void run() { 215 | if (client != null) { 216 | client.close(); 217 | } 218 | } 219 | } 220 | 221 | } 222 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/ISeleniumServer.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.server; 2 | 3 | import org.apache.http.HttpResponse; 4 | import org.apache.http.HttpStatus; 5 | import org.apache.http.client.methods.HttpGet; 6 | import org.apache.http.impl.client.CloseableHttpClient; 7 | import org.apache.http.impl.client.HttpClientBuilder; 8 | import org.openqa.grid.common.exception.GridConfigurationException; 9 | import org.openqa.grid.internal.TestSession; 10 | 11 | import java.io.IOException; 12 | 13 | /** 14 | * Represents the capabilities that a typical selenium server should possess. 15 | */ 16 | public interface ISeleniumServer { 17 | /** 18 | * @return - true if the server is running. 19 | */ 20 | default boolean isServerRunning() { 21 | String url = String.format("http://%s:%d/wd/hub/status", getHost(), getPort()); 22 | HttpGet host = new HttpGet(url); 23 | try (CloseableHttpClient client = HttpClientBuilder.create().build()) { 24 | HttpResponse response = client.execute(host); 25 | return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; 26 | } catch (IOException | GridConfigurationException e) { 27 | //Gobble Exception 28 | } 29 | return false; 30 | } 31 | 32 | /** 33 | * Helps start a selenium server. 34 | * 35 | * @param session - the capabilities the client requested. 36 | * @return - The port on which the server was spun off. 37 | * @throws ServerException - In case of problems. 38 | */ 39 | int startServer(TestSession session) throws ServerException; 40 | 41 | /** 42 | * @return - The port on which the server was spun off. 43 | */ 44 | int getPort(); 45 | 46 | /** 47 | * 48 | * @return - The host on which the server is running. 49 | */ 50 | String getHost(); 51 | 52 | /** 53 | * Shutsdown the server. 54 | * 55 | * @throws ServerException - In case of problems. 56 | */ 57 | void shutdownServer() throws ServerException; 58 | 59 | /** 60 | * Represents all exceptions that can arise out of attempts to manipulate server. 61 | */ 62 | class ServerException extends Exception { 63 | public ServerException(String message, Throwable e) { 64 | super(message, e); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/JvmBasedSeleniumServer.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.server; 2 | 3 | import com.rationaleemotions.servlets.EnrollServlet; 4 | import org.openqa.grid.internal.TestSession; 5 | import org.openqa.grid.selenium.GridLauncherV3; 6 | import org.openqa.selenium.net.PortProber; 7 | 8 | import java.io.File; 9 | import java.util.Arrays; 10 | import java.util.logging.Level; 11 | import java.util.logging.Logger; 12 | 13 | /** 14 | * Represents a {@link ISeleniumServer} implementation that is backed by a new JVM which executes the 15 | * selenium server as a separate process. 16 | */ 17 | public class JvmBasedSeleniumServer implements ISeleniumServer { 18 | private static final Logger LOG = Logger.getLogger(Marker.class.getEnclosingClass().getName()); 19 | private static final String JAVA = System.getProperty("java.home") + File.separator + "bin" + File.separator + 20 | "java"; 21 | private static final String CP = "-cp"; 22 | private static final String CLASSPATH = System.getProperty("java.class.path"); 23 | private static final String PORT_ARG = "-port"; 24 | private static final String MAIN_CLASS = GridLauncherV3.class.getCanonicalName(); 25 | private Process process; 26 | private int port; 27 | 28 | private static String[] getArgs(int port) { 29 | return new String[] { 30 | JAVA, 31 | CP, 32 | CLASSPATH, 33 | MAIN_CLASS, 34 | PORT_ARG, 35 | Integer.toString(port) 36 | }; 37 | } 38 | 39 | @Override 40 | public int getPort() { 41 | return port; 42 | } 43 | 44 | @Override 45 | public int startServer(TestSession session) throws ServerException { 46 | port = PortProber.findFreePort(); 47 | String[] args = getArgs(port); 48 | if (LOG.isLoggable(Level.INFO)) { 49 | LOG.info(String.format("Spawning a Selenium server using the arguments [%s]", Arrays.toString(args))); 50 | } 51 | ProcessBuilder pb = new ProcessBuilder(getArgs(port)); 52 | try { 53 | this.process = pb.start(); 54 | return port; 55 | } catch (Exception e) { 56 | throw new ServerException(e.getMessage(), e); 57 | } 58 | } 59 | 60 | @Override 61 | public void shutdownServer() { 62 | if (process != null) { 63 | process.destroyForcibly(); 64 | LOG.warning("***Server shutdown****"); 65 | process = null; 66 | } 67 | } 68 | 69 | @Override 70 | public String getHost() { 71 | return EnrollServlet.getHubHost(); 72 | } 73 | 74 | private interface Marker { 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/SpawnedServer.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.server; 2 | 3 | import com.rationaleemotions.config.ConfigReader; 4 | import org.openqa.grid.internal.TestSession; 5 | import org.openqa.selenium.remote.CapabilityType; 6 | 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | import java.util.logging.Level; 10 | import java.util.logging.Logger; 11 | 12 | public class SpawnedServer { 13 | private interface Marker { 14 | } 15 | 16 | private static final Logger LOG = Logger.getLogger(Marker.class.getEnclosingClass().getName()); 17 | 18 | private ISeleniumServer server; 19 | 20 | private SpawnedServer() { 21 | //We have a factory method. Hiding the constructor. 22 | } 23 | 24 | public static SpawnedServer spawnInstance(TestSession session) throws Exception { 25 | SpawnedServer server = new SpawnedServer(); 26 | AtomicInteger attempts = new AtomicInteger(0); 27 | String browser = (String) session.getRequestedCapabilities().get(CapabilityType.BROWSER_NAME); 28 | server.server = newInstance(browser); 29 | int port = server.server.startServer(session); 30 | 31 | do { 32 | TimeUnit.SECONDS.sleep(2); 33 | } while (!server.server.isServerRunning() && attempts.incrementAndGet() <= 5); 34 | if (LOG.isLoggable(Level.WARNING)) { 35 | LOG.warning(String.format("***Server started on [%d]****", port)); 36 | } 37 | return server; 38 | } 39 | 40 | public String getHost() { 41 | return server.getHost(); 42 | } 43 | 44 | public int getPort() { 45 | return server.getPort(); 46 | } 47 | 48 | private static ISeleniumServer newInstance(String browser) 49 | throws ClassNotFoundException, IllegalAccessException, InstantiationException { 50 | return (ISeleniumServer) getServerClass(browser).newInstance(); 51 | } 52 | 53 | private static Class getServerClass(String browser) throws ClassNotFoundException { 54 | String serverImpl = ConfigReader.getInstance().getMapping().get(browser).getImplementation(); 55 | Class clazz = Class.forName(serverImpl); 56 | LOG.info("Working with the implementation : [" + clazz.getCanonicalName() + "]."); 57 | if (ISeleniumServer.class.isAssignableFrom(clazz)) { 58 | return clazz; 59 | } 60 | throw new IllegalStateException(serverImpl + " does not extend " + ISeleniumServer.class 61 | .getCanonicalName()); 62 | } 63 | 64 | public void shutdown() { 65 | try { 66 | server.shutdownServer(); 67 | LOG.warning("***Server running on [" + getPort() + "] has been stopped****"); 68 | } catch (Exception e) { 69 | LOG.warning(e.getMessage()); 70 | } 71 | } 72 | 73 | @Override 74 | public String toString() { 75 | return "SpawnedServer[" + getHost() + ":" + getPort() + "]"; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/docker/ContainerAttributes.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.server.docker; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class ContainerAttributes { 7 | private String imageName; 8 | private boolean isPrivileged; 9 | private List deviceInfos; 10 | 11 | public String getImageName() { 12 | return imageName; 13 | } 14 | 15 | public void setImageName(String imageName) { 16 | this.imageName = imageName; 17 | } 18 | 19 | public boolean isPrivileged() { 20 | return isPrivileged; 21 | } 22 | 23 | public void setPrivileged(boolean privileged) { 24 | isPrivileged = privileged; 25 | } 26 | 27 | public List getDeviceInfos() { 28 | return deviceInfos; 29 | } 30 | 31 | public void setDeviceInfos(DeviceInfo... deviceInfos) { 32 | this.deviceInfos = Arrays.asList(deviceInfos); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/docker/DeviceInfo.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.server.docker; 2 | 3 | /** 4 | * 5 | */ 6 | public class DeviceInfo { 7 | private String pathOnContainer; 8 | private String pathOnHost; 9 | private String groupPermissions; 10 | 11 | public DeviceInfo(String pathOnHost) { 12 | this(pathOnHost, pathOnHost); 13 | } 14 | 15 | public DeviceInfo(String pathOnHost, String pathOnContainer) { 16 | this(pathOnHost, pathOnContainer, "crw"); 17 | } 18 | 19 | public DeviceInfo(String pathOnHost, String pathOnContainer, String groupPermissions) { 20 | this.pathOnContainer = pathOnHost; 21 | this.pathOnHost = pathOnContainer; 22 | this.groupPermissions = groupPermissions; 23 | } 24 | 25 | public String getGroupPermissions() { 26 | return groupPermissions; 27 | } 28 | 29 | public String getPathOnContainer() { 30 | return pathOnContainer; 31 | } 32 | 33 | public String getPathOnHost() { 34 | return pathOnHost; 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | return "DeviceInfo{" + 40 | "pathOnContainer='" + pathOnContainer + '\'' + 41 | ", pathOnHost='" + pathOnHost + '\'' + 42 | ", groupPermissions='" + groupPermissions + '\'' + 43 | '}'; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/server/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This package houses the server implementations. 3 | */ 4 | package com.rationaleemotions.server; 5 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/servlets/EnrollServlet.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions.servlets; 2 | 3 | import com.google.common.base.Preconditions; 4 | import com.google.gson.JsonArray; 5 | import com.google.gson.JsonObject; 6 | import com.google.gson.JsonParser; 7 | import com.rationaleemotions.config.ConfigReader; 8 | import java.io.BufferedReader; 9 | import java.nio.charset.Charset; 10 | import java.util.stream.Collectors; 11 | import org.apache.http.HttpHost; 12 | import org.apache.http.HttpResponse; 13 | import org.apache.http.HttpStatus; 14 | import org.apache.http.client.HttpClient; 15 | import org.apache.http.entity.StringEntity; 16 | import org.apache.http.impl.client.HttpClientBuilder; 17 | import org.apache.http.message.BasicHttpEntityEnclosingRequest; 18 | import org.openqa.grid.common.exception.GridConfigurationException; 19 | import org.openqa.grid.common.exception.GridException; 20 | import org.openqa.grid.internal.GridRegistry; 21 | import org.openqa.grid.web.servlet.RegistryBasedServlet; 22 | 23 | import javax.servlet.ServletException; 24 | import javax.servlet.http.HttpServletRequest; 25 | import javax.servlet.http.HttpServletResponse; 26 | import java.io.IOException; 27 | import java.io.InputStream; 28 | import java.io.InputStreamReader; 29 | import java.net.URL; 30 | 31 | /** 32 | * Represents a simple servlet that needs to be invoked in order to wire in our ghost node 33 | * which will act as a proxy for all proxies. 34 | */ 35 | public class EnrollServlet extends RegistryBasedServlet { 36 | private static String hubHost; 37 | 38 | public EnrollServlet(GridRegistry registry) { 39 | super(registry); 40 | } 41 | 42 | public EnrollServlet() { 43 | this(null); 44 | } 45 | 46 | @Override 47 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 48 | addProxy(); 49 | } 50 | 51 | private void addProxy() { 52 | //After the construction is finished, lets wrap up. 53 | int status; 54 | 55 | HttpClient client = HttpClientBuilder.create().build(); 56 | 57 | try { 58 | final int port = getRegistry().getHub().getConfiguration().port; 59 | hubHost = getRegistry().getHub().getConfiguration().host; 60 | final URL registration = new URL(String.format("http://%s:%d/grid/register", hubHost, port)); 61 | BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", 62 | registration.toExternalForm()); 63 | request.setEntity(getJsonAsEntity(hubHost, port)); 64 | HttpHost host = new HttpHost(registration.getHost(), registration.getPort()); 65 | HttpResponse response = client.execute(host, request); 66 | status = response.getStatusLine().getStatusCode(); 67 | 68 | } catch (IOException | GridConfigurationException e) { 69 | throw new GridException(e.getMessage(), e); 70 | } 71 | Preconditions.checkState(status == HttpStatus.SC_OK, "There was a problem in hooking in the ghost node."); 72 | } 73 | 74 | private String convert(InputStream inputStream, Charset charset) throws IOException { 75 | 76 | try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset))) { 77 | return br.lines().collect(Collectors.joining(System.lineSeparator())); 78 | } 79 | } 80 | 81 | private StringEntity getJsonAsEntity(String host, int port) { 82 | try { 83 | InputStream isr = Thread.currentThread().getContextClassLoader().getResourceAsStream("ondemand.json"); 84 | String string = convert(isr, Charset.defaultCharset()); 85 | JsonObject ondemand = new JsonParser().parse(string).getAsJsonObject(); 86 | int maxSession =ConfigReader.getInstance().getMaxSession(); 87 | JsonArray capsArray = ondemand.get("capabilities").getAsJsonArray(); 88 | for (int i=0; i < capsArray.size(); i++) { 89 | capsArray.get(i).getAsJsonObject().addProperty("maxInstances", maxSession); 90 | } 91 | JsonObject configuration = ondemand.get("configuration").getAsJsonObject(); 92 | configuration.addProperty("maxSession", maxSession); 93 | configuration.addProperty("hub", String.format("http://%s:%d", host, port)); 94 | string = ondemand.toString(); 95 | return new StringEntity(string); 96 | } catch (IOException e) { 97 | throw new GridException(e.getMessage(), e); 98 | } 99 | } 100 | 101 | public static String getHubHost() { 102 | return hubHost; 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/rationaleemotions/servlets/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This package houses the servlets. 3 | */ 4 | package com.rationaleemotions.servlets; 5 | -------------------------------------------------------------------------------- /src/main/resources/ondemand.json: -------------------------------------------------------------------------------- 1 | { 2 | "capabilities": [ 3 | { 4 | "browserName": "firefox", 5 | "maxInstances": 1, 6 | "platform" : "ANY" 7 | }, 8 | { 9 | "browserName": "chrome", 10 | "maxInstances": 1, 11 | "platform" : "ANY" 12 | } 13 | ], 14 | "configuration": { 15 | "proxy": "com.rationaleemotions.proxy.GhostProxy", 16 | "maxSession": 1, 17 | "port": 5555, 18 | "register": true, 19 | "registerCycle": 5000, 20 | "hub": "http://localhost:4444", 21 | "nodeStatusCheckTimeout": 5000, 22 | "nodePolling": 5000, 23 | "role": "node", 24 | "unregisterIfStillDownAfter": 60000, 25 | "downPollingLimit": 2, 26 | "debug": false, 27 | "servlets": [], 28 | "withoutServlets": [], 29 | "custom": {} 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/rationaleemotions/DockerSample.java: -------------------------------------------------------------------------------- 1 | package com.rationaleemotions; 2 | 3 | import com.spotify.docker.client.DefaultDockerClient; 4 | import com.spotify.docker.client.DockerClient; 5 | import com.spotify.docker.client.LoggingBuildHandler; 6 | import com.spotify.docker.client.messages.*; 7 | import org.apache.http.HttpResponse; 8 | import org.apache.http.client.methods.HttpGet; 9 | import org.apache.http.impl.client.CloseableHttpClient; 10 | import org.apache.http.impl.client.HttpClientBuilder; 11 | import org.openqa.selenium.net.PortProber; 12 | 13 | import java.io.BufferedReader; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | import java.io.InputStreamReader; 17 | import java.net.URISyntaxException; 18 | import java.net.URL; 19 | import java.util.ArrayList; 20 | import java.util.HashMap; 21 | import java.util.List; 22 | import java.util.Map; 23 | 24 | /** 25 | * 26 | */ 27 | public class DockerSample { 28 | private static final String CENTOS = "192.168.43.130"; 29 | public static final String SELENIUM_STANDALONE_CHROME = "selenium/standalone-chrome:3.0.1"; 30 | // public static final String SELENIUM_STANDALONE_CHROME = "selenium/standalone-chrome:LATEST"; 31 | 32 | 33 | private static void foo() throws Exception { 34 | boolean debug = Boolean.parseBoolean(System.getProperty("debug", "false")); 35 | String dockerHost = String.format("http://%s:%d", CENTOS, 2375); 36 | DockerClient docker = null; 37 | try { 38 | docker = DefaultDockerClient.builder() 39 | .uri(dockerHost).build(); 40 | Info info = docker.info(); 41 | System.err.println("Information : " + info); 42 | if (debug) { 43 | docker.pull(SELENIUM_STANDALONE_CHROME, new LoggingBuildHandler()); 44 | } else { 45 | docker.pull(SELENIUM_STANDALONE_CHROME); 46 | } 47 | final ImageInfo imageInfo = docker.inspectImage(SELENIUM_STANDALONE_CHROME); 48 | System.err.println("Information : " + imageInfo); 49 | // Bind container ports to host ports 50 | // final String[] ports = {Integer.toString(PortProber.findFreePort())}; 51 | final String[] ports = {"4444"}; 52 | final Map> portBindings = new HashMap<>(); 53 | for (String port : ports) { 54 | List hostPorts = new ArrayList<>(); 55 | hostPorts.add(PortBinding.of("0.0.0.0", PortProber.findFreePort())); 56 | portBindings.put(port, hostPorts); 57 | } 58 | // // Bind container port 443 to an automatically allocated available host port. 59 | // List randomPort = new ArrayList<>(); 60 | // randomPort.add(PortBinding.randomPort("0.0.0.0")); 61 | // portBindings.put("443", randomPort); 62 | 63 | System.err.println("Printing the port mappings : " + portBindings); 64 | 65 | final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build(); 66 | 67 | final ContainerConfig containerConfig = ContainerConfig.builder() 68 | .hostConfig(hostConfig) 69 | .image(SELENIUM_STANDALONE_CHROME).exposedPorts(ports) 70 | .build(); 71 | 72 | final ContainerCreation creation = docker.createContainer(containerConfig); 73 | final String id = creation.id(); 74 | 75 | // Inspect container 76 | final ContainerInfo containerInfo = docker.inspectContainer(id); 77 | System.err.println("Container Information " + containerInfo); 78 | String msg = "Checking to see if the container with id [" + id + "] and name [" + 79 | containerInfo.name() + "]..."; 80 | System.err.println(msg); 81 | if (! containerInfo.state().running()) { 82 | // Start container 83 | docker.startContainer(id); 84 | System.err.println(containerInfo.name() + " is now running."); 85 | } else { 86 | System.err.println(containerInfo.name() + " was already running."); 87 | } 88 | 89 | System.err.println("Lets wait here !!!"); 90 | } finally { 91 | if (docker != null) { 92 | docker.close(); 93 | } 94 | } 95 | } 96 | 97 | private static void checkServer(int port) throws IOException, URISyntaxException { 98 | CloseableHttpClient client = HttpClientBuilder.create().build(); 99 | String url = String.format("http://localhost:%d/wd/hub/status", port); 100 | HttpGet httpGet = new HttpGet(new URL(url).toURI()); 101 | HttpResponse response = client.execute(httpGet); 102 | InputStream content = response.getEntity().getContent(); 103 | String line; 104 | BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 105 | System.err.println("****Printing the response***"); 106 | while ((line = reader.readLine()) != null) { 107 | System.err.println(line); 108 | } 109 | client.close(); 110 | } 111 | 112 | 113 | // static void foo() { 114 | // String dockerHost = String.format("tcp://%s:%d", CENTOS, 2375); 115 | // 116 | // DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() 117 | // .withRegistryUrl("https://hub.docker.com/") 118 | // .withDockerHost(dockerHost).build(); 119 | // 120 | // DockerClient dockerClient = DockerClientBuilder.getInstance(config) 121 | // // .withDockerCmdExecFactory(dockerCmdExecFactory) 122 | // .build(); 123 | // List images = dockerClient.listImagesCmd().exec(); 124 | // System.err.println("***Printing the images***"); 125 | // for (Image image : images) { 126 | // System.err.println("Image :" + image); 127 | // } 128 | // Info info = dockerClient.infoCmd().exec(); 129 | // System.err.println("**Info " + info); 130 | // dockerClient.pullImageCmd("https://hub.docker.com") 131 | // ExposedPort tcp22 = ExposedPort.tcp(4444); 132 | // Ports portBindings = new Ports(); 133 | // portBindings.bind(tcp22, Ports.Binding.bindPort(4444)); 134 | // CreateContainerResponse container = dockerClient.createContainerCmd("selenium/standalone-chrome") 135 | // 136 | // .withCmd("true") 137 | // .withExposedPorts(tcp22) 138 | // .withPortBindings(portBindings) 139 | // .withImage("selenium/standalone-chrome:3.0.1") 140 | // .exec(); 141 | // 142 | // dockerClient.startContainerCmd(container.getId()).exec(); 143 | // } 144 | } 145 | -------------------------------------------------------------------------------- /src/test/resources/just-ask.json: -------------------------------------------------------------------------------- 1 | { 2 | "dockerHost": "192.168.43.130", 3 | "dockerPort": "2375", 4 | "localhost": "0.0.0.0", 5 | "dockerImagePort": "4444", 6 | "maxSession": 5, 7 | "mapping": [ 8 | { 9 | "browser": "chrome", 10 | "target": "selenium/standalone-chrome:3.0.1", 11 | "implementation": "com.rationaleemotions.server.DockerBasedSeleniumServer" 12 | }, 13 | { 14 | "browser": "firefox", 15 | "target": "selenium/standalone-firefox:3.0.1", 16 | "implementation": "com.rationaleemotions.server.JvmBasedSeleniumServer" 17 | } 18 | ] 19 | } 20 | --------------------------------------------------------------------------------