├── .gitattributes ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── OSSMETADATA ├── README.md ├── build.gradle ├── codequality └── checkstyle.xml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images ├── Prana.png └── Prana_Small.png ├── sample_config.properties ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── netflix │ │ └── prana │ │ ├── Main.java │ │ ├── MainModule.java │ │ ├── config │ │ └── PranaConfig.java │ │ ├── http │ │ ├── Context.java │ │ └── api │ │ │ ├── AbstractRequestHandler.java │ │ │ ├── DynamicPropertiesHandler.java │ │ │ ├── HandlersModule.java │ │ │ ├── HealthCheckHandler.java │ │ │ ├── HostsHandler.java │ │ │ ├── NIWSCommand.java │ │ │ ├── PingHandler.java │ │ │ ├── ProxyHandler.java │ │ │ ├── SimpleRouter.java │ │ │ ├── StatusHandler.java │ │ │ ├── UnicastDisposableCachingSubject.java │ │ │ └── Utils.java │ │ ├── internal │ │ └── DefaultContext.java │ │ └── service │ │ ├── EurekaHostService.java │ │ ├── HostService.java │ │ └── ServiceModule.java └── resources │ ├── config.properties │ ├── log4j.properties │ └── prana.properties └── test └── java └── com └── netflix └── prana └── http └── api ├── AbstractIntegrationTest.java ├── DynamicPropertiesHandlerTest.java ├── HealthCheckHandlerTest.java ├── HostsHandlerTest.java ├── PingHandlerTest.java ├── StatusHandlerTest.java └── TestUtils.java /.gitattributes: -------------------------------------------------------------------------------- 1 | /gradlew text eol=lf 2 | /updateWrapper text eol=lf 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.jar 19 | *.rar 20 | *.tar 21 | *.zip 22 | 23 | # Logs and databases # 24 | ###################### 25 | *.log 26 | 27 | # OS generated files # 28 | ###################### 29 | .DS_Store* 30 | ehthumbs.db 31 | Icon? 32 | Thumbs.db 33 | 34 | # Editor Files # 35 | ################ 36 | *~ 37 | *.swp 38 | 39 | # Gradle Files # 40 | ################ 41 | .gradle 42 | 43 | # Build output directies 44 | /target 45 | */target 46 | /build 47 | */build 48 | 49 | # IntelliJ specific files/directories 50 | out 51 | .idea 52 | *.ipr 53 | *.iws 54 | *.iml 55 | atlassian-ide-plugin.xml 56 | 57 | # Eclipse specific files/directories 58 | .classpath 59 | .project 60 | .settings 61 | .metadata 62 | 63 | # NetBeans specific files/directories 64 | .nbattrs 65 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Netflix/Prana/11b3f80b69e8614a00a84b52e39c5ee6f97e5546/CHANGELOG.md -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012 Netflix, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /OSSMETADATA: -------------------------------------------------------------------------------- 1 | osslifecycle=archived 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 4 | 5 | [![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/Prana.svg)]() 6 | 7 | ![](images/Prana_Small.png?raw=true=150x150) 8 | 9 | 10 | **Prana** - Making it easy to integrate with NetflixOSS services. Prana exposes Java based client libraries of various services like Eureka, Ribbon, Archaius over HTTP. Prana makes it easy for applications—especially those written in Non-JVM languages—exist in the NetflixOSS eco-system. 11 | 12 | 13 | ## Build 14 | 15 | We use Gradle for building 16 | 17 | ``` 18 | ./gradlew build 19 | ``` 20 | 21 | We use the standard Gradle application plugin to build a deployable artifact of Prana 22 | 23 | ``` 24 | ./gradlew distZip 25 | ``` 26 | 27 | ## Documentation 28 | 29 | Please visit the [wiki] (https://github.com/Netflix/Prana/wiki) for detailed documentation. 30 | Please open a GitHub issue if you feel the current documentation is not clear or needs more explanation. 31 | 32 | ## Contributions 33 | 34 | Please use the [GitHub Issues] (https://github.com/netflix/Prana/issues) for requests. 35 | We actively welcome pull requests. 36 | 37 | ## License 38 | 39 | Copyright 2014 Netflix, Inc. 40 | 41 | Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 42 | 43 | ## Current state of this project 44 | 45 | The current implementation of this project is not used internally at Netflix and therefore updates to the open source have been slow. For more context, see http://ispyker.blogspot.com/2015/10/towards-being-better-about-open-source.html 46 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'nebula.netflixoss' version '2.2.10' 3 | } 4 | 5 | group = "com.netflix.prana" 6 | 7 | repositories { 8 | jcenter() 9 | } 10 | 11 | apply plugin: 'java' 12 | apply plugin: 'application' 13 | 14 | sourceCompatibility = '1.7' 15 | targetCompatibility = '1.7' 16 | 17 | dependencies { 18 | compile "org.slf4j:slf4j-api:${slf4j_version}" 19 | 20 | compile 'com.netflix.ribbon:ribbon:2.0-RC9' 21 | compile 'com.netflix.ribbon:ribbon-eureka:2.0-RC9' 22 | compile 'com.netflix.ribbon:ribbon-transport:2.0-RC9' 23 | compile 'com.netflix.karyon:karyon-governator:2.1.00-RC5' 24 | compile 'com.netflix.karyon:karyon-eureka:2.1.00-RC5' 25 | compile 'com.netflix.karyon:karyon-servo:2.1.00-RC5' 26 | compile 'com.netflix.karyon:karyon-archaius:2.1.00-RC5' 27 | compile 'com.netflix.karyon:karyon-admin-web:2.1.00-RC5' 28 | compile 'com.netflix.blitz4j:blitz4j:1.35' 29 | 30 | compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.3.3' 31 | compile 'com.fasterxml.jackson.core:jackson-core:2.3.3' 32 | compile 'com.fasterxml.jackson.core:jackson-databind:2.3.3' 33 | 34 | compile 'args4j:args4j:2.0.28' 35 | 36 | testCompile 'junit:junit:4.11' 37 | testCompile 'org.mockito:mockito-all:1.9.5' 38 | } 39 | 40 | test { 41 | testLogging { 42 | exceptionFormat = 'full' 43 | } 44 | } 45 | 46 | run { 47 | systemProperty 'eureka.validateInstanceId', 'false' 48 | systemProperty 'eureka.serviceUrl.default', 'http://localhost:8080/eureka/v2/' 49 | } 50 | 51 | mainClassName = "com.netflix.prana.Main" 52 | -------------------------------------------------------------------------------- /codequality/checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 21 | 22 | 23 | 24 | 25 | 26 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2014 Netflix, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | slf4j_version=1.7.6 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Netflix/Prana/11b3f80b69e8614a00a84b52e39c5ee6f97e5546/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Jan 21 14:40:34 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /images/Prana.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Netflix/Prana/11b3f80b69e8614a00a84b52e39c5ee6f97e5546/images/Prana.png -------------------------------------------------------------------------------- /images/Prana_Small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Netflix/Prana/11b3f80b69e8614a00a84b52e39c5ee6f97e5546/images/Prana_Small.png -------------------------------------------------------------------------------- /sample_config.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2014 Netflix, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | #################### 18 | # Prana Properties 19 | #################### 20 | # Ensure that this url is accessible locally and returns valid Prana healthcheck responses 21 | # Note that this is likely on the same port as eureka.port 22 | prana.host.healthcheck.url=http://localhost:5050/status 23 | # Timeout for calls to the healthcheck in ms 24 | prana.host.healthcheck.timeout=1500 25 | # List of accepted encodings for the Prana proxy 26 | prana.proxy.req.acceptencoding=gzip 27 | 28 | 29 | #################### 30 | # Eureka Service Registration Properties 31 | #################### 32 | # Change this to the application name for your side managed process 33 | eureka.name=MYSERVICE 34 | # Change this to the VIP address for you side managed process 35 | eureka.vipAddress=MYSERVICE 36 | # This is the port your want clients to connect to in your side managed process 37 | eureka.port=5050 38 | 39 | #################### 40 | # Eureka Connectivity Properties 41 | #################### 42 | # Change this to a working eureka-client configuration. For simplicity 43 | # this Prana example assumes a single eureka server 44 | eureka.serviceUrl.default=http://eurekaserverhostnameorip:8080/eureka 45 | # In Karyon 2.0, Erueka will assume DatacenterInfo (Amazon) and without the 46 | # below property, service registration will fail if you are running outside of 47 | # Amazon (for development). In Amazon, delete this property. 48 | eureka.validateInstanceId=false 49 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | rootProject.name='Prana' 18 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana; 17 | 18 | import com.google.inject.Injector; 19 | import com.netflix.config.ConfigurationManager; 20 | import com.netflix.config.DeploymentContext; 21 | import com.netflix.governator.guice.LifecycleInjector; 22 | import com.netflix.governator.lifecycle.LifecycleManager; 23 | import com.netflix.karyon.KaryonServer; 24 | import com.netflix.prana.config.PranaConfig; 25 | import com.netflix.prana.http.api.HandlersModule; 26 | import com.netflix.prana.service.ServiceModule; 27 | import org.kohsuke.args4j.CmdLineException; 28 | import org.kohsuke.args4j.CmdLineParser; 29 | import org.slf4j.Logger; 30 | import org.slf4j.LoggerFactory; 31 | 32 | import java.io.FileInputStream; 33 | import java.io.FileNotFoundException; 34 | import java.util.Properties; 35 | 36 | public class Main { 37 | 38 | private static Logger logger = LoggerFactory.getLogger(Main.class); 39 | 40 | public static void main(String[] args) { 41 | PranaConfig pranaConfig = new PranaConfig(); 42 | CmdLineParser cmdLineParser = new CmdLineParser(pranaConfig); 43 | try { 44 | cmdLineParser.parseArgument(args); 45 | } catch (CmdLineException e) { 46 | System.err.println(e.getMessage()); 47 | cmdLineParser.printUsage(System.err); 48 | System.exit(1); 49 | } 50 | 51 | 52 | try { 53 | MainModule sm = new MainModule(pranaConfig); 54 | try { 55 | FileInputStream fileInputStream = new FileInputStream(pranaConfig.getConfigFile()); 56 | Properties properties = new Properties(); 57 | properties.load(fileInputStream); 58 | ConfigurationManager.loadProperties(properties); 59 | } catch (FileNotFoundException fox) { 60 | logger.error(String.format("Config file %s is not present, loading default properties present in classpath", 61 | pranaConfig.getConfigFile())); 62 | } 63 | DeploymentContext deploymentContext = ConfigurationManager.getDeploymentContext(); 64 | deploymentContext.setApplicationId(pranaConfig.getAppName()); 65 | Injector injector = LifecycleInjector.builder().withModules(sm, new ServiceModule(), new HandlersModule()).build().createInjector(); 66 | LifecycleManager manager = injector.getInstance(LifecycleManager.class); 67 | manager.start(); 68 | 69 | KaryonServer karyonServer = injector.getInstance(KaryonServer.class); 70 | karyonServer.startAndWaitTillShutdown(); 71 | } catch (Exception e) { 72 | logger.error(e.getMessage()); 73 | System.exit(1); 74 | } 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/MainModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana; 17 | 18 | import com.google.inject.AbstractModule; 19 | import com.google.inject.Inject; 20 | import com.google.inject.Provides; 21 | import com.google.inject.Singleton; 22 | import com.netflix.adminresources.resources.KaryonWebAdminModule; 23 | import com.netflix.karyon.Karyon; 24 | import com.netflix.karyon.KaryonBootstrapSuite; 25 | import com.netflix.karyon.KaryonServer; 26 | import com.netflix.karyon.archaius.ArchaiusSuite; 27 | import com.netflix.karyon.eureka.KaryonEurekaModule; 28 | import com.netflix.prana.config.PranaConfig; 29 | import com.netflix.prana.http.api.SimpleRouter; 30 | 31 | public class MainModule extends AbstractModule { 32 | 33 | private PranaConfig config; 34 | 35 | public MainModule(PranaConfig config) { 36 | this.config = config; 37 | } 38 | 39 | @Override 40 | protected void configure() { 41 | } 42 | 43 | @Provides 44 | @Singleton 45 | @Inject 46 | public KaryonServer providesKaryonSever(SimpleRouter simpleRouter) { 47 | return Karyon.forRequestHandler(config.getHttpPort(), 48 | simpleRouter, 49 | new KaryonBootstrapSuite(), 50 | KaryonEurekaModule.asSuite(), 51 | KaryonWebAdminModule.asSuite(), 52 | new ArchaiusSuite(config.getAppName()) 53 | ); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/config/PranaConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.config; 17 | 18 | import org.kohsuke.args4j.Option; 19 | 20 | public class PranaConfig { 21 | 22 | @Option(name = "-p", aliases = "--http-port-api", usage = "Http Port of Prana Server") 23 | private int httpPort = 8078; 24 | 25 | @Option(name = "-a", aliases = "--app-name", usage = "Parent host application name") 26 | private String appName = "prana"; 27 | 28 | @Option(name = "-c", aliases = "--config", usage = "Prana configuration file") 29 | private String configFile = "prana.properties"; 30 | 31 | public int getHttpPort() { 32 | return httpPort; 33 | } 34 | 35 | public String getAppName() { 36 | return appName; 37 | } 38 | 39 | public String getConfigFile() { 40 | return configFile; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/Context.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.netflix.prana.http; 18 | 19 | import io.netty.handler.codec.http.HttpResponseStatus; 20 | import rx.Observable; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * A context is a collection of functions to aid in the request handling process 26 | */ 27 | public interface Context { 28 | 29 | /** 30 | * Serializes an object and writes the bytes to the response stream 31 | * 32 | * @param object response object 33 | */ 34 | Observable send(Object object); 35 | 36 | /** 37 | * Sends a simple text message back through the response stream 38 | * 39 | * @param message the message to deliver 40 | */ 41 | Observable sendSimple(String message); 42 | 43 | /** 44 | * Serializes a simple error message back to the response using the supplied status code 45 | * 46 | * @param status the status code for the response 47 | * @param message the message to send back to the caller 48 | */ 49 | Observable sendError(HttpResponseStatus status, String message); 50 | 51 | /** 52 | * Retrieves the value of the specified header 53 | * 54 | * @param name the name of the header to retrieve 55 | * @return the header value 56 | */ 57 | String getHeader(String name); 58 | 59 | /** 60 | * Sets the response header value 61 | * 62 | * @param name the header's name 63 | * @param value the value of the header 64 | */ 65 | void setHeader(String name, String value); 66 | 67 | /** 68 | * Convenience method for retrieving a query parameter off of the request 69 | * 70 | * @param key the query parameter 71 | * @return the query param value 72 | */ 73 | String getQueryParam(String key); 74 | 75 | /** 76 | * Convenience method for retrieving a query parameter off of the request that contains multiple values 77 | * 78 | * @param key the name of the query parameter 79 | * @return the list of values from the query parameter 80 | */ 81 | List getQueryParams(String key); 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/AbstractRequestHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.netflix.prana.http.api; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.netflix.prana.http.Context; 21 | import com.netflix.prana.internal.DefaultContext; 22 | import io.netty.buffer.ByteBuf; 23 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 24 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 25 | import io.reactivex.netty.protocol.http.server.RequestHandler; 26 | import rx.Observable; 27 | 28 | public abstract class AbstractRequestHandler implements RequestHandler { 29 | 30 | private final ObjectMapper objectMapper; 31 | 32 | protected AbstractRequestHandler(ObjectMapper objectMapper) { 33 | this.objectMapper = objectMapper; 34 | } 35 | 36 | abstract Observable handle(Context context); 37 | 38 | @Override 39 | public Observable handle(HttpServerRequest request, final HttpServerResponse response) { 40 | DefaultContext context = new DefaultContext(request, response, objectMapper); 41 | return handle(context); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/DynamicPropertiesHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.netflix.config.DynamicProperty; 20 | import com.netflix.prana.http.Context; 21 | import rx.Observable; 22 | 23 | import javax.inject.Inject; 24 | import java.util.HashMap; 25 | import java.util.List; 26 | import java.util.Map; 27 | 28 | /** 29 | * Created by dchoudhury on 10/20/14. 30 | */ 31 | public class DynamicPropertiesHandler extends AbstractRequestHandler { 32 | 33 | private static final String ID_QUERY_PARAMETER = "id"; 34 | 35 | @Inject 36 | public DynamicPropertiesHandler(ObjectMapper objectMapper) { 37 | super(objectMapper); 38 | } 39 | 40 | @Override 41 | Observable handle(Context context) { 42 | Map properties = new HashMap<>(); 43 | List ids = context.getQueryParams(ID_QUERY_PARAMETER); 44 | for (String id : ids) { 45 | String property = DynamicProperty.getInstance(id).getString(null); 46 | properties.put(id, property); 47 | } 48 | return context.send(properties); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/HandlersModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.google.inject.AbstractModule; 19 | import com.google.inject.Scopes; 20 | 21 | /** 22 | * Created by dchoudhury on 10/17/14. 23 | */ 24 | public class HandlersModule extends AbstractModule { 25 | 26 | @Override 27 | protected void configure() { 28 | bind(StatusHandler.class).in(Scopes.SINGLETON); 29 | bind(SimpleRouter.class).in(Scopes.SINGLETON); 30 | bind(ProxyHandler.class).in(Scopes.SINGLETON); 31 | bind(HealthCheckHandler.class).in(Scopes.SINGLETON); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/HealthCheckHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.google.common.base.Strings; 20 | import com.netflix.config.DynamicProperty; 21 | import com.netflix.prana.http.Context; 22 | import io.netty.buffer.ByteBuf; 23 | import io.netty.channel.ChannelOption; 24 | import io.netty.handler.codec.http.HttpResponseStatus; 25 | import io.reactivex.netty.RxNetty; 26 | import io.reactivex.netty.pipeline.PipelineConfigurators; 27 | import io.reactivex.netty.protocol.http.client.HttpClient; 28 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 29 | import io.reactivex.netty.protocol.http.client.HttpClientResponse; 30 | import rx.Observable; 31 | import rx.exceptions.OnErrorThrowable; 32 | import rx.functions.Func1; 33 | 34 | import javax.inject.Inject; 35 | import java.net.MalformedURLException; 36 | import java.net.URL; 37 | 38 | public class HealthCheckHandler extends AbstractRequestHandler { 39 | private static final String DEFAULT_CONTENT_TYPE = "application/xml"; 40 | private static final Observable DEFAULT_NOOP_RESPONSE = Observable.just(null); 41 | 42 | public static final int DEFAULT_APPLICATION_PORT = 7101; 43 | public static final int DEFAULT_CONNECTION_TIMEOUT = 2000; 44 | public static final String DEFAULT_HEALTHCHECK_ENDPOINT = "http://localhost:7001/healthcheck"; 45 | public static final String DEFAULT_OK_HEALTH = "ok"; 46 | public static final String DEFAULT_FAIL_HEALTH = "fail"; 47 | 48 | 49 | @Inject 50 | public HealthCheckHandler(ObjectMapper objectMapper) { 51 | super(objectMapper); 52 | } 53 | 54 | @Override 55 | Observable handle(final Context context) { 56 | String externalHealthCheckURL = DynamicProperty.getInstance("prana.host.healthcheck.url") 57 | .getString(DEFAULT_HEALTHCHECK_ENDPOINT); 58 | context.setHeader("Content-type", DEFAULT_CONTENT_TYPE); 59 | if (Strings.isNullOrEmpty(externalHealthCheckURL)) { 60 | return context.sendSimple(DEFAULT_OK_HEALTH); 61 | } else { 62 | return getResponse(externalHealthCheckURL).flatMap(new Func1, Observable>() { 63 | @Override 64 | public Observable call(HttpClientResponse response) { 65 | if (response.getStatus().code() == HttpResponseStatus.OK.code()) { 66 | context.sendSimple(DEFAULT_OK_HEALTH); 67 | } else { 68 | context.sendError(HttpResponseStatus.SERVICE_UNAVAILABLE, DEFAULT_FAIL_HEALTH); 69 | } 70 | return DEFAULT_NOOP_RESPONSE; 71 | } 72 | }).onErrorFlatMap(new Func1>() { 73 | @Override 74 | public Observable call(OnErrorThrowable onErrorThrowable) { 75 | context.sendError(HttpResponseStatus.SERVICE_UNAVAILABLE, DEFAULT_FAIL_HEALTH); 76 | return DEFAULT_NOOP_RESPONSE; 77 | } 78 | }); 79 | } 80 | } 81 | 82 | private Observable> getResponse(String externalHealthCheckURL) { 83 | String host = "localhost"; 84 | int port = DEFAULT_APPLICATION_PORT; 85 | String path = "/healthcheck"; 86 | try { 87 | URL url = new URL(externalHealthCheckURL); 88 | host = url.getHost(); 89 | port = url.getPort(); 90 | path = url.getPath(); 91 | } catch (MalformedURLException e) { 92 | //continue 93 | } 94 | Integer timeout = DynamicProperty.getInstance("prana.host.healthcheck.timeout").getInteger(DEFAULT_CONNECTION_TIMEOUT); 95 | HttpClient httpClient = RxNetty.newHttpClientBuilder(host, port) 96 | .pipelineConfigurator(PipelineConfigurators.httpClientConfigurator()) 97 | .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout) 98 | .build(); 99 | return httpClient.submit(HttpClientRequest.createGet(path)); 100 | 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/HostsHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.google.common.base.Strings; 20 | import com.google.inject.Inject; 21 | import com.netflix.appinfo.InstanceInfo; 22 | import com.netflix.prana.http.Context; 23 | import com.netflix.prana.service.HostService; 24 | import io.netty.handler.codec.http.HttpResponseStatus; 25 | import rx.Observable; 26 | 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | import static com.netflix.appinfo.InstanceInfo.InstanceStatus; 31 | 32 | /** 33 | * Created by dchoudhury on 10/20/14. 34 | */ 35 | public class HostsHandler extends AbstractRequestHandler { 36 | 37 | private final HostService hostService; 38 | 39 | @Inject 40 | public HostsHandler(HostService hostService, ObjectMapper objectMapper) { 41 | super(objectMapper); 42 | this.hostService = hostService; 43 | } 44 | 45 | @Override 46 | Observable handle(Context context) { 47 | String appName = context.getQueryParam("appName"); 48 | String vip = context.getQueryParam("vip"); 49 | if (Strings.isNullOrEmpty(appName)) { 50 | return context.sendError(HttpResponseStatus.BAD_REQUEST, "appName has to be specified"); 51 | } else { 52 | List instances = hostService.getHosts(appName); 53 | List hosts = new ArrayList<>(); 54 | for (InstanceInfo instanceInfo : instances) { 55 | if (vip != null && !instanceInfo.getVIPAddress().contains(vip) && instanceInfo.getStatus().equals(InstanceStatus.UP)) { 56 | continue; 57 | } 58 | hosts.add(instanceInfo.getHostName()); 59 | } 60 | return context.send(hosts); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/NIWSCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.netflix.hystrix.HystrixCommandProperties; 19 | import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; 20 | import com.netflix.hystrix.HystrixCommandGroupKey; 21 | import com.netflix.hystrix.HystrixCommandKey; 22 | import com.netflix.hystrix.HystrixObservableCommand; 23 | import io.netty.buffer.ByteBuf; 24 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 25 | import io.reactivex.netty.protocol.http.client.HttpClientResponse; 26 | import rx.Observable; 27 | 28 | public class NIWSCommand extends HystrixObservableCommand> { 29 | 30 | private final LoadBalancingHttpClient httpClient; 31 | 32 | private final HttpClientRequest req; 33 | 34 | protected NIWSCommand(LoadBalancingHttpClient httpClient, HttpClientRequest req, 35 | HystrixCommandKey key) { 36 | super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("prana")).andCommandKey(key). 37 | andCommandPropertiesDefaults(HystrixCommandProperties.Setter(). 38 | withExecutionIsolationThreadTimeoutInMilliseconds(10000). 39 | withRequestCacheEnabled(false). 40 | withExecutionIsolationSemaphoreMaxConcurrentRequests(1000). 41 | withCircuitBreakerEnabled(false))); 42 | 43 | this.httpClient = httpClient; 44 | this.req = req; 45 | } 46 | 47 | @Override 48 | protected Observable> run() { 49 | return httpClient.submit(req); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/PingHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.netflix.prana.http.Context; 20 | import rx.Observable; 21 | 22 | import javax.inject.Inject; 23 | 24 | public class PingHandler extends AbstractRequestHandler { 25 | 26 | private static final String CACHE_CONTROL_HEADER = "Cache-Control"; 27 | private static final String CACHE_CONTROL_HEADER_VAL = "must-revalidate,no-cache,no-store"; 28 | private static final String DEFAULT_PONG_RESPONSE = "pong"; 29 | 30 | @Inject 31 | public PingHandler(ObjectMapper objectMapper) { 32 | super(objectMapper); 33 | } 34 | 35 | @Override 36 | Observable handle(Context context) { 37 | context.setHeader(CACHE_CONTROL_HEADER, CACHE_CONTROL_HEADER_VAL); 38 | return context.sendSimple(DEFAULT_PONG_RESPONSE); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/ProxyHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.google.common.base.Strings; 19 | import com.netflix.client.config.IClientConfig; 20 | import com.netflix.client.config.IClientConfigKey; 21 | import com.netflix.config.DynamicProperty; 22 | import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; 23 | import com.netflix.ribbon.transport.netty.RibbonTransport; 24 | import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; 25 | import io.netty.buffer.ByteBuf; 26 | import io.reactivex.netty.protocol.http.client.HttpClientPipelineConfigurator; 27 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 28 | import io.reactivex.netty.protocol.http.client.HttpClientResponse; 29 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 30 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 31 | import io.reactivex.netty.protocol.http.server.RequestHandler; 32 | import org.slf4j.Logger; 33 | import org.slf4j.LoggerFactory; 34 | import rx.Observable; 35 | import rx.functions.Action0; 36 | import rx.functions.Action1; 37 | import rx.functions.Func1; 38 | 39 | import java.util.List; 40 | import java.util.Map; 41 | import java.util.Set; 42 | import java.util.concurrent.ConcurrentHashMap; 43 | 44 | public class ProxyHandler implements RequestHandler { 45 | 46 | private static final ConcurrentHashMap> httpClients = new ConcurrentHashMap<>(); 47 | 48 | private final String PROXY_REQ_ACCEPT_ENCODING = DynamicProperty.getInstance("prana.proxy.req.acceptencoding").getString("deflate, gzip"); 49 | 50 | private Logger logger = LoggerFactory.getLogger(getClass().getName()); 51 | 52 | private final String ERROR_RESPONSE = "500Error forwarding request to origin"; 53 | 54 | 55 | @Override 56 | public Observable handle(final HttpServerRequest serverRequest, final HttpServerResponse serverResponse) { 57 | String vip = Utils.forQueryParam(serverRequest.getQueryParameters(), "vip"); 58 | String path = Utils.forQueryParam(serverRequest.getQueryParameters(), "path"); 59 | if (Strings.isNullOrEmpty(vip)) { 60 | serverResponse.getHeaders().set("Content-Type", "application/xml"); 61 | serverResponse.writeString(ERROR_RESPONSE); 62 | logger.error("VIP is empty"); 63 | return serverResponse.close(); 64 | } 65 | 66 | if (path == null) { 67 | path = ""; 68 | } 69 | 70 | final LoadBalancingHttpClient client = getClient(vip); 71 | final HttpClientRequest req = HttpClientRequest.create(serverRequest.getHttpMethod(), path); 72 | populateRequestHeaders(serverRequest, req); 73 | 74 | final UnicastDisposableCachingSubject cachedContent = UnicastDisposableCachingSubject.create(); 75 | /** 76 | * Why do we retain here? 77 | * After the onNext on the content returns, RxNetty releases the sent ByteBuf. This ByteBuf is kept out of 78 | * the scope of the onNext for consumption of the client in the route. The client when eventually writes 79 | * this ByteBuf over the wire expects the ByteBuf to be usable (i.e. ref count => 1). If this retain() call 80 | * is removed, the ref count will be 0 after the onNext on the content returns and hence it will be unusable 81 | * by the client in the route. 82 | */ 83 | serverRequest.getContent().map(new Func1() { 84 | @Override 85 | public ByteBuf call(ByteBuf byteBuf) { 86 | return byteBuf.retain(); 87 | } 88 | }).subscribe(cachedContent); // Caches data if arrived before client writes it out, else passes through 89 | 90 | req.withContentSource(cachedContent); 91 | 92 | return client.submit(req).flatMap(new Func1, Observable>() { 93 | @Override 94 | public Observable call(final HttpClientResponse response) { 95 | serverResponse.setStatus(response.getStatus()); 96 | List> headers = response.getHeaders().entries(); 97 | for (Map.Entry header : headers) { 98 | serverResponse.getHeaders().add(header.getKey(), header.getValue()); 99 | } 100 | return response.getContent().map(new Func1() { 101 | @Override 102 | public ByteBuf call(ByteBuf byteBuf) { 103 | return byteBuf.retain(); 104 | } 105 | }).map(new Func1() { 106 | @Override 107 | public Void call(ByteBuf byteBuf) { 108 | serverResponse.write(byteBuf); 109 | return null; 110 | } 111 | }); 112 | } 113 | }).onErrorResumeNext(new Func1>() { 114 | @Override 115 | public Observable call(Throwable throwable) { 116 | serverResponse.getHeaders().set("Content-Type", "application/xml"); 117 | serverResponse.writeString(ERROR_RESPONSE); 118 | return Observable.just(null); 119 | } 120 | }).doOnCompleted(new Action0() { 121 | @Override 122 | public void call() { 123 | serverResponse.close(); 124 | cachedContent.dispose(new Action1() { 125 | @Override 126 | public void call(ByteBuf byteBuf) { 127 | /** 128 | * Why do we release here? 129 | * 130 | * All ByteBuf which were never consumed are disposed and sent here. This means that the 131 | * client in the route never consumed this ByteBuf. Before sending this ByteBuf to the 132 | * content subject, we do a retain (see above for reason) expecting the client in the route 133 | * to release it when written over the wire. In this case, though, the client never consumed 134 | * it and hence never released corresponding to the retain done by us. 135 | */ 136 | if (byteBuf.refCnt() > 1) { // 1 refCount will be from the subject putting into the cache. 137 | byteBuf.release(); 138 | } 139 | } 140 | }); 141 | } 142 | }); 143 | } 144 | 145 | private void populateRequestHeaders(HttpServerRequest serverRequest, HttpClientRequest request) { 146 | Set headerNames = serverRequest.getHeaders().names(); 147 | for (String name : headerNames) { 148 | if (name.contains("content-length")) { 149 | continue; 150 | } 151 | request.getHeaders().add(name, serverRequest.getHeaders().getHeader(name)); 152 | } 153 | // Normally always request gzipped from the server. But can be overridden with a Dynamic Property. 154 | if (PROXY_REQ_ACCEPT_ENCODING != null && PROXY_REQ_ACCEPT_ENCODING.length() > 0) { 155 | request.getHeaders().addHeader("accept-encoding", PROXY_REQ_ACCEPT_ENCODING); 156 | } 157 | //TODO Write X-Forwarded-Host, X-Forwarded-Port, X-Forwarded-Proto, X-Forwarded-For in the headers 158 | } 159 | 160 | private LoadBalancingHttpClient getClient(String vip) { 161 | LoadBalancingHttpClient client = httpClients.get(vip); 162 | if (client == null) { 163 | IClientConfig config = IClientConfig.Builder.newBuilder("prana_backend"). 164 | withDefaultValues(). 165 | withDeploymentContextBasedVipAddresses(vip). 166 | build(). 167 | set(IClientConfigKey.Keys.MaxTotalConnections, 2000). 168 | set(IClientConfigKey.Keys.MaxConnectionsPerHost, 2000). 169 | set(IClientConfigKey.Keys.OkToRetryOnAllOperations, false). 170 | set(IClientConfigKey.Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); 171 | 172 | client = RibbonTransport.newHttpClient(new HttpClientPipelineConfigurator(), config); 173 | httpClients.putIfAbsent(vip, client); 174 | 175 | } 176 | return client; 177 | } 178 | 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/SimpleRouter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.google.inject.Inject; 19 | import com.netflix.karyon.transport.http.SimpleUriRouter; 20 | import io.netty.buffer.ByteBuf; 21 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 22 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 23 | import io.reactivex.netty.protocol.http.server.RequestHandler; 24 | import rx.Observable; 25 | 26 | /** 27 | * Created by dchoudhury on 10/20/14. 28 | */ 29 | public class SimpleRouter implements RequestHandler { 30 | 31 | private final SimpleUriRouter delegate; 32 | 33 | @Inject 34 | public SimpleRouter(ProxyHandler proxyHandler, HealthCheckHandler healthCheckHandler, HostsHandler hostsHandler, 35 | PingHandler pingHandler, DynamicPropertiesHandler dynamicPropertiesHandler, StatusHandler statusHandler) { 36 | delegate = new SimpleUriRouter<>(); 37 | delegate.addUri("/healthcheck", healthCheckHandler) 38 | .addUri("/dynamicproperties", dynamicPropertiesHandler) 39 | .addUri("/proxy", proxyHandler) 40 | .addUri("/eureka/hosts", hostsHandler) 41 | .addUri("/ping", pingHandler) 42 | .addUri("/status", statusHandler); 43 | } 44 | 45 | @Override 46 | public Observable handle(HttpServerRequest request, HttpServerResponse response) { 47 | return delegate.handle(request, response); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/StatusHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.netflix.prana.http.api; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.netflix.appinfo.ApplicationInfoManager; 21 | import com.netflix.prana.http.Context; 22 | import rx.Observable; 23 | 24 | import javax.inject.Inject; 25 | import java.util.HashMap; 26 | import java.util.Map; 27 | 28 | /** 29 | * A request handler to return the application's status in Discovery 30 | */ 31 | public class StatusHandler extends AbstractRequestHandler { 32 | 33 | private final ApplicationInfoManager applicationInfoManager; 34 | 35 | @Inject 36 | public StatusHandler(ObjectMapper objectMapper, ApplicationInfoManager applicationInfoManager) { 37 | super(objectMapper); 38 | this.applicationInfoManager = applicationInfoManager; 39 | } 40 | 41 | @Override 42 | Observable handle(Context context) { 43 | Map status = new HashMap() {{ 44 | put("status", applicationInfoManager.getInfo().getStatus().name()); 45 | }}; 46 | return context.send(status); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/UnicastDisposableCachingSubject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import io.netty.util.ReferenceCountUtil; 19 | import io.netty.util.ReferenceCounted; 20 | import rx.Observer; 21 | import rx.Subscriber; 22 | import rx.functions.Action0; 23 | import rx.functions.Action1; 24 | import rx.internal.operators.NotificationLite; 25 | import rx.observers.Subscribers; 26 | import rx.subjects.Subject; 27 | import rx.subscriptions.Subscriptions; 28 | 29 | import java.util.concurrent.ConcurrentLinkedQueue; 30 | import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; 31 | import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; 32 | 33 | /** 34 | * A {@link rx.subjects.Subject} implementation for caching {@link io.netty.util.ReferenceCounted} objects which can be disposed if not sent to 35 | * the sole subscriber of this subject. 36 | * 37 | * @author Nitesh Kant 38 | */ 39 | final class UnicastDisposableCachingSubject extends Subject { 40 | 41 | private final State state; 42 | 43 | private UnicastDisposableCachingSubject(State state) { 44 | super(new OnSubscribeAction<>(state)); 45 | this.state = state; 46 | } 47 | 48 | public static UnicastDisposableCachingSubject create() { 49 | State state = new State<>(); 50 | return new UnicastDisposableCachingSubject<>(state); 51 | } 52 | 53 | /** 54 | * Disposes the items held by this subject which were not given out to the lone subscriber. 55 | * 56 | * @param disposedElementsProcessor All elements that were disposed are passed to this processor. 57 | */ 58 | public void dispose(Action1 disposedElementsProcessor) { 59 | if (state.casState(State.STATES.UNSUBSCRIBED, State.STATES.DISPOSED)) { 60 | _dispose(disposedElementsProcessor); 61 | } else if (state.casState(State.STATES.SUBSCRIBED, State.STATES.DISPOSED)) { 62 | state.observerRef.onCompleted(); // Complete the existing subscription in case it is still not unsubscribed. 63 | _dispose(disposedElementsProcessor); 64 | } 65 | } 66 | 67 | private void _dispose(Action1 disposedElementsProcessor) { 68 | Subscriber noOpSub = new PassThruObserver<>(Subscribers.create(disposedElementsProcessor, 69 | new Action1() { 70 | @Override 71 | public void call(Throwable throwable) { 72 | 73 | } 74 | }), 75 | state); // Any buffering post buffer draining must not be lying in the buffer 76 | state.buffer.sendAllNotifications(noOpSub); // It is important to empty the buffer before setting the observer. 77 | // If not done, there can be two threads draining the buffer 78 | // (PassThroughObserver on any notification) and this thread. 79 | state.setObserverRef(noOpSub); // All future notifications are not sent anywhere. 80 | } 81 | 82 | /** 83 | * The common state. 84 | */ 85 | private static final class State { 86 | 87 | /** 88 | * Following are the only possible state transitions: 89 | * UNSUBSCRIBED -> SUBSCRIBED 90 | * UNSUBSCRIBED -> DISPOSED 91 | */ 92 | private enum STATES { 93 | UNSUBSCRIBED /*Initial*/, SUBSCRIBED /*Terminal state*/, DISPOSED/*Terminal state*/ 94 | } 95 | 96 | private volatile int state = STATES.UNSUBSCRIBED.ordinal(); /*Values are the ordinals of STATES enum*/ 97 | 98 | /** 99 | * Following Observers are associated with the states: 100 | * UNSUBSCRIBED => {@link BufferedObserver} 101 | * SUBSCRIBED => {@link PassThruObserver} 102 | * DISPOSED => {@link Subscribers#empty()} 103 | */ 104 | private volatile Observer observerRef = new BufferedObserver(); 105 | 106 | /** 107 | * The only buffer associated with this state. All notifications go to this buffer if no one has subscribed and 108 | * the {@link UnicastDisposableCachingSubject} instance is not disposed. 109 | */ 110 | private final ByteBufAwareBuffer buffer = new ByteBufAwareBuffer<>(); 111 | 112 | /** 113 | * Field updater for observerRef. 114 | */ 115 | @SuppressWarnings("rawtypes") 116 | private static final AtomicReferenceFieldUpdater OBSERVER_UPDATER 117 | = AtomicReferenceFieldUpdater.newUpdater(State.class, Observer.class, "observerRef"); 118 | 119 | /** 120 | * Field updater for state. 121 | */ 122 | @SuppressWarnings("rawtypes") 123 | private static final AtomicIntegerFieldUpdater STATE_UPDATER 124 | = AtomicIntegerFieldUpdater.newUpdater(State.class, "state"); 125 | 126 | public boolean casState(STATES expected, STATES next) { 127 | return STATE_UPDATER.compareAndSet(this, expected.ordinal(), next.ordinal()); 128 | } 129 | 130 | public void setObserverRef(Observer o) { // Guarded by casState() 131 | observerRef = o; 132 | } 133 | 134 | public boolean casObserverRef(Observer expected, Observer next) { 135 | return OBSERVER_UPDATER.compareAndSet(this, expected, next); 136 | } 137 | 138 | /** 139 | * The default subscriber when the enclosing state is created. 140 | */ 141 | private final class BufferedObserver extends Subscriber { 142 | 143 | private final NotificationLite nl = NotificationLite.instance(); 144 | 145 | @Override 146 | public void onCompleted() { 147 | buffer.add(nl.completed()); 148 | } 149 | 150 | @Override 151 | public void onError(Throwable e) { 152 | buffer.add(nl.error(e)); 153 | } 154 | 155 | @Override 156 | public void onNext(T t) { 157 | buffer.add(nl.next(t)); 158 | } 159 | } 160 | } 161 | 162 | private static final class OnSubscribeAction implements OnSubscribe { 163 | 164 | private final State state; 165 | 166 | public OnSubscribeAction(State state) { 167 | this.state = state; 168 | } 169 | 170 | @Override 171 | public void call(final Subscriber subscriber) { 172 | if (state.casState(State.STATES.UNSUBSCRIBED, State.STATES.SUBSCRIBED)) { 173 | 174 | // drain queued notifications before subscription 175 | // we do this here before PassThruObserver so the consuming thread can do this before putting itself in 176 | // the line of the producer 177 | state.buffer.sendAllNotifications(subscriber); 178 | 179 | // register real observer for pass-thru ... and drain any further events received on first notification 180 | state.setObserverRef(new PassThruObserver<>(subscriber, state)); 181 | subscriber.add(Subscriptions.create(new Action0() { 182 | @Override 183 | public void call() { 184 | state.setObserverRef(Subscribers.empty()); 185 | } 186 | })); 187 | } else if (State.STATES.SUBSCRIBED.ordinal() == state.state) { 188 | subscriber.onError(new IllegalStateException("Content can only have one subscription. Use Observable.publish() if you want to multicast.")); 189 | } else if (State.STATES.DISPOSED.ordinal() == state.state) { 190 | subscriber.onError(new IllegalStateException("Content stream is already disposed.")); 191 | } 192 | } 193 | 194 | } 195 | 196 | @Override 197 | public void onCompleted() { 198 | state.observerRef.onCompleted(); 199 | } 200 | 201 | @Override 202 | public void onError(Throwable e) { 203 | state.observerRef.onError(e); 204 | } 205 | 206 | @Override 207 | public void onNext(T t) { 208 | state.observerRef.onNext(t); 209 | } 210 | 211 | /** 212 | * This is a temporary observer between buffering and the actual that gets into the line of notifications 213 | * from the producer and will drain the queue of any items received during the race of the initial drain and 214 | * switching this. 215 | *

216 | * It will then immediately swap itself out for the actual (after a single notification), but since this is 217 | * now being done on the same producer thread no further buffering will occur. 218 | */ 219 | private static final class PassThruObserver extends Subscriber { 220 | 221 | private final Observer actual; 222 | // this assumes single threaded synchronous notifications (the Rx contract for a single Observer) 223 | private final ByteBufAwareBuffer buffer; // Same buffer instance from the original BufferedObserver. 224 | private final State state; 225 | 226 | PassThruObserver(Observer actual, State state) { 227 | this.actual = actual; 228 | buffer = state.buffer; 229 | this.state = state; 230 | } 231 | 232 | @Override 233 | public void onCompleted() { 234 | drainIfNeededAndSwitchToActual(); 235 | actual.onCompleted(); 236 | } 237 | 238 | @Override 239 | public void onError(Throwable e) { 240 | drainIfNeededAndSwitchToActual(); 241 | actual.onError(e); 242 | } 243 | 244 | @Override 245 | public void onNext(T t) { 246 | drainIfNeededAndSwitchToActual(); 247 | actual.onNext(t); 248 | } 249 | 250 | private void drainIfNeededAndSwitchToActual() { 251 | buffer.sendAllNotifications(this); 252 | // now we can safely change over to the actual and get rid of the pass-thru 253 | // but only if not unsubscribed 254 | state.casObserverRef(this, actual); 255 | } 256 | } 257 | 258 | private static final class ByteBufAwareBuffer { 259 | 260 | private final ConcurrentLinkedQueue actual = new ConcurrentLinkedQueue<>(); 261 | private final NotificationLite nl = NotificationLite.instance(); 262 | 263 | private void add(Object toAdd) { 264 | ReferenceCountUtil.retain(toAdd); // Released when the notification is sent. 265 | actual.add(toAdd); 266 | } 267 | 268 | public void sendAllNotifications(Subscriber subscriber) { 269 | Object notification; // Can be onComplete notification, onError notification or just the actual "T". 270 | while ((notification = actual.poll()) != null) { 271 | try { 272 | nl.accept(subscriber, notification); 273 | } finally { 274 | ReferenceCountUtil.release(notification); // If it is the actual T for onNext and is a ByteBuf, it will be released. 275 | } 276 | } 277 | } 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/http/api/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | public class Utils { 22 | 23 | public static String forQueryParam(Map> queryParams, String paramName) { 24 | List values = queryParams.get(paramName); 25 | if (values != null) { 26 | return values.get(0); 27 | } 28 | return null; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/internal/DefaultContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.netflix.prana.internal; 18 | 19 | import com.fasterxml.jackson.core.JsonProcessingException; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.netflix.prana.http.Context; 22 | import io.netty.buffer.ByteBuf; 23 | import io.netty.handler.codec.http.HttpResponseStatus; 24 | import io.reactivex.netty.protocol.http.server.HttpRequestHeaders; 25 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 26 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 27 | import rx.Observable; 28 | 29 | import javax.ws.rs.core.MediaType; 30 | import java.util.ArrayList; 31 | import java.util.HashMap; 32 | import java.util.List; 33 | import java.util.Map; 34 | 35 | public class DefaultContext implements Context { 36 | private static final String ULTIMATE_FAILURE_STRING = "no content"; 37 | 38 | private final HttpServerResponse response; 39 | private final HttpRequestHeaders requestHeaders; 40 | private final Map> queryParameters; 41 | private final ObjectMapper objectMapper; 42 | 43 | public DefaultContext(HttpServerRequest request, HttpServerResponse response, ObjectMapper objectMapper) { 44 | this.response = response; 45 | this.requestHeaders = request.getHeaders(); 46 | this.queryParameters = request.getQueryParameters(); 47 | this.objectMapper = objectMapper; 48 | } 49 | 50 | @Override 51 | public String getHeader(String name) { 52 | return requestHeaders.getHeader(name); 53 | } 54 | 55 | @Override 56 | public void setHeader(String name, String value) { 57 | response.getHeaders().setHeader(name, value); 58 | } 59 | 60 | @Override 61 | public String getQueryParam(String key) { 62 | List param = queryParameters.get(key); 63 | return (param != null && param.size() > 0) ? param.get(0) : null; 64 | } 65 | 66 | @Override 67 | public List getQueryParams(String key) { 68 | List param = queryParameters.get(key); 69 | return (param != null && param.size() > 0) ? param : new ArrayList(); 70 | } 71 | 72 | @Override 73 | public Observable send(Object object) { 74 | return sendJson(object); 75 | } 76 | 77 | @Override 78 | public Observable sendSimple(String message) { 79 | setOk(); 80 | response.writeString(message); 81 | return response.close(); 82 | } 83 | 84 | @Override 85 | public Observable sendError(final HttpResponseStatus status, final String message) { 86 | Map messageObject = new HashMap() {{ 87 | put("reason", status.reasonPhrase()); 88 | put("message", message); 89 | }}; 90 | 91 | return sendJson(messageObject); 92 | } 93 | 94 | private void setOk() { 95 | response.setStatus(HttpResponseStatus.OK); 96 | } 97 | 98 | private Observable sendJson(Object object) { 99 | byte[] bytes = new byte[0]; 100 | try { 101 | setOk(); 102 | bytes = objectMapper.writeValueAsBytes(object); 103 | response.getHeaders().setHeader("Content-type", MediaType.APPLICATION_JSON); 104 | } catch (JsonProcessingException e) { 105 | response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); 106 | try { 107 | bytes = objectMapper.writeValueAsBytes(e); 108 | } catch (JsonProcessingException e1) { 109 | // we can't really do much at this point. 110 | } 111 | } 112 | if (bytes.length > 0) { 113 | response.writeBytes(bytes); 114 | } else { 115 | response.writeString(ULTIMATE_FAILURE_STRING); 116 | } 117 | return response.close(); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/service/EurekaHostService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.service; 17 | 18 | import com.google.inject.Inject; 19 | import com.netflix.appinfo.InstanceInfo; 20 | import com.netflix.discovery.DiscoveryClient; 21 | 22 | import java.util.List; 23 | 24 | public class EurekaHostService implements HostService { 25 | 26 | private DiscoveryClient discoveryClient; 27 | 28 | @Inject 29 | public EurekaHostService(DiscoveryClient discoveryClient) { 30 | this.discoveryClient = discoveryClient; 31 | } 32 | 33 | @Override 34 | public List getHosts(String appName) { 35 | return discoveryClient.getApplication(appName).getInstances(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/service/HostService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.service; 17 | 18 | import com.netflix.appinfo.InstanceInfo; 19 | 20 | import java.util.List; 21 | 22 | public interface HostService { 23 | 24 | List getHosts(String appName); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/netflix/prana/service/ServiceModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.service; 17 | 18 | import com.google.inject.AbstractModule; 19 | import com.google.inject.Scopes; 20 | 21 | public class ServiceModule extends AbstractModule { 22 | @Override 23 | protected void configure() { 24 | bind(HostService.class).to(EurekaHostService.class).in(Scopes.SINGLETON); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/resources/config.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2014 Netflix, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | archaius.deployment.applicationId=prana 18 | archaius.deployment.environment=dev 19 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2014 Netflix, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | log4j.rootLogger=INFO,stdout,R 18 | 19 | # stdout 20 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 21 | log4j.appender.stdout.layout=com.netflix.logging.log4jAdapter.NFPatternLayout 22 | log4j.appender.stdout.layout.ConversionPattern=%5p %d{HH:mm:ss,SSS} %m%n 23 | 24 | # rolling log file 25 | log4j.appender.R=org.apache.log4j.RollingFileAppender 26 | log4j.appender.R.maxFileSize=20MB 27 | log4j.appender.R.maxBackupIndex=50 28 | log4j.appender.R.layout=com.netflix.logging.log4jAdapter.NFPatternLayout 29 | log4j.appender.R.layout.ConversionPattern=%5p [%t] %d{ISO8601} %F (line %L) %m%n 30 | log4j.appender.R.File=logs/prana.log 31 | 32 | # convert to async appender 33 | log4j.logger.asyncAppenders=INFO,stdout,R 34 | batcher.com.netflix.logging.AsyncAppender.stdout.waitTimeinMillis=120000 -------------------------------------------------------------------------------- /src/main/resources/prana.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2014 Netflix, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | eureka.validateInstanceId=false 18 | eureka.name=prana 19 | eureka.port=8080 20 | eureka.vipAddress=prana 21 | eureka.serviceUrl.default=http://localhost:8080/eureka/v2/ -------------------------------------------------------------------------------- /src/test/java/com/netflix/prana/http/api/AbstractIntegrationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.netflix.prana.http.api; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import io.netty.buffer.ByteBuf; 21 | import io.netty.channel.ChannelOption; 22 | import io.reactivex.netty.RxNetty; 23 | import io.reactivex.netty.pipeline.PipelineConfigurators; 24 | import io.reactivex.netty.protocol.http.client.HttpClient; 25 | import io.reactivex.netty.protocol.http.server.HttpServer; 26 | import io.reactivex.netty.protocol.http.server.RequestHandler; 27 | import org.junit.After; 28 | import org.junit.Before; 29 | 30 | public abstract class AbstractIntegrationTest { 31 | protected ObjectMapper objectMapper = new ObjectMapper(); 32 | protected HttpServer server; 33 | protected HttpClient client; 34 | 35 | protected abstract RequestHandler getHandler(); 36 | 37 | @Before 38 | public void setUp() { 39 | server = RxNetty.newHttpServerBuilder(0, getHandler()) 40 | .pipelineConfigurator(PipelineConfigurators.httpServerConfigurator()).build(); 41 | server.start(); 42 | client = RxNetty.newHttpClientBuilder("localhost", server.getServerPort()) 43 | .pipelineConfigurator(PipelineConfigurators.httpClientConfigurator()) 44 | .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000) 45 | .build(); 46 | 47 | } 48 | 49 | @After 50 | public void tearDown() throws InterruptedException { 51 | server.shutdown(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/prana/http/api/DynamicPropertiesHandlerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.netflix.config.ConfigurationManager; 19 | import io.netty.buffer.ByteBuf; 20 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 21 | import io.reactivex.netty.protocol.http.server.RequestHandler; 22 | import org.junit.Test; 23 | 24 | import static org.junit.Assert.assertEquals; 25 | import static org.junit.Assert.assertTrue; 26 | 27 | public class DynamicPropertiesHandlerTest extends AbstractIntegrationTest { 28 | 29 | @Test 30 | public void shouldReturnListOfProperties() { 31 | ConfigurationManager.getConfigInstance().setProperty("foo", "bar"); 32 | ConfigurationManager.getConfigInstance().setProperty("lol", 10); 33 | HttpClientRequest request = HttpClientRequest.createGet("/dynamicproperties?id=foo&id=lol"); 34 | String response = TestUtils.getResponse(request, client); 35 | assertTrue(response.contains("\"lol\":\"10\"")); 36 | assertTrue(response.contains("\"foo\":\"bar\"")); 37 | } 38 | 39 | 40 | @Test 41 | public void shouldReturnNullForUnknownProperties() { 42 | HttpClientRequest request = HttpClientRequest.createGet("/dynamicproperties?id=bar"); 43 | assertEquals("{\"bar\":null}", TestUtils.getResponse(request, client)); 44 | 45 | } 46 | 47 | @Override 48 | protected RequestHandler getHandler() { 49 | return new DynamicPropertiesHandler(objectMapper); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/prana/http/api/HealthCheckHandlerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.netflix.config.ConfigurationManager; 19 | import io.netty.buffer.ByteBuf; 20 | import io.netty.handler.codec.http.HttpResponseStatus; 21 | import io.reactivex.netty.RxNetty; 22 | import io.reactivex.netty.pipeline.PipelineConfigurators; 23 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 24 | import io.reactivex.netty.protocol.http.server.HttpServer; 25 | import io.reactivex.netty.protocol.http.server.HttpServerRequest; 26 | import io.reactivex.netty.protocol.http.server.HttpServerResponse; 27 | import io.reactivex.netty.protocol.http.server.RequestHandler; 28 | import org.junit.After; 29 | import org.junit.Assert; 30 | import org.junit.Before; 31 | import org.junit.Test; 32 | import rx.Observable; 33 | 34 | public class HealthCheckHandlerTest extends AbstractIntegrationTest { 35 | 36 | private HttpServer externalServer; 37 | private int externalServerPort; 38 | 39 | @Override 40 | protected RequestHandler getHandler() { 41 | return new HealthCheckHandler(objectMapper); 42 | } 43 | 44 | @Before 45 | public void setUp() { 46 | super.setUp(); 47 | externalServer = RxNetty.newHttpServerBuilder(0, new ExternalServerHandler()) 48 | .pipelineConfigurator(PipelineConfigurators.httpServerConfigurator()).build(); 49 | externalServer.start(); 50 | this.externalServerPort = externalServer.getServerPort(); 51 | } 52 | 53 | @After 54 | public void tearDown() throws InterruptedException{ 55 | super.tearDown(); 56 | externalServer.shutdown(); 57 | } 58 | 59 | @Test 60 | public void shouldPingExternalHostsForHealthCheck() { 61 | ConfigurationManager.getConfigInstance().setProperty("prana.host.healthcheck.url", "http://localhost:" + externalServerPort); 62 | HttpClientRequest request = HttpClientRequest.createGet("/healthcheck"); 63 | Assert.assertEquals("ok", TestUtils.getResponse(request, client)); 64 | } 65 | 66 | @Test 67 | public void shouldReturnOkIfHealthCheckURLIsSetToNull() { 68 | System.setProperty("prana.host.healthcheck.url", ""); 69 | ConfigurationManager.getConfigInstance().setProperty("prana.host.healthcheck.url", ""); 70 | HttpClientRequest request = HttpClientRequest.createGet("/healthcheck"); 71 | Assert.assertEquals("ok", TestUtils.getResponse(request, client)); 72 | } 73 | 74 | 75 | private class ExternalServerHandler implements RequestHandler { 76 | 77 | @Override 78 | public Observable handle(HttpServerRequest request, HttpServerResponse response) { 79 | response.setStatus(HttpResponseStatus.OK); 80 | return response.close(); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/prana/http/api/HostsHandlerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.netflix.appinfo.InstanceInfo; 20 | import com.netflix.prana.service.HostService; 21 | import io.netty.buffer.ByteBuf; 22 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 23 | import io.reactivex.netty.protocol.http.server.RequestHandler; 24 | import org.junit.Assert; 25 | import org.junit.Test; 26 | 27 | import java.util.ArrayList; 28 | 29 | import static org.mockito.Mockito.mock; 30 | import static org.mockito.Mockito.when; 31 | 32 | /** 33 | * Created by dchoudhury on 10/28/14. 34 | */ 35 | public class HostsHandlerTest extends AbstractIntegrationTest { 36 | 37 | private HostService hostService = mock(HostService.class); 38 | 39 | @Override 40 | protected RequestHandler getHandler() { 41 | ArrayList instanceInfos = new ArrayList<>(); 42 | instanceInfos.add(InstanceInfo.Builder.newBuilder().setAppName("foo").setVIPAddress("bar").setHostName("host1").build()); 43 | instanceInfos.add(InstanceInfo.Builder.newBuilder().setAppName("foo").setVIPAddress("bar").setHostName("host2").build()); 44 | when(hostService.getHosts("foo")).thenReturn(instanceInfos); 45 | return new HostsHandler(hostService, new ObjectMapper()); 46 | } 47 | 48 | @Test 49 | public void shouldReturnAListOfHostsWhenBothVipAndAppIsSpecified() { 50 | HttpClientRequest request = HttpClientRequest.createGet("/hosts?appName=foo&vip=bar"); 51 | String response = TestUtils.getResponse(request, client); 52 | Assert.assertEquals("[\"host1\",\"host2\"]", response); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/prana/http/api/PingHandlerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 20 | import io.reactivex.netty.protocol.http.server.RequestHandler; 21 | import org.junit.Test; 22 | 23 | import static org.junit.Assert.assertEquals; 24 | 25 | public class PingHandlerTest extends AbstractIntegrationTest { 26 | 27 | @Test 28 | public void shouldRespondWithPong() { 29 | HttpClientRequest request = HttpClientRequest.createGet("/ping"); 30 | assertEquals("pong", TestUtils.getResponse(request, client)); 31 | } 32 | 33 | @Override 34 | protected RequestHandler getHandler() { 35 | return new PingHandler(objectMapper); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/prana/http/api/StatusHandlerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.netflix.prana.http.api; 18 | 19 | import com.netflix.appinfo.ApplicationInfoManager; 20 | import com.netflix.appinfo.InstanceInfo; 21 | import io.netty.buffer.ByteBuf; 22 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 23 | import io.reactivex.netty.protocol.http.server.RequestHandler; 24 | import org.junit.Test; 25 | 26 | import static org.junit.Assert.assertTrue; 27 | import static org.mockito.Mockito.mock; 28 | import static org.mockito.Mockito.when; 29 | 30 | public class StatusHandlerTest extends AbstractIntegrationTest { 31 | 32 | private ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class); 33 | 34 | @Override 35 | protected RequestHandler getHandler() { 36 | return new StatusHandler(objectMapper, applicationInfoManager); 37 | } 38 | 39 | @Test 40 | public void shouldReturnDiscoveryStatus() { 41 | InstanceInfo outOfService = InstanceInfo.Builder.newBuilder() 42 | .setAppName("foo") 43 | .setStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE).build(); 44 | when(applicationInfoManager.getInfo()).thenReturn(outOfService); 45 | HttpClientRequest request = HttpClientRequest.createGet("/status"); 46 | String response = TestUtils.getResponse(request, client); 47 | assertTrue(response.contains("\"status\":\"OUT_OF_SERVICE\"")); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/netflix/prana/http/api/TestUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.netflix.prana.http.api; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.reactivex.netty.protocol.http.client.HttpClient; 20 | import io.reactivex.netty.protocol.http.client.HttpClientRequest; 21 | import io.reactivex.netty.protocol.http.client.HttpClientResponse; 22 | import rx.Observable; 23 | import rx.exceptions.OnErrorThrowable; 24 | import rx.functions.Func1; 25 | 26 | import java.nio.charset.Charset; 27 | 28 | public class TestUtils { 29 | 30 | public static String getResponse(HttpClientRequest request, HttpClient client) { 31 | return client.submit(request).flatMap(new Func1, Observable>() { 32 | @Override 33 | public Observable call(HttpClientResponse response) { 34 | return response.getContent().map(new Func1() { 35 | @Override 36 | public String call(ByteBuf byteBuf) { 37 | return byteBuf.toString(Charset.defaultCharset()); 38 | } 39 | }); 40 | } 41 | }).onErrorFlatMap(new Func1>() { 42 | @Override 43 | public Observable call(OnErrorThrowable onErrorThrowable) { 44 | throw onErrorThrowable; 45 | } 46 | }).toBlocking().first(); 47 | } 48 | } --------------------------------------------------------------------------------