├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.sbt ├── project ├── build.properties └── plugins.sbt ├── scalastyle-config.xml ├── scripts └── build.sh ├── src ├── main │ └── scala │ │ └── com │ │ └── hashicorp │ │ └── nomad │ │ └── scalasdk │ │ ├── NomadScalaApi.scala │ │ ├── ScalaAclPoliciesApi.scala │ │ ├── ScalaAclTokensApi.scala │ │ ├── ScalaAgentApi.scala │ │ ├── ScalaAllocationsApi.scala │ │ ├── ScalaClientApi.scala │ │ ├── ScalaDeploymentsApi.scala │ │ ├── ScalaEvaluationsApi.scala │ │ ├── ScalaJobsApi.scala │ │ ├── ScalaNamespacesApi.scala │ │ ├── ScalaNodesApi.scala │ │ ├── ScalaOperatorApi.scala │ │ ├── ScalaQueryOptions.scala │ │ ├── ScalaQuotasApi.scala │ │ ├── ScalaRegionsApi.scala │ │ ├── ScalaSearchApi.scala │ │ ├── ScalaSentinelPoliciesApi.scala │ │ ├── ScalaStatusApi.scala │ │ ├── ScalaSystemApi.scala │ │ └── package.scala └── test │ └── scala │ └── com │ └── hashicorp │ └── nomad │ └── scalasdk │ └── NomadScalaApiTest.scala └── version.sbt /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | target/ 3 | .idea/ 4 | .idea_modules/ 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | 3 | language: scala 4 | 5 | jdk: 6 | - oraclejdk8 7 | 8 | scala: 9 | - 2.11.12 10 | - 2.12.7 11 | - 2.13.0-M2 12 | 13 | matrix: 14 | exclude: 15 | 16 | before_install: 17 | - | 18 | git clone https://github.com/hashicorp/nomad-java-sdk 19 | cd nomad-java-sdk 20 | mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V 21 | cd - 22 | 23 | before_script: 24 | - | 25 | set -euo pipefail 26 | if [[ ! -f cache/bin/nomad ]]; then 27 | export GOPATH="$PWD/gopath" 28 | eval "$(curl -sL https://raw.githubusercontent.com/travis-ci/gimme/master/gimme | GIMME_GO_VERSION=1.11 bash)" 29 | export PATH="$PATH:$GOPATH/bin" 30 | go get -u github.com/hashicorp/nomad 31 | cd "$GOPATH/src/github.com/hashicorp/nomad" 32 | git checkout tags/v0.9.7 33 | make bootstrap 34 | cd - 35 | 36 | mkdir -p cache/bin 37 | cd cache/bin 38 | go build -tags nomad_test github.com/hashicorp/nomad 39 | cd - 40 | fi 41 | set +euo pipefail # restory options to work around https://github.com/travis-ci/travis-ci/issues/5434 42 | - export PATH="$PWD/cache/bin:$PATH" 43 | 44 | script: sbt ++$TRAVIS_SCALA_VERSION scalastyle test 45 | 46 | cache: 47 | directories: 48 | - $HOME/.m2 49 | - cache 50 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 HashiCorp, Inc. 2 | 3 | Mozilla Public License, version 2.0 4 | 5 | 1. Definitions 6 | 7 | 1.1. "Contributor" 8 | 9 | means each individual or legal entity that creates, contributes to the 10 | creation of, or owns Covered Software. 11 | 12 | 1.2. "Contributor Version" 13 | 14 | means the combination of the Contributions of others (if any) used by a 15 | Contributor and that particular Contributor's Contribution. 16 | 17 | 1.3. "Contribution" 18 | 19 | means Covered Software of a particular Contributor. 20 | 21 | 1.4. "Covered Software" 22 | 23 | means Source Code Form to which the initial Contributor has attached the 24 | notice in Exhibit A, the Executable Form of such Source Code Form, and 25 | Modifications of such Source Code Form, in each case including portions 26 | thereof. 27 | 28 | 1.5. "Incompatible With Secondary Licenses" 29 | means 30 | 31 | a. that the initial Contributor has attached the notice described in 32 | Exhibit B to the Covered Software; or 33 | 34 | b. that the Covered Software was made available under the terms of 35 | version 1.1 or earlier of the License, but not also under the terms of 36 | a Secondary License. 37 | 38 | 1.6. "Executable Form" 39 | 40 | means any form of the work other than Source Code Form. 41 | 42 | 1.7. "Larger Work" 43 | 44 | means a work that combines Covered Software with other material, in a 45 | separate file or files, that is not Covered Software. 46 | 47 | 1.8. "License" 48 | 49 | means this document. 50 | 51 | 1.9. "Licensable" 52 | 53 | means having the right to grant, to the maximum extent possible, whether 54 | at the time of the initial grant or subsequently, any and all of the 55 | rights conveyed by this License. 56 | 57 | 1.10. "Modifications" 58 | 59 | means any of the following: 60 | 61 | a. any file in Source Code Form that results from an addition to, 62 | deletion from, or modification of the contents of Covered Software; or 63 | 64 | b. any new file in Source Code Form that contains any Covered Software. 65 | 66 | 1.11. "Patent Claims" of a Contributor 67 | 68 | means any patent claim(s), including without limitation, method, 69 | process, and apparatus claims, in any patent Licensable by such 70 | Contributor that would be infringed, but for the grant of the License, 71 | by the making, using, selling, offering for sale, having made, import, 72 | or transfer of either its Contributions or its Contributor Version. 73 | 74 | 1.12. "Secondary License" 75 | 76 | means either the GNU General Public License, Version 2.0, the GNU Lesser 77 | General Public License, Version 2.1, the GNU Affero General Public 78 | License, Version 3.0, or any later versions of those licenses. 79 | 80 | 1.13. "Source Code Form" 81 | 82 | means the form of the work preferred for making modifications. 83 | 84 | 1.14. "You" (or "Your") 85 | 86 | means an individual or a legal entity exercising rights under this 87 | License. For legal entities, "You" includes any entity that controls, is 88 | controlled by, or is under common control with You. For purposes of this 89 | definition, "control" means (a) the power, direct or indirect, to cause 90 | the direction or management of such entity, whether by contract or 91 | otherwise, or (b) ownership of more than fifty percent (50%) of the 92 | outstanding shares or beneficial ownership of such entity. 93 | 94 | 95 | 2. License Grants and Conditions 96 | 97 | 2.1. Grants 98 | 99 | Each Contributor hereby grants You a world-wide, royalty-free, 100 | non-exclusive license: 101 | 102 | a. under intellectual property rights (other than patent or trademark) 103 | Licensable by such Contributor to use, reproduce, make available, 104 | modify, display, perform, distribute, and otherwise exploit its 105 | Contributions, either on an unmodified basis, with Modifications, or 106 | as part of a Larger Work; and 107 | 108 | b. under Patent Claims of such Contributor to make, use, sell, offer for 109 | sale, have made, import, and otherwise transfer either its 110 | Contributions or its Contributor Version. 111 | 112 | 2.2. Effective Date 113 | 114 | The licenses granted in Section 2.1 with respect to any Contribution 115 | become effective for each Contribution on the date the Contributor first 116 | distributes such Contribution. 117 | 118 | 2.3. Limitations on Grant Scope 119 | 120 | The licenses granted in this Section 2 are the only rights granted under 121 | this License. No additional rights or licenses will be implied from the 122 | distribution or licensing of Covered Software under this License. 123 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 124 | Contributor: 125 | 126 | a. for any code that a Contributor has removed from Covered Software; or 127 | 128 | b. for infringements caused by: (i) Your and any other third party's 129 | modifications of Covered Software, or (ii) the combination of its 130 | Contributions with other software (except as part of its Contributor 131 | Version); or 132 | 133 | c. under Patent Claims infringed by Covered Software in the absence of 134 | its Contributions. 135 | 136 | This License does not grant any rights in the trademarks, service marks, 137 | or logos of any Contributor (except as may be necessary to comply with 138 | the notice requirements in Section 3.4). 139 | 140 | 2.4. Subsequent Licenses 141 | 142 | No Contributor makes additional grants as a result of Your choice to 143 | distribute the Covered Software under a subsequent version of this 144 | License (see Section 10.2) or under the terms of a Secondary License (if 145 | permitted under the terms of Section 3.3). 146 | 147 | 2.5. Representation 148 | 149 | Each Contributor represents that the Contributor believes its 150 | Contributions are its original creation(s) or it has sufficient rights to 151 | grant the rights to its Contributions conveyed by this License. 152 | 153 | 2.6. Fair Use 154 | 155 | This License is not intended to limit any rights You have under 156 | applicable copyright doctrines of fair use, fair dealing, or other 157 | equivalents. 158 | 159 | 2.7. Conditions 160 | 161 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 162 | Section 2.1. 163 | 164 | 165 | 3. Responsibilities 166 | 167 | 3.1. Distribution of Source Form 168 | 169 | All distribution of Covered Software in Source Code Form, including any 170 | Modifications that You create or to which You contribute, must be under 171 | the terms of this License. You must inform recipients that the Source 172 | Code Form of the Covered Software is governed by the terms of this 173 | License, and how they can obtain a copy of this License. You may not 174 | attempt to alter or restrict the recipients' rights in the Source Code 175 | Form. 176 | 177 | 3.2. Distribution of Executable Form 178 | 179 | If You distribute Covered Software in Executable Form then: 180 | 181 | a. such Covered Software must also be made available in Source Code Form, 182 | as described in Section 3.1, and You must inform recipients of the 183 | Executable Form how they can obtain a copy of such Source Code Form by 184 | reasonable means in a timely manner, at a charge no more than the cost 185 | of distribution to the recipient; and 186 | 187 | b. You may distribute such Executable Form under the terms of this 188 | License, or sublicense it under different terms, provided that the 189 | license for the Executable Form does not attempt to limit or alter the 190 | recipients' rights in the Source Code Form under this License. 191 | 192 | 3.3. Distribution of a Larger Work 193 | 194 | You may create and distribute a Larger Work under terms of Your choice, 195 | provided that You also comply with the requirements of this License for 196 | the Covered Software. If the Larger Work is a combination of Covered 197 | Software with a work governed by one or more Secondary Licenses, and the 198 | Covered Software is not Incompatible With Secondary Licenses, this 199 | License permits You to additionally distribute such Covered Software 200 | under the terms of such Secondary License(s), so that the recipient of 201 | the Larger Work may, at their option, further distribute the Covered 202 | Software under the terms of either this License or such Secondary 203 | License(s). 204 | 205 | 3.4. Notices 206 | 207 | You may not remove or alter the substance of any license notices 208 | (including copyright notices, patent notices, disclaimers of warranty, or 209 | limitations of liability) contained within the Source Code Form of the 210 | Covered Software, except that You may alter any license notices to the 211 | extent required to remedy known factual inaccuracies. 212 | 213 | 3.5. Application of Additional Terms 214 | 215 | You may choose to offer, and to charge a fee for, warranty, support, 216 | indemnity or liability obligations to one or more recipients of Covered 217 | Software. However, You may do so only on Your own behalf, and not on 218 | behalf of any Contributor. You must make it absolutely clear that any 219 | such warranty, support, indemnity, or liability obligation is offered by 220 | You alone, and You hereby agree to indemnify every Contributor for any 221 | liability incurred by such Contributor as a result of warranty, support, 222 | indemnity or liability terms You offer. You may include additional 223 | disclaimers of warranty and limitations of liability specific to any 224 | jurisdiction. 225 | 226 | 4. Inability to Comply Due to Statute or Regulation 227 | 228 | If it is impossible for You to comply with any of the terms of this License 229 | with respect to some or all of the Covered Software due to statute, 230 | judicial order, or regulation then You must: (a) comply with the terms of 231 | this License to the maximum extent possible; and (b) describe the 232 | limitations and the code they affect. Such description must be placed in a 233 | text file included with all distributions of the Covered Software under 234 | this License. Except to the extent prohibited by statute or regulation, 235 | such description must be sufficiently detailed for a recipient of ordinary 236 | skill to be able to understand it. 237 | 238 | 5. Termination 239 | 240 | 5.1. The rights granted under this License will terminate automatically if You 241 | fail to comply with any of its terms. However, if You become compliant, 242 | then the rights granted under this License from a particular Contributor 243 | are reinstated (a) provisionally, unless and until such Contributor 244 | explicitly and finally terminates Your grants, and (b) on an ongoing 245 | basis, if such Contributor fails to notify You of the non-compliance by 246 | some reasonable means prior to 60 days after You have come back into 247 | compliance. Moreover, Your grants from a particular Contributor are 248 | reinstated on an ongoing basis if such Contributor notifies You of the 249 | non-compliance by some reasonable means, this is the first time You have 250 | received notice of non-compliance with this License from such 251 | Contributor, and You become compliant prior to 30 days after Your receipt 252 | of the notice. 253 | 254 | 5.2. If You initiate litigation against any entity by asserting a patent 255 | infringement claim (excluding declaratory judgment actions, 256 | counter-claims, and cross-claims) alleging that a Contributor Version 257 | directly or indirectly infringes any patent, then the rights granted to 258 | You by any and all Contributors for the Covered Software under Section 259 | 2.1 of this License shall terminate. 260 | 261 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 262 | license agreements (excluding distributors and resellers) which have been 263 | validly granted by You or Your distributors under this License prior to 264 | termination shall survive termination. 265 | 266 | 6. Disclaimer of Warranty 267 | 268 | Covered Software is provided under this License on an "as is" basis, 269 | without warranty of any kind, either expressed, implied, or statutory, 270 | including, without limitation, warranties that the Covered Software is free 271 | of defects, merchantable, fit for a particular purpose or non-infringing. 272 | The entire risk as to the quality and performance of the Covered Software 273 | is with You. Should any Covered Software prove defective in any respect, 274 | You (not any Contributor) assume the cost of any necessary servicing, 275 | repair, or correction. This disclaimer of warranty constitutes an essential 276 | part of this License. No use of any Covered Software is authorized under 277 | this License except under this disclaimer. 278 | 279 | 7. Limitation of Liability 280 | 281 | Under no circumstances and under no legal theory, whether tort (including 282 | negligence), contract, or otherwise, shall any Contributor, or anyone who 283 | distributes Covered Software as permitted above, be liable to You for any 284 | direct, indirect, special, incidental, or consequential damages of any 285 | character including, without limitation, damages for lost profits, loss of 286 | goodwill, work stoppage, computer failure or malfunction, or any and all 287 | other commercial damages or losses, even if such party shall have been 288 | informed of the possibility of such damages. This limitation of liability 289 | shall not apply to liability for death or personal injury resulting from 290 | such party's negligence to the extent applicable law prohibits such 291 | limitation. Some jurisdictions do not allow the exclusion or limitation of 292 | incidental or consequential damages, so this exclusion and limitation may 293 | not apply to You. 294 | 295 | 8. Litigation 296 | 297 | Any litigation relating to this License may be brought only in the courts 298 | of a jurisdiction where the defendant maintains its principal place of 299 | business and such litigation shall be governed by laws of that 300 | jurisdiction, without reference to its conflict-of-law provisions. Nothing 301 | in this Section shall prevent a party's ability to bring cross-claims or 302 | counter-claims. 303 | 304 | 9. Miscellaneous 305 | 306 | This License represents the complete agreement concerning the subject 307 | matter hereof. If any provision of this License is held to be 308 | unenforceable, such provision shall be reformed only to the extent 309 | necessary to make it enforceable. Any law or regulation which provides that 310 | the language of a contract shall be construed against the drafter shall not 311 | be used to construe this License against a Contributor. 312 | 313 | 314 | 10. Versions of the License 315 | 316 | 10.1. New Versions 317 | 318 | Mozilla Foundation is the license steward. Except as provided in Section 319 | 10.3, no one other than the license steward has the right to modify or 320 | publish new versions of this License. Each version will be given a 321 | distinguishing version number. 322 | 323 | 10.2. Effect of New Versions 324 | 325 | You may distribute the Covered Software under the terms of the version 326 | of the License under which You originally received the Covered Software, 327 | or under the terms of any subsequent version published by the license 328 | steward. 329 | 330 | 10.3. Modified Versions 331 | 332 | If you create software not governed by this License, and you want to 333 | create a new license for such software, you may create and use a 334 | modified version of this License if you rename the license and remove 335 | any references to the name of the license steward (except to note that 336 | such modified license differs from this License). 337 | 338 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 339 | Licenses If You choose to distribute Source Code Form that is 340 | Incompatible With Secondary Licenses under the terms of this version of 341 | the License, the notice described in Exhibit B of this License must be 342 | attached. 343 | 344 | Exhibit A - Source Code Form License Notice 345 | 346 | This Source Code Form is subject to the 347 | terms of the Mozilla Public License, v. 348 | 2.0. If a copy of the MPL was not 349 | distributed with this file, You can 350 | obtain one at 351 | http://mozilla.org/MPL/2.0/. 352 | 353 | If it is not possible or desirable to put the notice in a particular file, 354 | then You may include the notice in a location (such as a LICENSE file in a 355 | relevant directory) where a recipient would be likely to look for such a 356 | notice. 357 | 358 | You may add additional accurate notices of copyright ownership. 359 | 360 | Exhibit B - "Incompatible With Secondary Licenses" Notice 361 | 362 | This Source Code Form is "Incompatible 363 | With Secondary Licenses", as defined by 364 | the Mozilla Public License, v. 2.0. 365 | 366 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Nomad Scala SDK [![Build Status](https://travis-ci.org/hashicorp/nomad-scala-sdk.svg?branch=master)](https://travis-ci.org/hashicorp/nomad-scala-sdk) [![Maven Central](https://img.shields.io/maven-central/v/com.hashicorp.nomad/nomad-scala-sdk_2.11.svg)](https://mvnrepository.com/artifact/com.hashicorp.nomad/nomad-scala-sdk_2.11) 2 | =============== 3 | 4 | A Scala SDK for interacting with [HashiCorp's Nomad] through its [HTTP API]. 5 | This is a wrapper around the [Java SDK]. 6 | 7 | [HashiCorp's Nomad]: https://www.nomadproject.io/ 8 | [HTTP API]: https://www.nomadproject.io/docs/http/ 9 | [Java SDK]: https://github.com/hashicorp/nomad-java-sdk 10 | 11 | This SDK requires at least a Java 8 runtime. 12 | 13 | 14 | Using 15 | ----- 16 | 17 | Create a `NomadScalaApi`. 18 | 19 | ```.scala 20 | val api = NomadScalaApi("http://my.nomad.server:4646"); 21 | ``` 22 | 23 | Methods are grouped into into API groupings according to their function, 24 | and these groupings can be accessed from the client. 25 | For example, to list the jobs running on the cluster, 26 | use the `list` method on the jobs API grouping: 27 | 28 | ```.scala 29 | val responseFuture: ServerQueryResponse[Seq[JobListStub]] = 30 | api.jobs.list() 31 | ``` 32 | 33 | The result is a `ServerQueryResponse`. The API has a few 34 | different response types, depending on the type of query. The response 35 | classes have some methods for getting metadata about the response, 36 | and a `getValue` method that returns the response value. 37 | The generic type parameter in the response class indicates the response 38 | value type, so in this case, `getValue` will return a sequence of 39 | `JobListStub`s. 40 | 41 | ### Request Options 42 | 43 | Endpoints that interact with server APIs accept `ScalaQueryOptions` or 44 | `WriteOptions`, which let you specify additional options when making a 45 | request. 46 | 47 | `ScalaQueryOptions` supports [stale queries], and [blocking queries]. 48 | It also supports repeated performing blocking queries until a condition is met. 49 | 50 | [cross-region requests]: https://www.nomadproject.io/docs/http/index.html#cross-region-requests 51 | [blocking queries]: https://www.nomadproject.io/docs/http/index.html#blocking-queries 52 | [stale queries]: https://www.nomadproject.io/docs/http/index.html#consistency-modes 53 | 54 | #### Regions 55 | 56 | Both `ScalaQueryOptions` or `WriteOptions` allow you to specify a region to 57 | support [cross-region requests]. Requests sent to a Nomad server are 58 | bound to a particular region; if no region is specified, the server 59 | assumes the request is bound for its own region. You can specify an 60 | explicit region per-request using the options, and you can specify a 61 | client-wide default in the client configuration. You can also rely on 62 | the default behaviour. 63 | 64 | ### Note on Terminology 65 | 66 | Nomad *agents* can operate as *Nomad servers* which perform scheduling, 67 | or *Nomad clients* which connect to servers and run the task groups they 68 | are assigned, or both (see the [Nomad glossary]). Regardless of their client 69 | and/or server roles in the Nomad cluster, all agents have an embedded 70 | HTTP server that serves the Nomad [HTTP API]. This Java API makes use of an 71 | *HTTP client* to connect to that API, and is thus a Nomad HTTP *API client*. 72 | 73 | [Nomad glossary]: https://www.nomadproject.io/docs/internals/architecture.html#glossary 74 | 75 | So be aware that there are two conflicting meanings of "client" in 76 | scope. `NomadApiClient` is the main API client class, and has nothing to 77 | do with the *Nomad client* concept. The `ClientApi` class, on the other 78 | hand, is the API for interacting with Nomad client agents. 79 | 80 | 81 | Building 82 | -------- 83 | 84 | The SDK is built with sbt. You can use `scripts/build.sh` to run a 85 | build, provided an appropriate Nomad executable is available for tests 86 | as described below. 87 | 88 | ### Testing 89 | 90 | The tests make use of Nomad's 91 | [`mock_driver`](https://github.com/hashicorp/nomad/blob/master/client/driver/mock_driver.go), 92 | a driver for test purposes that isn't built into Nomad by default. 93 | To build Nomad with `mock_driver` support, you will need Go, a properly 94 | configured `GOPATH`, and the [Nomad source], which you can clone with 95 | git or with `go get`, e.g.: 96 | 97 | ```.sh 98 | go get github.com/hashicorp/nomad 99 | ``` 100 | 101 | [Nomad source]: https://github.com/hashicorp/nomad 102 | 103 | You will then need to pass the `nomad_test` flag passed to the Go 104 | compiler when building Nomad, e.g. the follow will put a Nomad 105 | executable in `$GOPATH/bin/`: 106 | 107 | ```.sh 108 | go install -tags nomad_test github.com/hashicorp/nomad 109 | ``` 110 | 111 | You can then run the tests with this executable on the `PATH`, e.g.: 112 | 113 | ```.sh 114 | PATH="$GOPATH/bin:$PATH" sbt test 115 | ``` 116 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | import sbt.KeyRanks.APlusSetting 2 | 3 | organization := "com.hashicorp.nomad" 4 | organizationName := "Hashicorp" 5 | organizationHomepage := Some(url("https://www.hashicorp.com/")) 6 | 7 | name := "nomad-scala-sdk" 8 | homepage := Some(url("https://github.com/hashicorp/nomad-scala-sdk")) 9 | scmInfo := homepage.value.map { repo => 10 | ScmInfo( 11 | browseUrl = repo, 12 | connection = s"scm:git:$repo.git" 13 | ) 14 | } 15 | licenses := Seq("Mozilla Public License, version 2.0" -> url("https://www.mozilla.org/en-US/MPL/2.0/")) 16 | 17 | crossScalaVersions := Seq("2.11.12", "2.12.4", "2.13.0-M2") 18 | scalaVersion := crossScalaVersions.value.head 19 | 20 | resolvers += Resolver.mavenLocal 21 | 22 | val nomadJavaSdkVersion = SettingKey[String]("nomadJavaSdkVersion", "The version of the Java nomad-sdk dependency.") 23 | nomadJavaSdkVersion := "0.9.7.0" 24 | 25 | libraryDependencies += "com.hashicorp.nomad" % "nomad-sdk" % nomadJavaSdkVersion.value 26 | 27 | libraryDependencies += "com.hashicorp.nomad" % "nomad-testkit" % nomadJavaSdkVersion.value % Test 28 | libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.4" % Test 29 | 30 | useGpg := true 31 | usePgpKeyHex("7D65AD3D5B24A0EA035BDA2BDC6367189CC3BC7C") 32 | 33 | publishMavenStyle := true 34 | pomExtra := 35 | 36 | 37 | {organizationName.value} 38 | {organizationHomepage.value} 39 | 40 | 41 | 42 | releaseCrossBuild := true 43 | releaseVersion := (_ => nomadJavaSdkVersion.value) 44 | releaseProcess := { 45 | import ReleaseTransformations._ 46 | Seq[ReleaseStep]( 47 | checkSnapshotDependencies, 48 | inquireVersions, 49 | runClean, 50 | ReleaseStep(action = Command.process("scalastyle", _)), 51 | runTest, 52 | setReleaseVersion, 53 | commitReleaseVersion, 54 | tagRelease, 55 | ReleaseStep(action = Command.process("publishSigned", _), enableCrossBuild = true), 56 | setNextVersion, 57 | commitNextVersion, 58 | ReleaseStep(action = Command.process("sonatypeReleaseAll", _), enableCrossBuild = true), 59 | pushChanges 60 | ) 61 | } 62 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.15 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0") 2 | addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.9") 3 | addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.1") 4 | addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "1.1") 5 | -------------------------------------------------------------------------------- /scalastyle-config.xml: -------------------------------------------------------------------------------- 1 | 2 | Scalastyle configuration for Nomad Scala API 3 | 4 | 5 | (.*Test$) 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 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 | -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | exec sbt +compile +test:compile +test +scalastyle 5 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/NomadScalaApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import com.hashicorp.nomad.apimodel.Node 4 | import com.hashicorp.nomad.javasdk.{ NomadApiClient, NomadApiConfiguration } 5 | import org.apache.http.HttpHost 6 | 7 | /** Companion object for NomadScalaApi with helpful apply methods. */ 8 | object NomadScalaApi { 9 | 10 | /** Creates a Scala API client. 11 | * 12 | * @param address the scheme (http or https), host and port of the agent to connect to, 13 | * e.g. "http://localhost:4646" 14 | **/ 15 | def apply(address: String): NomadScalaApi = 16 | new NomadScalaApi(new NomadApiClient(address)) 17 | 18 | /** Creates a Scala API client. 19 | * 20 | * @param address the scheme (http or https), host and port of the agent to connect to 21 | **/ 22 | def apply(address: HttpHost): NomadScalaApi = 23 | new NomadScalaApi(new NomadApiClient(address)) 24 | 25 | /** Returns a new NomadScalaApi. 26 | * 27 | * @param config the configuration for the new API instance 28 | */ 29 | def apply(config: NomadApiConfiguration): NomadScalaApi = 30 | new NomadScalaApi(new NomadApiClient(config)) 31 | 32 | } 33 | 34 | /** An API for interacting with Nomad in Scala. 35 | * 36 | * The Scala API is a wrapper for the NomadApiClient from the Nomad Java SDK that provides more Scala friendly types 37 | * for convenient use from Scala. 38 | * 39 | * @param apiClient the underlying API client from the Nomad Java SDK 40 | */ 41 | class NomadScalaApi(val apiClient: NomadApiClient) { 42 | 43 | /** Returns the API's configuration */ 44 | def config: NomadApiConfiguration = 45 | apiClient.getConfig 46 | 47 | /** Sets the active ACL token secret ID that this client passes to the server. 48 | * 49 | * @param authToken the secret ID to use 50 | */ 51 | def setAuthToken(authToken: String): this.type = { 52 | apiClient.setAuthToken(authToken) 53 | this 54 | } 55 | 56 | /** Sets the active namespace of this API client. 57 | * 58 | * @param namespace the namespace to use 59 | */ 60 | def setNamespace(namespace: String): this.type = { 61 | apiClient.setNamespace(namespace) 62 | this 63 | } 64 | 65 | /** Closes the underlying NomadApiClient's HTTP client. */ 66 | def close(): Unit = 67 | apiClient.close() 68 | 69 | /** Returns an API for managing ACL policies. */ 70 | def aclPolicies: ScalaAclPoliciesApi = 71 | new ScalaAclPoliciesApi(apiClient.getAclPoliciesApi) 72 | 73 | /** Returns an API for managing ACL tokens. */ 74 | def aclTokens: ScalaAclTokensApi = 75 | new ScalaAclTokensApi(apiClient.getAclTokensApi) 76 | 77 | /** Returns an API for agent a cluster management. */ 78 | def agent: ScalaAgentApi = 79 | new ScalaAgentApi(apiClient.getAgentApi) 80 | 81 | /** Returns an API for querying information about allocations. */ 82 | def allocations: ScalaAllocationsApi = 83 | new ScalaAllocationsApi(apiClient.getAllocationsApi) 84 | 85 | /** Returns an API for interacting directly with a client node. 86 | * 87 | * @param node the client node to connect to 88 | */ 89 | def client(node: Node): ScalaClientApi = 90 | new ScalaClientApi(apiClient.getClientApi(node)) 91 | 92 | /** Returns an API for interacting directly with a client node. 93 | * 94 | * @param clientAddress the HTTP or HTTPS address of the client node 95 | */ 96 | def client(clientAddress: HttpHost): ScalaClientApi = 97 | new ScalaClientApi(apiClient.getClientApi(clientAddress)) 98 | 99 | /** Returns an API for interacting directly with a client node after looking up its address. 100 | * 101 | * @param nodeId the nodeId of the client node to connect to 102 | */ 103 | def lookupClientApiByNodeId(nodeId: String): ScalaClientApi = 104 | new ScalaClientApi(apiClient.lookupClientApiByNodeId(nodeId)) 105 | 106 | /** Returns an API for managing deployments. */ 107 | def getDeploymentsApi: ScalaDeploymentsApi = 108 | new ScalaDeploymentsApi(apiClient.getDeploymentsApi) 109 | 110 | /** Returns an API for querying information about evaluations. */ 111 | def evaluations: ScalaEvaluationsApi = 112 | new ScalaEvaluationsApi(apiClient.getEvaluationsApi) 113 | 114 | /** Returns an API for submitting and managing jobs. */ 115 | def jobs: ScalaJobsApi = 116 | new ScalaJobsApi(apiClient.getJobsApi) 117 | 118 | /** Returns an API for managing namespaces. */ 119 | def namespaces: ScalaNamespacesApi = 120 | new ScalaNamespacesApi(apiClient.getNamespacesApi) 121 | 122 | /** Returns an API for querying information about the client nodes in the Nomad cluster. */ 123 | def nodes: ScalaNodesApi = 124 | new ScalaNodesApi(apiClient.getNodesApi) 125 | 126 | /** Returns an API for operating the Nomad cluster. */ 127 | def operatorApi: ScalaOperatorApi = 128 | new ScalaOperatorApi(apiClient.getOperatorApi) 129 | 130 | /** Returns an API for managing quotas. */ 131 | def quotas: ScalaQuotasApi = 132 | new ScalaQuotasApi(apiClient.getQuotasApi) 133 | 134 | /** Returns an API for listing the regions in the Nomad cluster. */ 135 | def regions: ScalaRegionsApi = 136 | new ScalaRegionsApi(apiClient.getRegionsApi) 137 | 138 | /** Returns an API for searching for items in Nomad cluster. */ 139 | def search: ScalaSearchApi = 140 | new ScalaSearchApi(apiClient.getSearchApi) 141 | 142 | /** Returns an API for managing sentinel policies. */ 143 | def sentinelPolicies: ScalaSentinelPoliciesApi = 144 | new ScalaSentinelPoliciesApi(apiClient.getSentinelPoliciesApi) 145 | 146 | /** Returns an API for querying the status of the Nomad cluster. */ 147 | def status: ScalaStatusApi = 148 | new ScalaStatusApi(apiClient.getStatusApi) 149 | 150 | /** Returns an API for performing system maintenance operations on the Nomad cluster. */ 151 | def system: ScalaSystemApi = 152 | new ScalaSystemApi(apiClient.getSystemApi) 153 | 154 | } 155 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaAclPoliciesApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{ AclPolicy, AclPolicyListStub } 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** 9 | * API for managing ACL policies, 10 | * exposing the [[https://www.nomadproject.io/api/acl-policies.html ACL policies]] functionality of the 11 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 12 | * 13 | * @param aclPoliciesApi the underlying Java SDK AclPoliciesApi 14 | */ 15 | class ScalaAclPoliciesApi(aclPoliciesApi: AclPoliciesApi) { 16 | 17 | /** 18 | * Deletes an ACL policy. 19 | * 20 | * @param policyName name of the policy to delete 21 | * @param options options controlling how the request is performed 22 | * @see [[https://www.nomadproject.io/docs/http/acl-policy.html#delete-policy `DELETE /v1/acl/policy/:name`]] 23 | */ 24 | def delete(policyName: String, options: Option[WriteOptions] = None): ServerResponse[Unit] = 25 | aclPoliciesApi.delete(policyName, options.orNull) 26 | .map((_: Void) => ()) 27 | 28 | /** 29 | * Retrieves an ACL policy. 30 | * 31 | * @param name name of the policy. 32 | * @param options options controlling how the request is performed 33 | * @see [[https://www.nomadproject.io/docs/http/acl-policies.html#read-policy `GET /v1/acl/policy/:name`]] 34 | */ 35 | def info(name: String, options: Option[ScalaQueryOptions[AclPolicy]] = None): ServerQueryResponse[AclPolicy] = 36 | aclPoliciesApi.info(name, options.asJava) 37 | 38 | /** 39 | * Lists ACL policies. 40 | * 41 | * @param namePrefix a name prefix that, if given, 42 | * restricts the results to only policies having a name with this prefix 43 | * @param options options controlling how the request is performed 44 | * @see [[https://www.nomadproject.io/docs/http/acl-policies.html#list-policies `GET /v1/acl/policies`]] 45 | */ 46 | def list(namePrefix: Option[String] = None, options: Option[ScalaQueryOptions[Seq[AclPolicyListStub]]] = None): ServerQueryResponse[Seq[AclPolicyListStub]] = 47 | aclPoliciesApi.list(namePrefix.orNull, options.asJava(_.asScala)) 48 | .map(_.asScala) 49 | 50 | /** 51 | * Creates or updates an ACL policy. 52 | * 53 | * @param policy the ACL policy 54 | * @param options options controlling how the request is performed 55 | * @see [[https://www.nomadproject.io/docs/http/acl-policies.html#create-or-update-policy `PUT /v1/acl/policy/:name`]] 56 | */ 57 | def upsert(policy: AclPolicy, options: Option[WriteOptions] = None): ServerResponse[Unit] = 58 | aclPoliciesApi.upsert(policy, options.orNull) 59 | .map((_: Void) => ()) 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaAclTokensApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{ AclToken, AclTokenListStub } 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** 9 | * API for managing ACL tokens, 10 | * exposing the [[https://www.nomadproject.io/api/acl-tokens.html ACL tokens]] functionality of the 11 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 12 | * 13 | * @param aclTokensApi the underlying Java SDK AclTokensApi 14 | */ 15 | class ScalaAclTokensApi(aclTokensApi: AclTokensApi) { 16 | 17 | /** 18 | * Bootstraps the ACL system and returns the initial management token. 19 | * 20 | * @param options options controlling how the request is performed 21 | * @see [[https://www.nomadproject.io/api/acl-tokens.html#bootstrap-token `PUT /v1/acl/bootstrap`]] 22 | */ 23 | def bootstrap(options: Option[WriteOptions] = None): ServerResponse[AclToken] = 24 | aclTokensApi.bootstrap(options.orNull) 25 | 26 | /** 27 | * Creates an ACL token, returning a token with a server-assigned accessor ID and secret ID. 28 | * 29 | * @param token a token with no accessor ID 30 | * @param options options controlling how the request is performed 31 | * @see [[https://www.nomadproject.io/api/acl-tokens.html#create-token `PUT /v1/acl/token`]] 32 | */ 33 | def create(token: AclToken, options: Option[WriteOptions] = None): ServerResponse[AclToken] = 34 | aclTokensApi.create(token, options.orNull) 35 | 36 | /** 37 | * Deletes an ACL token. 38 | * 39 | * @param accessorId accessorId of the token to delete 40 | * @param options options controlling how the request is performed 41 | * @see [[https://www.nomadproject.io/docs/http/acl-token.html#delete-token `DELETE /v1/acl/token/:accessor_id`]] 42 | */ 43 | def delete(accessorId: String, options: Option[WriteOptions] = None): ServerResponse[Void] = 44 | aclTokensApi.delete(accessorId, options.orNull) 45 | 46 | /** 47 | * Retrieves an ACL token. 48 | * 49 | * @param accessorId accessor ID of the token. 50 | * @param options options controlling how the request is performed 51 | * @see [[https://www.nomadproject.io/api/acl-tokens.html#read-token `GET /v1/acl/token/:accessor_id`]] 52 | */ 53 | def info(accessorId: String, options: Option[ScalaQueryOptions[AclToken]] = None): ServerQueryResponse[AclToken] = 54 | aclTokensApi.info(accessorId, options.asJava) 55 | 56 | /** 57 | * Lists ACL tokens. 58 | * 59 | * @param accessorIdPrefix an even-length accessor ID prefix that, if given, 60 | * restricts the results to only tokens having an accessor ID with this prefix 61 | * @param options options controlling how the request is performed 62 | * @see [[https://www.nomadproject.io/api/acl-tokens.html#list-tokens `GET /v1/acl/tokens`]] 63 | */ 64 | def list( 65 | accessorIdPrefix: Option[String] = None, 66 | options: Option[ScalaQueryOptions[Seq[AclTokenListStub]]] = None 67 | ): ServerQueryResponse[Seq[AclTokenListStub]] = 68 | aclTokensApi.list(accessorIdPrefix.orNull, options.asJava(_.asScala)) 69 | .map(_.asScala) 70 | 71 | /** 72 | * Retrieves the ACL token currently being used. 73 | * 74 | * @param options options controlling how the request is performed 75 | * @see [[https://www.nomadproject.io/api/acl-tokens.html#read-self-token `GET /v1/acl/token/self`]] 76 | */ 77 | def self(options: Option[ScalaQueryOptions[AclToken]] = None): ServerQueryResponse[AclToken] = 78 | aclTokensApi.self(options.asJava) 79 | 80 | /** 81 | * Updates an ACL token. 82 | * 83 | * @param token a token with with an accessor ID 84 | * @param options options controlling how the request is performed 85 | * @see [[https://www.nomadproject.io/api/acl-tokens.html#update-token `PUT /v1/acl/token/:accessor_id`]] 86 | */ 87 | def update(token: AclToken, options: Option[WriteOptions] = None): ServerResponse[AclToken] = 88 | aclTokensApi.update(token, options.orNull) 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaAgentApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{ AgentHealthResponse, AgentSelf, ServerMembers } 6 | import com.hashicorp.nomad.javasdk.{ AgentApi, NomadResponse } 7 | 8 | /** Scala API for Nomad agent and cluster management, 9 | * exposing the functionality of the `/v1/agent/…` endpoints of the 10 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 11 | * 12 | * @param agentApi the underlying Java SDK AgentApi 13 | */ 14 | class ScalaAgentApi private[scalasdk](agentApi: AgentApi) { 15 | 16 | /** Performs a basic healthcheck. 17 | * 18 | * @see [[https://www.nomadproject.io/api/agent.html#health `GET /v1/agent/health`]] 19 | */ 20 | def health(): NomadResponse[AgentHealthResponse] = 21 | agentApi.health() 22 | 23 | /** Queries for information about the agent we are connected to. 24 | * 25 | * @see [[https://www.nomadproject.io/docs/http/agent-self.html `GET /v1/agent/self`]] 26 | */ 27 | def self(): NomadResponse[AgentSelf] = 28 | agentApi.self() 29 | 30 | /** Queries for the known peers in the gossip pool. 31 | * 32 | * @see [[https://www.nomadproject.io/docs/http/agent-members.html `GET /v1/agent/members`]] 33 | */ 34 | def members(): NomadResponse[ServerMembers] = 35 | agentApi.members() 36 | 37 | /** Forces a member of the gossip pool from the "failed" state into the "left" state. 38 | * 39 | * @param nodeName the name of the node to force out of the pool 40 | * @see [[https://www.nomadproject.io/docs/http/agent-force-leave.html `PUT /v1/agent/force-leave`]] 41 | */ 42 | def forceLeave(nodeName: String): NomadResponse[Unit] = 43 | agentApi.forceLeave(nodeName) 44 | .map((_: Void) => ()) 45 | 46 | /** Queries an agent in client mode for its list of known servers. 47 | * 48 | * @see [[https://www.nomadproject.io/docs/http/agent-servers.html#get `GET /v1/agent/servers`]] 49 | */ 50 | def servers(): NomadResponse[Seq[String]] = 51 | agentApi.servers() 52 | .map(_.asScala: Seq[String]) 53 | 54 | /** Updates the list of known servers to the given addresses, replacing all previous addresses. 55 | * 56 | * @param addresses the server addresses 57 | * @see [[https://www.nomadproject.io/docs/http/agent-servers.html#put-post `PUT /v1/agent/servers`]] 58 | */ 59 | def setServers(addresses: Iterable[String]): NomadResponse[Unit] = 60 | agentApi.setServers(addresses.asJava) 61 | .map((_: Void) => ()) 62 | 63 | /** Causes the agent to join a cluster by joining the gossip pool at one of the given addresses. 64 | * 65 | * @param addresses the addresses to try joining 66 | * @see [[https://www.nomadproject.io/docs/http/agent-join.html `PUT /v1/agent/join`]] 67 | */ 68 | def join(addresses: Iterable[String]): NomadResponse[Unit] = 69 | agentApi.setServers(addresses.asJava) 70 | .map((_: Void) => ()) 71 | } 72 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaAllocationsApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | import com.hashicorp.nomad.apimodel.{AllocStopResponse, Allocation, AllocationListStub} 5 | import com.hashicorp.nomad.javasdk._ 6 | 7 | /** API for querying for information about allocations, 8 | * exposing the functionality of the `/v1/allocations` and `/v1/allocation` endpoints of the 9 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 10 | * 11 | * @param allocationsApi the underlying API from the Java SDK 12 | */ 13 | class ScalaAllocationsApi private[scalasdk](allocationsApi: AllocationsApi) { 14 | 15 | /** Queries an allocation in the active region. 16 | * 17 | * @param id the allocation ID to lookup 18 | * @param options options controlling how the request is performed 19 | * @see [[https://www.nomadproject.io/docs/http/alloc.html `GET /v1/allocation/{ID}`]] 20 | */ 21 | def info(id: String, options: Option[ScalaQueryOptions[Allocation]] = None): ServerQueryResponse[Allocation] = 22 | allocationsApi.info(id, options.asJava) 23 | 24 | /** Lists allocations in the active region. 25 | * 26 | * @param allocationIdPrefix an even-length prefix that, if given, 27 | * restricts the results to only allocations having an ID with this prefix 28 | * @param options options controlling how the request is performed 29 | * @see [[https://www.nomadproject.io/docs/http/allocs.html `GET /v1/allocations`]] 30 | */ 31 | def list( 32 | allocationIdPrefix: Option[String] = None, 33 | options: Option[ScalaQueryOptions[Seq[AllocationListStub]]] = None 34 | ): ServerQueryResponse[Seq[AllocationListStub]] = 35 | allocationsApi.list(allocationIdPrefix.orNull, options.asJava((_: java.util.List[AllocationListStub]).asScala)) 36 | .map(_.asScala) 37 | 38 | /** Stops and reschedules an allocation. 39 | * 40 | * @param id the allocation ID to stop 41 | * @return allocation stop response, including the id of the follow-up evaluation for any rescheduled alloc. 42 | * @see [[https://nomadproject.io/api-docs/allocations/#stop-allocation `PUT /v1/allocation/{ID}/stop`]] 43 | */ 44 | def stop(id: String): ServerResponse[AllocStopResponse] = allocationsApi.stop(id) 45 | 46 | /** Sends a signal to an allocation or task. 47 | * 48 | * @param id the allocation ID to stop 49 | * @param signal the signal to send 50 | * @param task the name of the task, required if the task group has more than one task 51 | * @see [[https://nomadproject.io/api-docs/allocations/#signal-allocation `PUT /v1/allocation/{ID}/signal`]] 52 | */ 53 | def signal(id: String, signal: String, task: Option[String] = None): Unit = 54 | allocationsApi.signal(id, signal, task.orNull) 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaClientApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import java.io.InputStream 4 | 5 | import scala.collection.JavaConverters._ 6 | 7 | import com.hashicorp.nomad.apimodel._ 8 | import com.hashicorp.nomad.javasdk._ 9 | 10 | /** API for interacting with a particular Nomad client, 11 | * exposing the functionality of the `/v1/client/…` endpoints of the 12 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 13 | * 14 | * @param clientApi the underlying Java SDK AgentApi 15 | */ 16 | class ScalaClientApi private[scalasdk](clientApi: ClientApi) { 17 | 18 | /** Queries the actual resource usage of the client node. 19 | * 20 | * @see [[https://www.nomadproject.io/docs/http/client-stats.html `GET /v1/client/stats`]] 21 | */ 22 | def stats(): NomadResponse[HostStats] = 23 | clientApi.stats() 24 | 25 | /** Queries the resource usage of an allocation running on the client node. 26 | * 27 | * @param allocationId ID of the allocation to lookup 28 | * @see [[https://www.nomadproject.io/docs/http/client-allocation-stats.html `GET /v1/client/allocation/{ID}/stats`]] 29 | */ 30 | def stats(allocationId: String): NomadResponse[AllocResourceUsage] = 31 | clientApi.stats(allocationId) 32 | 33 | /** Reads the contents of a file in an allocation directory. 34 | * 35 | * @param allocationId ID of the allocation that produced the file 36 | * @param path the path of the file relative to the root of the allocation directory 37 | * @see [[https://www.nomadproject.io/docs/http/client-fs.html `GET /v1/client/fs/cat/{Allocation-ID}`]] 38 | */ 39 | def cat(allocationId: String, path: String): NomadResponse[String] = 40 | clientApi.cat(allocationId, path) 41 | 42 | /** Reads the contents of a file in an allocation directory at a particular offset. 43 | * 44 | * @param allocationId ID of the allocation that produced the file 45 | * @param path the path of the file relative to the root of the allocation directory 46 | * @param offset the byte offset from where content will be read 47 | * @param limit the number of bytes to read from the offset 48 | * @see [[https://www.nomadproject.io/docs/http/client-fs.html `GET /v1/client/fs/readat/{Allocation-ID}`]] 49 | */ 50 | def readAt(allocationId: String, path: String, offset: Long, limit: Long): NomadResponse[String] = 51 | clientApi.readAt(allocationId, path, offset, limit) 52 | 53 | /** Streams the contents of a file in an allocation directory. 54 | *

55 | * The stream handler's [[StreamHandler#handleFrame]] method will be called repeatedly with stream events, 56 | * until the [[StreamHandler#isDone]] method returns false. 57 | *

58 | * In the event of an error, the stream handler's [[StreamHandler#handleThrowable]] method will be invoked. 59 | *

60 | * Note that unless there is an error, the streaming connection to the client node will remain open until the stream 61 | * handler's isDone method returns true, even if the allocation has completed. 62 | *

63 | * To retrieve the contents of a file without the complexity of streaming, use the [[#cat]] method instead. 64 | * 65 | * @param allocationId the ID of the allocation that produced the file 66 | * @param path the path of the file relative to the root of the allocation directory 67 | * @param offset the byte offset at which to start streaming 68 | * @param origin null or "start" indicate the the offset is relative to the beginning of the file, 69 | * "end" indicates that the offset is relative to end of the file. 70 | * @return a FramedStream that can be used to read the frames in the stream. 71 | * @see [[https://www.nomadproject.io/docs/http/client-fs.html `GET /v1/client/fs/stream/{Allocation-ID}`]] 72 | */ 73 | def stream(allocationId: String, path: String, offset: Option[Long] = None, origin: Option[String] = None): FramedStream = 74 | clientApi.stream(allocationId, path, offset.map(long2Long).orNull, origin.orNull) 75 | 76 | /** Streams a task's stdout or stderr log. 77 | *

78 | * Note that if follow is true, then unless there is an error, the streaming connection to the client node will 79 | * remain open until the stream handler's isDone method returns true, even if the allocation has completed. 80 | * 81 | * @param allocationId the ID of the allocation that produced the log 82 | * @param taskName the name of the task that produced the log 83 | * @param follow if true, the stream remains open even after the end of the log has been reached 84 | * @param logType "stdout" or "stderr" 85 | * @return a FramedStream that can be used to read the frames in the stream. 86 | * @see [[https://www.nomadproject.io/docs/http/client-fs.html `GET /v1/client/fs/logs/{Allocation-ID}`]] 87 | */ 88 | def logs(allocationId: String, taskName: String, follow: Boolean, logType: String): InputStream = 89 | clientApi.logs(allocationId, taskName, follow, logType) 90 | 91 | /** Streams a task's stdout or stderr log. 92 | *

93 | * Note that if follow is true, then unless there is an error, the streaming connection to the client node will 94 | * remain open until the stream handler's isDone method returns true, even if the allocation has completed. 95 | * 96 | * @param allocationId the ID of the allocation that produced the log 97 | * @param taskName the name of the task that produced the log 98 | * @param follow if true, the stream remains open even after the end of the log has been reached 99 | * @param logType "stdout" or "stderr" 100 | * @return a FramedStream that can be used to read the frames in the stream. 101 | * @see [[https://www.nomadproject.io/docs/http/client-fs.html `GET /v1/client/fs/logs/{Allocation-ID}`]] 102 | */ 103 | def logsAsFrames(allocationId: String, taskName: String, follow: Boolean, logType: String): FramedStream = 104 | clientApi.logsAsFrames(allocationId, taskName, follow, logType) 105 | 106 | /** Lists the files in an allocation directory. 107 | * 108 | * @param allocationId ID of the allocation that owns the directory 109 | * @param path the path relative to the root of the allocation directory 110 | * @see [[https://www.nomadproject.io/docs/http/client-fs.html `GET /v1/client/fs/ls/{Allocation-ID}`]] 111 | */ 112 | def ls(allocationId: String, path: String): NomadResponse[Seq[AllocFileInfo]] = 113 | clientApi.ls(allocationId, path) 114 | .map(_.asScala) 115 | 116 | /** Stat a file in an allocation directory. 117 | * 118 | * @param allocationId ID of the allocation that owns the file 119 | * @param path the path relative to the root of the allocation directory 120 | * @see [[https://www.nomadproject.io/docs/http/client-fs.html `GET /v1/client/fs/stat/{Allocation-ID}`]] 121 | */ 122 | def stat(allocationId: String, path: String): NomadResponse[AllocFileInfo] = 123 | clientApi.stat(allocationId, path) 124 | } 125 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaDeploymentsApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{ AllocationListStub, Deployment, DeploymentUpdateResponse } 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** API for querying for information about deployments, 9 | * exposing the [[https://www.nomadproject.io/api/deployments.html deployments]] functionality of the 10 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 11 | * 12 | * @param deploymentsApi the underlying Java SDK DeploymentsApi 13 | */ 14 | class ScalaDeploymentsApi(deploymentsApi: DeploymentsApi) { 15 | 16 | /** Lists deployments in the active region. 17 | * 18 | * @param deploymentIdPrefix an even-length prefix that, if given, 19 | * restricts the results to only deployments having an ID with this prefix 20 | * @param options options controlling how the request is performed 21 | * @see [[https://www.nomadproject.io/api/deployments.html#list-deployments `GET /v1/deployments`]] 22 | */ 23 | def list(deploymentIdPrefix: Option[String] = None, options: Option[ScalaQueryOptions[Seq[Deployment]]] = None): ServerQueryResponse[Seq[Deployment]] = 24 | deploymentsApi.list(deploymentIdPrefix.orNull, options.asJava(_.asScala)) 25 | .map(_.asScala) 26 | 27 | 28 | /** Queries a deployment in the active region. 29 | * 30 | * @param deploymentId ID of the deployment to lookup 31 | * @param options options controlling how the request is performed 32 | * @see [[https://www.nomadproject.io/api/deployments.html#read-deployment `GET /v1/deployment/{ID}`]] 33 | */ 34 | @throws[NomadException] 35 | def info(deploymentId: String, options: Option[ScalaQueryOptions[Deployment]] = None): ServerQueryResponse[Deployment] = 36 | deploymentsApi.info(deploymentId, options.asJava) 37 | 38 | /** Lists the allocations belonging to a deployment in the active region. 39 | * 40 | * @param deploymentId the ID of the deployment to list allocations for 41 | * @param options options controlling how the request is performed 42 | * @see [[https://www.nomadproject.io/api/deployments.html#list-allocations-for-deployment `GET /v1/deployment//allocations`]] 43 | */ 44 | def allocations(deploymentId: String, options: Option[ScalaQueryOptions[Seq[AllocationListStub]]]): ServerQueryResponse[Seq[AllocationListStub]] = 45 | deploymentsApi.allocations(deploymentId, options.asJava(_.asScala)) 46 | .map(_.asScala) 47 | 48 | /** Fails a deployment in the active region. 49 | * 50 | * @param deploymentId the ID of the deployment to list allocations for 51 | * @param options options controlling how the request is performed 52 | * @see [[https://www.nomadproject.io/api/deployments.html#fail-deployment `PUT /v1/deployment/fail/`]] 53 | */ 54 | def fail(deploymentId: String, options: Option[WriteOptions] = None): ServerResponse[DeploymentUpdateResponse] = 55 | deploymentsApi.fail(deploymentId, options.orNull) 56 | 57 | /** Pauses or un-pauses a deployment in the active region. 58 | * 59 | * @param deploymentId the ID of the deployment to list allocations for 60 | * @param pause true if the deployment should be paused, false if it should be un-paused 61 | * @param options options controlling how the request is performed 62 | * @see [[https://www.nomadproject.io/api/deployments.html#pause-deployment `PUT /v1/deployment/pause/`]] 63 | */ 64 | def pause(deploymentId: String, pause: Boolean, options: Option[WriteOptions] = None): ServerResponse[DeploymentUpdateResponse] = 65 | deploymentsApi.pause(deploymentId: String, pause, options.orNull) 66 | 67 | /** Promotes the canaries in the provided groups of a deployment in the active region. 68 | * 69 | * @param deploymentId the ID of the deployment to list allocations for 70 | * @param groups when specified, only canaries in these groups will be promoted 71 | * @param options options controlling how the request is performed 72 | * @see [[https://www.nomadproject.io/api/deployments.html#promote-deployment `PUT /v1/deployment/promote/`]] 73 | */ 74 | def promote(deploymentId: String, groups: Option[Seq[String]] = None, options: Option[WriteOptions] = None): ServerResponse[DeploymentUpdateResponse] = 75 | groups match { 76 | case None => deploymentsApi.promoteAll(deploymentId, options.orNull) 77 | case Some(groups) => deploymentsApi.promoteGroups(deploymentId, groups.asJava, options.orNull) 78 | } 79 | 80 | /** 81 | * Sets the health of allocations that are part of a deployment. 82 | * 83 | * @param deploymentId the ID of the deployment to list allocations for 84 | * @param healthy ids of allocations to be set healthy 85 | * @param unhealthy ids of allocations to be set unhealthy 86 | * @param options options controlling how the request is performed 87 | * @see [[https://www.nomadproject.io/api/deployments.html#set-allocation-health-in-deployment `PUT /v1/deployment/allocation-health/`]] 88 | */ 89 | def setAllocHealth( 90 | deploymentId: String, 91 | healthy: Seq[String], 92 | unhealthy: Seq[String], 93 | options: Option[WriteOptions] = None 94 | ): ServerResponse[DeploymentUpdateResponse] = 95 | deploymentsApi.setAllocHealth(deploymentId, healthy.asJava, unhealthy.asJava, options.orNull) 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaEvaluationsApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{AllocationListStub, Evaluation} 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** API for querying for information about evaluations, 9 | * exposing the functionality of the `/v1/evaluations` and `/v1/evaluation` endpoints of the 10 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 11 | * 12 | * @param evaluationsApi the underlying API from the Java SDK 13 | */ 14 | class ScalaEvaluationsApi(evaluationsApi: EvaluationsApi) { 15 | 16 | /** Queries an evaluation in the active region. 17 | * 18 | * @param evaluationId ID of the evaluation to lookup 19 | * @param options options controlling how the request is performed 20 | * @see [[https://www.nomadproject.io/docs/http/eval.html `GET /v1/evaluation/{ID}`]] 21 | */ 22 | def info(evaluationId: String, options: Option[ScalaQueryOptions[Evaluation]] = None): ServerQueryResponse[Evaluation] = 23 | evaluationsApi.info(evaluationId, options.asJava) 24 | 25 | /** Lists evaluations in the active region. 26 | * 27 | * @param evaluationIdPrefix an even-length prefix that, if given, 28 | * restricts the results to only evaluations having an ID with this prefix 29 | * @param options options controlling how the request is performed 30 | * @see [[https://www.nomadproject.io/docs/http/evals.html `GET /v1/evaluations`]] 31 | */ 32 | def list( 33 | evaluationIdPrefix: Option[String] = None, 34 | options: Option[ScalaQueryOptions[Seq[Evaluation]]] = None 35 | ): ServerQueryResponse[Seq[Evaluation]] = 36 | evaluationsApi.list(evaluationIdPrefix.orNull, options.asJava(_.asScala)) 37 | .map(_.asScala) 38 | 39 | /** Lists allocations created or modified an evaluation in the active region. 40 | * 41 | * @param evaluationId ID of the evaluation that created or modified the allocations 42 | * @param options options controlling how the request is performed 43 | * @see [[https://www.nomadproject.io/docs/http/evals.html `GET /v1/evaluation//allocations`]] 44 | */ 45 | def allocations( 46 | evaluationId: String, 47 | options: Option[ScalaQueryOptions[Seq[AllocationListStub]]] = None 48 | ): ServerQueryResponse[Seq[AllocationListStub]] = 49 | evaluationsApi.allocations(evaluationId, options.asJava(_.asScala)) 50 | .map(_.asScala) 51 | 52 | /** Poll the server until an evaluation has completed. 53 | * 54 | * @param evaluationId ID of the evaluation to poll for 55 | * @param waitStrategy the wait strategy to use during polling 56 | */ 57 | def pollForCompletion(evaluationId: String, waitStrategy: WaitStrategy): ServerQueryResponse[Evaluation] = 58 | evaluationsApi.pollForCompletion(evaluationId, waitStrategy) 59 | 60 | /** Poll the server until an evaluation has completed. 61 | * 62 | * @param evaluation an EvaluationResponse containing the ID of the evaluation to poll for 63 | * @param waitStrategy the wait strategy to use during polling 64 | */ 65 | def pollForCompletion(evaluation: EvaluationResponse, waitStrategy: WaitStrategy): ServerQueryResponse[Evaluation] = 66 | pollForCompletion(evaluation.getValue, waitStrategy) 67 | } 68 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaJobsApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import java.math.BigInteger 4 | 5 | import scala.collection.JavaConverters._ 6 | import com.hashicorp.nomad.apimodel._ 7 | import com.hashicorp.nomad.javasdk._ 8 | 9 | /** API for managing and querying jobs, 10 | * exposing the functionality of the `/v1/jobs` and `/v1/job` endpoints of the 11 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 12 | * 13 | * @param jobsApi the underlying API from the Java SDK 14 | * @see [[https://www.nomadproject.io/docs/http/json-jobs.html Job Specification]] 15 | * for documentation about the [[Job]] structure. 16 | */ 17 | class ScalaJobsApi(jobsApi: JobsApi) { 18 | 19 | /** Lists the allocations belonging to a job in the active region. 20 | * 21 | * @param jobId the ID of the job to list allocations for 22 | * @param options options controlling how the request is performed 23 | * @see [[https://www.nomadproject.io/docs/http/job.html `GET /v1/job//allocations`]] 24 | */ 25 | def allocations(jobId: String, options: Option[ScalaQueryOptions[Seq[AllocationListStub]]] = None): ServerQueryResponse[Seq[AllocationListStub]] = 26 | jobsApi.allocations(jobId, options.asJava(_.asScala)) 27 | .map(_.asScala) 28 | 29 | /** 30 | * Lists the deployments belonging to a job in the active region. 31 | * 32 | * @param jobId the ID of the job to list deployments for 33 | * @param options options controlling how the request is performed 34 | * @see {@code GET /v1/job//deployments} 35 | */ 36 | def deployments(jobId: String, 37 | options: Option[ScalaQueryOptions[Seq[Deployment]]] = None): ServerQueryResponse[Seq[Deployment]] = 38 | jobsApi.deployments(jobId, options.asJava(_.asScala)).map(_.asScala) 39 | 40 | /** Deregisters a job in the active region, 41 | * and stops all allocations that are part of it. 42 | * 43 | * @param jobId the ID of the job to deregister 44 | * @param purge If true, the job is deregistered and purged from the system versus still being queryable and 45 | * eventually GC'ed from the system. Most callers should not specify purge. 46 | * @param options options controlling how the request is performed 47 | * @see [[https://www.nomadproject.io/docs/http/job.html#delete `DELETE /v1/job/`]] 48 | */ 49 | def deregister(jobId: String, purge: Boolean = false, options: Option[WriteOptions] = None): EvaluationResponse = 50 | jobsApi.deregister(jobId, purge, options.orNull) 51 | 52 | /** Dispatches a new instance of a parameterized job in the active region. 53 | * 54 | * @param jobId id of the parameterized job to instantiate 55 | * @param meta metadata for the instantiated job 56 | * @param payload payload for the instantiated job 57 | * @param options options controlling how the request is performed 58 | * @see {@code PUT /v1/job//dispatch} 59 | */ 60 | def dispatch(jobId: String, meta: Option[Map[String,String]] = None, 61 | payload: Option[Array[Byte]] = None, options: Option[WriteOptions] = None): ServerResponse[JobDispatchResponse] = 62 | jobsApi.dispatch(jobId, meta.map(_.asJava).orNull, payload.orNull, options.orNull) 63 | 64 | /** Lists the evaluations belonging to a job in the active region. 65 | * 66 | * @param jobId the ID of the job to list evaluations for 67 | * @param options options controlling how the request is performed 68 | * @see [[https://www.nomadproject.io/docs/http/job.html `GET /v1/job//evaluations`]] 69 | */ 70 | def evaluations(jobId: String, options: Option[ScalaQueryOptions[Seq[Evaluation]]] = None): ServerQueryResponse[Seq[Evaluation]] = 71 | jobsApi.evaluations(jobId, options.asJava(_.asScala)) 72 | .map(_.asScala) 73 | 74 | /** Creates a new evaluation for a job in the active region. 75 | * 76 | * This can be used to force run the scheduling logic if necessary. 77 | * 78 | * @param jobId the ID of the job to evaluate 79 | * @param options options controlling how the request is performed 80 | * @see [[https://www.nomadproject.io/docs/http/job.html `PUT /v1/job//evaluate`]] 81 | */ 82 | def forceEvaluate(jobId: String, options: Option[WriteOptions] = None): EvaluationResponse = 83 | jobsApi.forceEvaluate(jobId, options.orNull) 84 | 85 | /** Queries a job in the active region. 86 | * 87 | * @param jobId the ID of the job to query 88 | * @param options options controlling how the request is performed 89 | * @see [[https://www.nomadproject.io/docs/http/job.html `GET /v1/job/{ID}`]] 90 | */ 91 | def info(jobId: String, options: Option[ScalaQueryOptions[Job]] = None): ServerQueryResponse[Job] = 92 | jobsApi.info(jobId, options.asJava) 93 | 94 | /** Gets the latest deployment belonging to a job. 95 | * 96 | * @param jobId the ID of the job 97 | * @param options options controlling how the request is performed 98 | * @see [[https://www.nomadproject.io/api/jobs.html#read-job-39-s-most-recent-deployment `GET /v1/job//deployment`]] 99 | */ 100 | def latestDeployment(jobId: String, options: Option[ScalaQueryOptions[Deployment]] = None): ServerQueryResponse[Deployment] = 101 | jobsApi.latestDeployment(jobId, options.asJava) 102 | 103 | /** Lists jobs in the active region. 104 | * 105 | * @param jobIdPrefix an even-length prefix that, if given, 106 | * restricts the results to only jobs having an ID with this prefix 107 | * @param options options controlling how the request is performed 108 | * @see [[https://www.nomadproject.io/docs/http/jobs.html `GET /v1/jobs`]] 109 | */ 110 | def list(jobIdPrefix: Option[String] = None, options: Option[ScalaQueryOptions[Seq[JobListStub]]] = None): ServerQueryResponse[Seq[JobListStub]] = 111 | jobsApi.list(jobIdPrefix.orNull, options.asJava(_.asScala)) 112 | .map(_.asScala) 113 | 114 | /** Forces a new instance of a periodic job in the active region. 115 | *

116 | * A new instance will be created even if it violates the job's prohibit_overlap settings. 117 | * As such, this should be only used to immediately run a periodic job. 118 | * 119 | * @param jobId the ID of the job to force a run of 120 | * @param options options controlling how the request is performed 121 | * @see [[https://www.nomadproject.io/docs/http/job.html `PUT /v1/job/{ID}/periodic/force`]] 122 | */ 123 | def periodicForce(jobId: String, options: Option[WriteOptions] = None): EvaluationResponse = 124 | jobsApi.periodicForce(jobId, options.orNull) 125 | 126 | /** Invokes a dry-run of the scheduler for a job in the active region. 127 | *

128 | * Can be used together with the modifyIndex parameter of [[register]] 129 | * to inspect what will happen before registering a job. 130 | * 131 | * @param job detailed specification of the job to plan for 132 | * @param diff indicates whether a diff between the current and submitted versions of the job 133 | * should be included in the response. 134 | * @param policyOverride If set, any soft mandatory Sentinel policies will be overriden. 135 | * This allows a job to be registered when it would be denied by policy. 136 | * @param options options controlling how the request is performed 137 | * @see [[https://www.nomadproject.io/intro/getting-started/jobs.html#modifying-a-job Modifying a Job]] 138 | * @see [[https://www.nomadproject.io/docs/http/job.html `PUT /v1/job/{ID}/periodic/force`]] 139 | */ 140 | def plan(job: Job, diff: Boolean, policyOverride: Boolean = false, options: Option[WriteOptions] = None): ServerResponse[JobPlanResponse] = 141 | jobsApi.plan(job, diff, policyOverride, options.orNull) 142 | 143 | /** Registers or updates a job in the active region. 144 | * 145 | * @param job detailed specification of the job to register 146 | * @param modifyIndex when specified, the registration is only performed if the job's modify index matches. 147 | * This can be used to make sure the job hasn't changed since getting a [[plan]]. 148 | * @param policyOverride If true, any soft mandatory Sentinel policies will be overriden. 149 | * This allows a job to be registered when it would be denied by policy. 150 | * @param options options controlling how the request is performed 151 | * @see [[https://www.nomadproject.io/docs/http/jobs.html#put-post `PUT /v1/jobs`]] 152 | */ 153 | def register(job: Job, modifyIndex: Option[BigInteger] = None, policyOverride: Boolean = false, options: Option[WriteOptions] = None): EvaluationResponse = 154 | jobsApi.register(job, modifyIndex.orNull, policyOverride, options.orNull) 155 | 156 | /** Reverts to a prior version of a job. 157 | * 158 | * @param jobId ID of the job 159 | * @param version the version to revert to 160 | * @param priorVersion when set, the job is only reverted if the job's current version matches this prior version 161 | * @param options options controlling how the request is performed 162 | * @see [[https://www.nomadproject.io/api/jobs.html#revert-to-older-job-version `PUT /v1/job/{ID}/revert`]] 163 | */ 164 | def revert(jobId: String, version: BigInteger, priorVersion: Option[BigInteger] = None, options: Option[WriteOptions] = None): EvaluationResponse = 165 | jobsApi.revert(jobId, version, priorVersion.orNull, options.orNull) 166 | 167 | /** 168 | * Marks a version of a job as stable or unstable. 169 | * 170 | * @param jobId ID of the job 171 | * @param version the job version to affect 172 | * @param stable whether the job is stable or unstable 173 | * @param options options controlling how the request is performed 174 | * @see [[https://www.nomadproject.io/api/jobs.html#set-job-stability `PUT /v1/job/{ID}/stable`]] 175 | */ 176 | def stable(jobId: String, version: BigInteger, stable: Boolean, options: Option[WriteOptions] = None): EvaluationResponse = 177 | jobsApi.stable(jobId, version, stable, options.orNull) 178 | 179 | /** Queries the summary of a job in the active region. 180 | * 181 | * @param jobId ID of the job to get a summary for 182 | * @param options options controlling how the request is performed 183 | * @see [[https://www.nomadproject.io/docs/http/job.html `GET /v1/job/{ID}/summary`]] 184 | */ 185 | def summary(jobId: String, options: Option[ScalaQueryOptions[JobSummary]] = None): ServerQueryResponse[JobSummary] = 186 | jobsApi.summary(jobId, options.asJava) 187 | 188 | /** 189 | * Validates a job. 190 | * 191 | * @param job the job to validate 192 | * @param options options controlling how the request is performed 193 | * @see [[https://www.nomadproject.io/api/validate.html#validate-job `PUT /v1/validate/job`]] 194 | */ 195 | def validate(job: Job, options: Option[WriteOptions] = None): ServerResponse[JobValidateResponse] = 196 | jobsApi.validate(job, options.orNull) 197 | 198 | /** 199 | * Lists the versions of a job. 200 | * 201 | * @param jobId ID of the job 202 | * @param diffs when true, diffs are returned in addition the the job versions 203 | * @param options options controlling how the request is performed 204 | * @see [[https://www.nomadproject.io/api/jobs.html#list-job-versions `GET /v1/job/{ID}/versions`]] 205 | */ 206 | def versions( 207 | jobId: String, 208 | diffs: Boolean = false, 209 | options: Option[ScalaQueryOptions[JobVersionsResponseData]] = None 210 | ): ServerQueryResponse[JobVersionsResponseData] = 211 | jobsApi.versions(jobId, diffs, options.asJava) 212 | 213 | } 214 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaNamespacesApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.Namespace 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** 9 | * API for querying for information about namespaces, 10 | * exposing the [[https://www.nomadproject.io/api/namespaces.html namespaces]] functionality of the 11 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 12 | * 13 | * @param namespacesApi the underlying Java SDK NamespacesApi 14 | */ 15 | class ScalaNamespacesApi(namespacesApi: NamespacesApi) { 16 | 17 | /** 18 | * Deletes a namespace. 19 | * 20 | * @param namespaceId the ID of the namespace to delete 21 | * @param options options controlling how the request is performed 22 | * @see [[https://www.nomadproject.io/docs/http/namespaces.html#delete-namespace `DELETE /v1/namespace/:id`]] 23 | */ 24 | def delete(namespaceId: String, options: Option[WriteOptions] = None): ServerResponse[Unit] = 25 | namespacesApi.delete(namespaceId, options.orNull) 26 | .map((_: Void) => ()) 27 | 28 | /** 29 | * Queries a namespace. 30 | * 31 | * @param name name of the namespace. 32 | * @param options options controlling how the request is performed 33 | * @see [[https://www.nomadproject.io/docs/http/namespaces.html#read-namespace `GET /v1/namespace/:id`]] 34 | */ 35 | def info(name: String, options: Option[ScalaQueryOptions[Namespace]] = None): ServerQueryResponse[Namespace] = 36 | namespacesApi.info(name, options.asJava) 37 | 38 | /** 39 | * Lists namespaces. 40 | * 41 | * @param namePrefix a name prefix that, if given, 42 | * restricts the results to only namespaces having a name with this prefix 43 | * @param options options controlling how the request is performed 44 | * @see [[https://www.nomadproject.io/docs/http/namespaces.html#list-namespaces `GET /v1/namespaces`]] 45 | */ 46 | def list(namePrefix: Option[String] = None, options: Option[ScalaQueryOptions[Seq[Namespace]]] = None): ServerQueryResponse[Seq[Namespace]] = 47 | namespacesApi.list(namePrefix.orNull, options.asJava(_.asScala)) 48 | .map(_.asScala) 49 | 50 | /** 51 | * Registers or updates a namespace. 52 | * 53 | * @param namespace the namespace to register 54 | * @param options options controlling how the request is performed 55 | * @see [[https://www.nomadproject.io/docs/http/namespaces.html#create-or-update-a-namespace `PUT /v1/namespace`]] 56 | */ 57 | def register(namespace: Namespace, options: Option[WriteOptions] = None): ServerResponse[Unit] = 58 | namespacesApi.register(namespace, options.orNull) 59 | .map((_: Void) => ()) 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaNodesApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{ AllocationListStub, Node, NodeListStub } 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** API for querying for information about client nodes, 9 | * exposing the functionality of the `/v1/nodes` and `/v1/node` endpoints of the 10 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 11 | * 12 | * @param nodesApi the underlying API from the Java SDK 13 | */ 14 | class ScalaNodesApi(nodesApi: NodesApi) { 15 | 16 | /** List the allocations belonging to a nodes in the active region. 17 | * 18 | * @param nodeId ID of the node to list allocations for 19 | * @param options options controlling how the request is performed 20 | * @see [[https://www.nomadproject.io/docs/http/node.html `GET /v1/node/{ID}/allocations`]] 21 | */ 22 | def allocations(nodeId: String, options: Option[ScalaQueryOptions[Seq[AllocationListStub]]] = None): ServerQueryResponse[Seq[AllocationListStub]] = 23 | nodesApi.allocations(nodeId, options.asJava(_.asScala)) 24 | .map(_.asScala) 25 | 26 | /** Creates a new evaluation for a node. 27 | * 28 | * @param nodeId ID of the node to evaluate 29 | * @param options options controlling how the request is performed 30 | * @see [[https://www.nomadproject.io/docs/http/node.html `PUT /v1/node//evaluate`]] 31 | */ 32 | def forceEvaluate(nodeId: String, options: Option[WriteOptions] = None): ServerResponse[Unit] = 33 | nodesApi.forceEvaluate(nodeId, options.orNull) 34 | .map((_: Void) => ()) 35 | 36 | /** Queries a node in the active region. 37 | * 38 | * @param nodeId ID of the node to query 39 | * @param options options controlling how the request is performed 40 | * @see [[https://www.nomadproject.io/docs/http/node.html `GET /v1/node/{ID}`]] 41 | */ 42 | def info(nodeId: String, options: Option[ScalaQueryOptions[Node]] = None): ServerQueryResponse[Node] = 43 | nodesApi.info(nodeId, options.asJava) 44 | 45 | /** Lists client nodes in the active region. 46 | * 47 | * @param nodeIdPrefix an even-length prefix that, if given, 48 | * restricts the results to only nodes having an ID with this prefix 49 | * @param options options controlling how the request is performed 50 | * @see [[https://www.nomadproject.io/docs/http/nodes.html `GET /v1/nodes`]] 51 | */ 52 | def list( 53 | nodeIdPrefix: Option[String] = None, 54 | options: Option[ScalaQueryOptions[Seq[NodeListStub]]] = None): ServerQueryResponse[Seq[NodeListStub]] = 55 | nodesApi.list(nodeIdPrefix.orNull, options.asJava(_.asScala)) 56 | .map(_.asScala) 57 | 58 | /** Toggles drain mode on or off on a node in the active region. 59 | *

60 | * When drain mode is enabled, no further allocations will be assigned and existing allocations will be migrated. 61 | * 62 | * @param nodeId ID of the node to control 63 | * @param enabled drain mode is turned on when this is true, and off when false. 64 | * @param options options controlling how the request is performed 65 | * @see [[https://www.nomadproject.io/docs/http/node.html#put-post `PUT /v1/node/{ID}/drain`]] 66 | */ 67 | def toggleDrain(nodeId: String, enabled: Boolean, options: Option[WriteOptions] = None): ServerResponse[Unit] = 68 | nodesApi.toggleDrain(nodeId, enabled, options.orNull) 69 | .map(_ => ()) 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaOperatorApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import java.lang 4 | import java.math.BigInteger 5 | 6 | import com.hashicorp.nomad.apimodel._ 7 | import com.hashicorp.nomad.javasdk._ 8 | 9 | /** API for operating a Nomad cluster, 10 | * exposing the [[https://www.nomadproject.io/api/operator.html operator]] functionality of the 11 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 12 | * 13 | * @param operatorApi the underlying Java SDK OperatorApi 14 | */ 15 | class ScalaOperatorApi(operatorApi: OperatorApi) { 16 | 17 | /** Gets the cluster's Raft configuration. 18 | * 19 | * @param options options controlling how the request is performed 20 | * @see [[https://www.nomadproject.io/api/operator.html#read-raft-configuration `GET /v1/operator/raft/configuration`]] 21 | */ 22 | def raftGetConfiguration(options: Option[ScalaQueryOptions[RaftConfiguration]] = None): NomadResponse[RaftConfiguration] = 23 | operatorApi.raftGetConfiguration(options.asJava) 24 | 25 | /** 26 | * Removes a raft peer from the cluster. 27 | * 28 | * @param address ip:port address of the peer to remove 29 | * @param options options controlling how the request is performed 30 | * @see [[https://www.nomadproject.io/api/operator.html#remove-raft-peer `DELETE /v1/operator/raft/peer`]] 31 | */ 32 | def raftRemovePeerByAddress(address: String, options: Option[WriteOptions] = None): NomadResponse[Unit] = 33 | operatorApi.raftRemovePeerByAddress(address, options.orNull) 34 | .map((_: Void) => ()) 35 | 36 | /** Gets the health of the autopilot status. 37 | * 38 | * @param options options controlling how the request is performed 39 | * @see {@code GET /v1/operator/autopilot/health} 40 | */ 41 | def getHealth(options: Option[ScalaQueryOptions[OperatorHealthReply]] = None): NomadResponse[OperatorHealthReply] = 42 | operatorApi.getHealth(options.asJava) 43 | 44 | /** Gets the autopilot configuration. 45 | * 46 | * @param options options controlling how the request is performed 47 | * @see {@code GET /v1/operator/autopilot/configuration} 48 | */ 49 | def getAutopilotConfiguration(options: Option[ScalaQueryOptions[AutopilotConfiguration]] = None): NomadResponse[AutopilotConfiguration] = 50 | operatorApi.getAutopilotConfiguration(options.asJava) 51 | 52 | /** Updates the autopilot configuration. 53 | * 54 | * @param autopilotConfiguration the desired autopilot configuration 55 | * @param options options controlling how the request is performed 56 | * @see {@code PUT /v1/operator/autopilot/configuration} 57 | */ 58 | def updateAutopilotConfiguration(autopilotConfiguration: AutopilotConfiguration, 59 | options: Option[WriteOptions] = None): NomadResponse[lang.Boolean] = 60 | operatorApi.updateAutopilotConfiguration(autopilotConfiguration, options.orNull) 61 | 62 | /** Gets the scheduler configuration. 63 | * 64 | * @param options options controlling how the request is performed 65 | * @see {@code GET /v1/operator/scheduler/configuration} 66 | */ 67 | def getSchedulerConfiguration(options: Option[ScalaQueryOptions[SchedulerConfigurationResponse]] = None): NomadResponse[SchedulerConfigurationResponse] = 68 | operatorApi.getSchedulerConfiguration(options.asJava) 69 | 70 | /** Updates the scheduler configuration. 71 | * 72 | * @param schedulerConfiguration the desired scheduler configuration 73 | * @param options options controlling how the request is performed 74 | * @param cas if not null, use check-and-set semantics on the update 75 | * @see {@code PUT /v1/operator/scheduler/configuration} 76 | */ 77 | def updateSchedulerConfiguration(schedulerConfiguration: SchedulerConfiguration, 78 | options: Option[WriteOptions] = None, 79 | cas: Option[BigInteger] = None ): NomadResponse[SchedulerSetConfigurationResponse] = 80 | operatorApi.updateSchedulerConfiguration(schedulerConfiguration, options.orNull, cas.orNull) 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaQueryOptions.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import java.math.BigInteger 4 | 5 | import com.hashicorp.nomad.javasdk.{ Predicate, QueryOptions, ServerQueryResponse, WaitStrategy } 6 | 7 | /** Options for queries to a Nomad server API. 8 | * 9 | * @param region the region to which the request should be forwarded (when None the API's region setting is used) 10 | * @param namespace the namepspace the to use for the request (when None the API's namespace setting is used) 11 | * @param index the long-polling query index to use for blocking queries 12 | * @param waitStrategy the wait strategy to use for long-polling blocking queries 13 | * @param allowStale whether to allow stale responses 14 | * (see [[https://www.nomadproject.io/docs/http/index.html#consistency-modes Consistency Modes]]) 15 | * @param repeatedPollPredicate when specified, the server is repeatedly polled until the response satisfied the 16 | * predicate or the waitStrategy throws a TimeoutException. 17 | * @param authToken the secret ID of the ACL token to use for this request 18 | * @see [[https://www.nomadproject.io/docs/http/index.html#blocking-queries Blocking Queries]] 19 | * @tparam A the expected response type. 20 | */ 21 | case class ScalaQueryOptions[A]( 22 | region: Option[String] = None, 23 | namespace: Option[String] = None, 24 | index: Option[BigInteger] = None, 25 | waitStrategy: Option[WaitStrategy] = None, 26 | allowStale: Boolean = false, 27 | repeatedPollPredicate: Option[ServerQueryResponse[A] => Boolean] = None, 28 | authToken: Option[String] = None) { 29 | 30 | /** Returns Java [[QueryOptions]] equivalent to these options. 31 | * 32 | * @param f a function that maps a Java response value to its Scala equivalent 33 | * @tparam B the Java type representing the response value 34 | */ 35 | private[scalasdk] def asJava[B](f: B => A): QueryOptions[B] = { 36 | val javaOptions = new QueryOptions[B]() 37 | region.foreach(javaOptions.setRegion) 38 | namespace.foreach(javaOptions.setNamespace) 39 | index.foreach(javaOptions.setIndex) 40 | waitStrategy.foreach(javaOptions.setWaitStrategy) 41 | if (allowStale) javaOptions.setAllowStale(true) 42 | repeatedPollPredicate.foreach(p => javaOptions.setRepeatedPollPredicate(new Predicate[ServerQueryResponse[B]] { 43 | override def apply(r: ServerQueryResponse[B]): Boolean = 44 | p(new ServerQueryResponse(r.getHttpResponse, r.getRawEntity, f(r.getValue))) 45 | })) 46 | authToken.foreach(javaOptions.setAuthToken) 47 | javaOptions 48 | } 49 | 50 | /** Returns Java [[QueryOptions]] equivalent to these options, 51 | * assuming the Java and Scala representations of the response value are the same. 52 | */ 53 | private[scalasdk] def asJava: QueryOptions[A] = asJava(identity) 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaQuotasApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{ QuotaSpec, QuotaUsage } 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** 9 | * API for managing quotas, 10 | * exposing the [[https://www.nomadproject.io/api/quotas.html ACL policies]] functionality of the 11 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 12 | * 13 | * @param quotasApi the underlying Java SDK QuotasApi 14 | */ 15 | class ScalaQuotasApi(quotasApi: QuotasApi) { 16 | 17 | /** 18 | * Deletes a quota specification. 19 | * 20 | * @param quotaName the name of the quota to delete 21 | * @param options options controlling how the request is performed 22 | * @see [[https://www.nomadproject.io/api/quotas.html#delete-quota-specification `DELETE /v1/quota/:name`]] 23 | */ 24 | def delete(quotaName: String, options: Option[WriteOptions] = None): ServerResponse[Unit] = 25 | quotasApi.delete(quotaName, options.orNull) 26 | .map((_: Void) => ()) 27 | 28 | /** 29 | * Queries a quota specification. 30 | * 31 | * @param name name of the quota. 32 | * @param options options controlling how the request is performed 33 | * @see [[https://www.nomadproject.io/api/quotas.html#read-quota-specification `GET /v1/quota/:name`]] 34 | */ 35 | def info(name: String, options: Option[ScalaQueryOptions[QuotaSpec]] = None): ServerQueryResponse[QuotaSpec] = 36 | quotasApi.info(name, options.asJava) 37 | 38 | /** 39 | * Lists quota specifications. 40 | * 41 | * @param namePrefix a name prefix that, if given, 42 | * restricts the results to only quotas having a name with this prefix 43 | * @param options options controlling how the request is performed 44 | * @see [[https://www.nomadproject.io/api/quotas.html#list-quota-specifications `GET /v1/quotas`]] 45 | */ 46 | def list(namePrefix: Option[String] = None, options: Option[ScalaQueryOptions[Seq[QuotaSpec]]] = None): ServerQueryResponse[Seq[QuotaSpec]] = 47 | quotasApi.list(namePrefix.orNull, options.asJava(_.asScala)) 48 | .map(_.asScala) 49 | 50 | /** 51 | * Lists quota usages. 52 | * 53 | * @param namePrefix a name prefix that, if given, 54 | * restricts the results to only quotas having a name with this prefix 55 | * @param options options controlling how the request is performed 56 | * @see [[https://www.nomadproject.io/api/quotas.html#list-quota-usages `GET /v1/quota-usages`]] 57 | */ 58 | def listUsage(namePrefix: Option[String] = None, options: Option[ScalaQueryOptions[Seq[QuotaUsage]]] = None): ServerQueryResponse[Seq[QuotaUsage]] = 59 | quotasApi.listUsage(namePrefix.orNull, options.asJava(_.asScala)) 60 | .map(_.asScala) 61 | 62 | /** 63 | * Registers or updates a quota. 64 | * 65 | * @param quota the quota to register 66 | * @param options options controlling how the request is performed 67 | * @see [[https://www.nomadproject.io/api/quotas.html#create-or-update-quota-specification `PUT /v1/quota`]] 68 | */ 69 | def register(quota: QuotaSpec, options: Option[WriteOptions] = None): ServerResponse[Unit] = 70 | quotasApi.register(quota, options.orNull) 71 | .map((_: Void) => ()) 72 | 73 | /** 74 | * Queries a quota usage. 75 | * 76 | * @param name name of the quota. 77 | * @param options options controlling how the request is performed 78 | * @see [[https://www.nomadproject.io/api/quotas.html#read-quota-usage `GET /v1/quota/:name`]] 79 | */ 80 | def usage(name: String, options: Option[ScalaQueryOptions[QuotaUsage]] = None): ServerQueryResponse[QuotaUsage] = 81 | quotasApi.usage(name, options.asJava) 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaRegionsApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | import scala.collection.mutable 5 | import scala.concurrent.Future 6 | 7 | import com.hashicorp.nomad.javasdk.{NomadResponse, RegionsApi} 8 | 9 | /** API for querying for information about regions, 10 | * exposing the functionality of the `/v1/regions` endpoint of the 11 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 12 | * 13 | * @param regionsApi the underlying API from the Java SDK 14 | */ 15 | class ScalaRegionsApi(regionsApi: RegionsApi) { 16 | 17 | /** List the names of the known regions in the cluster. 18 | * 19 | * @see [[https://www.nomadproject.io/docs/http/regions.html `GET /v1/regions`]] 20 | */ 21 | def list(): NomadResponse[Seq[String]] = 22 | regionsApi.list() 23 | .map(_.asScala) 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaSearchApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import com.hashicorp.nomad.apimodel.SearchResponse 4 | import com.hashicorp.nomad.javasdk.{ SearchApi, ServerQueryResponse } 5 | 6 | /** API for performing searches in the Nomad cluster, 7 | * exposing the [[https://www.nomadproject.io/api/search.html search]] functionality of the 8 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 9 | * 10 | * @param searchApi the underlying Java SDK SearchApi 11 | */ 12 | class ScalaSearchApi(searchApi: SearchApi) { 13 | 14 | /** Returns a list of matches for a particular context and prefix. 15 | * 16 | * @param prefix items with this prefix are returned 17 | * @param context one of the following: allocs, deployment, evals, jobs, nodes, namespaces, quotas, all 18 | * @param options options controlling how the request is performed 19 | * @see [[https://www.nomadproject.io/api/search.html `PUT /v1/search`]] 20 | */ 21 | def prefixSearch(prefix: String, context: String, options: Option[ScalaQueryOptions[SearchResponse]] = None): ServerQueryResponse[SearchResponse] = 22 | searchApi.prefixSearch(prefix, context, options.asJava) 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaSentinelPoliciesApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import scala.collection.JavaConverters._ 4 | 5 | import com.hashicorp.nomad.apimodel.{ SentinelPolicy, SentinelPolicyListStub } 6 | import com.hashicorp.nomad.javasdk._ 7 | 8 | /** API for managing sentinel policies, 9 | * exposing the [[https://www.nomadproject.io/api/sentinel-policies.html sentinel policies]] functionality of the 10 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 11 | * 12 | * @param sentinelPoliciesApi the underlying Java SDK SentinelPoliciesApi 13 | */ 14 | class ScalaSentinelPoliciesApi(sentinelPoliciesApi: SentinelPoliciesApi) { 15 | 16 | /** 17 | * Deletes an sentinel policy. 18 | * 19 | * @param policyName name of the policy to delete 20 | * @param options options controlling how the request is performed 21 | * @see [[https://www.nomadproject.io/docs/http/sentinel-policies.html#delete-policy `DELETE /v1/sentinel/policy/:name`]] 22 | */ 23 | def delete(policyName: String, options: Option[WriteOptions] = None): ServerResponse[Unit] = 24 | sentinelPoliciesApi.delete(policyName, options.orNull) 25 | .map((_: Void) => ()) 26 | 27 | /** 28 | * Retrieves an sentinel policy. 29 | * 30 | * @param name name of the policy. 31 | * @param options options controlling how the request is performed 32 | * @see [[https://www.nomadproject.io/docs/http/sentinel-policies.html#read-policy `GET /v1/sentinel/policy/:name`]] 33 | */ 34 | def info(name: String, options: Option[ScalaQueryOptions[SentinelPolicy]] = None): ServerQueryResponse[SentinelPolicy] = 35 | sentinelPoliciesApi.info(name, options.asJava) 36 | 37 | /** 38 | * Lists sentinel policies. 39 | * 40 | * @param namePrefix a name prefix that, if given, 41 | * restricts the results to only policies having a name with this prefix 42 | * @param options options controlling how the request is performed 43 | * @see [[https://www.nomadproject.io/docs/http/sentinel-policies.html#list-policies `GET /v1/sentinel/policies`]] 44 | */ 45 | def list( 46 | namePrefix: Option[String] = None, 47 | options: Option[ScalaQueryOptions[Seq[SentinelPolicyListStub]]] = None 48 | ): ServerResponse[Seq[SentinelPolicyListStub]] = 49 | sentinelPoliciesApi.list(namePrefix.orNull, options.asJava(_.asScala)) 50 | .map(_.asScala) 51 | 52 | /** 53 | * Creates or updates an sentinel policy. 54 | * 55 | * @param policy the policy 56 | * @param options options controlling how the request is performed 57 | * @see [[https://www.nomadproject.io/docs/http/sentinel-policies.html#create-or-update-policy `PUT /v1/sentinel/policy/:name`]] 58 | */ 59 | def upsert(policy: SentinelPolicy, options: Option[WriteOptions] = None): ServerResponse[Unit] = 60 | sentinelPoliciesApi.upsert(policy, options.orNull) 61 | .map((_: Void) => ()) 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaStatusApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import com.hashicorp.nomad.javasdk.{NomadResponse, StatusApi} 4 | import scala.collection.JavaConverters._ 5 | import scala.collection.mutable 6 | import scala.concurrent.Future 7 | 8 | /** API for querying for information about the status of the cluster, 9 | * exposing the functionality of the `/v1/status/…` endpoints of the 10 | * [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 11 | * 12 | * @param statusApi the underlying API from the Java SDK 13 | * @see [[https://www.nomadproject.io/docs/http/status.html `/v1/status documentation`]] 14 | */ 15 | class ScalaStatusApi(statusApi: StatusApi) { 16 | 17 | /** Queries the address of the Raft leader in the given or active region. 18 | * 19 | * @param region the region to forward the request to 20 | * @see [[https://www.nomadproject.io/docs/http/status.html `GET /v1/status/peers`]] 21 | */ 22 | def leader(region: Option[String] = None): NomadResponse[String] = 23 | statusApi.leader(region.orNull) 24 | 25 | /** List the addresses of the Raft peers in the active region. 26 | * 27 | * @param region the region to forward the request to 28 | * @see [[https://www.nomadproject.io/docs/http/status.html `GET /v1/status/peers`]] 29 | */ 30 | def peers(region: Option[String] = None): NomadResponse[Seq[String]] = 31 | statusApi.peers(region.orNull) 32 | .map(_.asScala) 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/ScalaSystemApi.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import com.hashicorp.nomad.javasdk.{NomadResponse, SystemApi, WriteOptions} 4 | 5 | import scala.concurrent.Future 6 | 7 | /** API for performing system maintenance that shouldn't be necessary for most users, 8 | * exposing the functionality of the 9 | * [[https://www.nomadproject.io/docs/http/system.html `/v1/system/…` endpoints]] 10 | * of the [[https://www.nomadproject.io/docs/http/index.html Nomad HTTP API]]. 11 | * 12 | * @param systemApi the underlying API from the Java SDK 13 | */ 14 | class ScalaSystemApi(systemApi: SystemApi) { 15 | 16 | /** Initiates garbage collection of jobs, evals, allocations and nodes 17 | * in the active region. 18 | * 19 | * @param options options controlling how the request is performed 20 | * @see [[https://www.nomadproject.io/docs/http/system.html `PUT /v1/system/gc`]] 21 | */ 22 | def garbageCollect(options: Option[WriteOptions] = None): NomadResponse[Unit] = 23 | systemApi.garbageCollect(options.orNull) 24 | .map((_: Void) => ()) 25 | 26 | /** Reconciles the summaries of all jobs in the active region. 27 | * 28 | * @param options options controlling how the request is performed 29 | * @see [[https://www.nomadproject.io/docs/http/system.html `PUT /v1/system/reconcile/summaries`]] 30 | */ 31 | def reconcileSummaries(options: Option[WriteOptions] = None): NomadResponse[Unit] = 32 | systemApi.reconcileSummaries(options.orNull) 33 | .map((_: Void) => ()) 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/scala/com/hashicorp/nomad/scalasdk/package.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad 2 | 3 | import java.util.concurrent.ExecutionException 4 | 5 | import scala.concurrent._ 6 | 7 | import com.hashicorp.nomad.javasdk.{ NomadResponse, QueryOptions, ServerQueryResponse, ServerResponse } 8 | 9 | /** An SDK for interacting with Nomad from Scala. 10 | * 11 | * The central class in the SDK is [[com.hashicorp.nomad.scalasdk.NomadScalaApi]]. 12 | */ 13 | package object scalasdk { 14 | 15 | // /** Syntactic sugar for [[ListenableFuture]]s, the futures returned by the Java API. 16 | // * 17 | // * @param future the future to operate on 18 | // * @tparam A the type held by the future 19 | // */ 20 | // implicit final class ListenableFutureSyntax[A](private val future: ListenableFuture[A]) extends AnyVal { 21 | // 22 | // /** Returns a Scala [[scala.concurrent.Future]] equivalent to the [[ListenableFuture]]. */ 23 | // def asScala: Future[A] = 24 | // asScala(identity) 25 | // 26 | // /** Returns a Scala [[scala.concurrent.Future]] equivalent to the [[ListenableFuture]] 27 | // * 28 | // * @param f a function that maps the Java value eventually held by the ListenableFuture to its Scala equivalent 29 | // * @tparam B the type that will be held in the Scala Future 30 | // */ 31 | // def asScala[B](f: A => B): Future[B] = { 32 | // val promise = Promise[B]() 33 | // future.addListener(new Runnable { 34 | // override def run(): Unit = 35 | // try promise.trySuccess(f(future.get())) 36 | // catch { 37 | // case e: ExecutionException => promise.tryFailure(e.getCause) 38 | // case e: Throwable => promise.tryFailure(e) 39 | // } 40 | // }, MoreExecutors.directExecutor()) 41 | // promise.future 42 | // } 43 | // } 44 | 45 | /** Syntactic sugar for [[NomadResponse]]s. 46 | * 47 | * @param response the response to operate on 48 | * @tparam A the Java type representing the body of the response 49 | */ 50 | private[scalasdk] implicit final class FutureNomadResponseSyntax[A]( 51 | private val response: NomadResponse[A]) extends AnyVal { 52 | 53 | /** Returns a Scala representation of the response future. 54 | * 55 | * @param f a function that maps the response body from its Java representation to its Scala representation 56 | * @tparam B the Scala type representing the body of the response 57 | */ 58 | def map[B](f: A => B): NomadResponse[B] = 59 | new NomadResponse(response.getRawEntity, f(response.getValue)) 60 | } 61 | 62 | /** Syntactic sugar for [[ServerResponse]]s. 63 | * 64 | * @param response the response to operate on 65 | * @tparam A the Java type representing the body of the response 66 | */ 67 | private[scalasdk] implicit final class FutureServerResponseSyntax[A]( 68 | private val response: ServerResponse[A]) extends AnyVal { 69 | 70 | /** Returns a Scala representation of the response future. 71 | * 72 | * @param f a function that maps the response body from its Java representation to its Scala representation 73 | * @tparam B the Scala type representing the body of the response 74 | */ 75 | def map[B](f: A => B): ServerResponse[B] = 76 | new ServerResponse(response.getHttpResponse, response.getRawEntity, f(response.getValue)) 77 | } 78 | 79 | /** Syntactic sugar for [[ServerQueryResponse]]s. 80 | * 81 | * @param response the response to operate on 82 | * @tparam A the Java type representing the body of the response 83 | */ 84 | private[scalasdk] implicit final class FutureServerQueryResponseSyntax[A]( 85 | private val response: ServerQueryResponse[A]) extends AnyVal { 86 | 87 | /** Returns a Scala representation of the response future. 88 | * 89 | * @param f a function that maps the response body from its Java representation to its Scala representation 90 | * @tparam B the Scala type representing the body of the response 91 | */ 92 | def map[B](f: A => B): ServerQueryResponse[B] = 93 | new ServerQueryResponse(response.getHttpResponse, response.getRawEntity, f(response.getValue)) 94 | } 95 | 96 | /** Syntactic sugar for optional ScalaQueryOptions. 97 | * 98 | * @param options the options to operate on 99 | * @tparam A the Scala type representing the response body for the method the options will be used with 100 | */ 101 | private[scalasdk] implicit final class QueryOptionsSyntax[A](private val options: Option[ScalaQueryOptions[A]]) extends AnyVal { 102 | 103 | /** Returns equivalent QueryOptions for the Java API, assuming the Scala and Java types representing the response body are the same. */ 104 | def asJava: QueryOptions[A] = 105 | asJava(identity) 106 | 107 | /** Returns equivalent QueryOptions for the Java API. 108 | * 109 | * @param responseValueToScala a function that maps the response body from its Java representation to its Scala representation 110 | * @tparam J the Java type representing the response body for the method the options will be used with 111 | */ 112 | def asJava[J](responseValueToScala: J => A): QueryOptions[J] = 113 | options.map(_.asJava(responseValueToScala)).orNull 114 | 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/test/scala/com/hashicorp/nomad/scalasdk/NomadScalaApiTest.scala: -------------------------------------------------------------------------------- 1 | package com.hashicorp.nomad.scalasdk 2 | 3 | import java.io.{PrintWriter, StringWriter} 4 | 5 | import com.hashicorp.nomad.apimodel._ 6 | import com.hashicorp.nomad.javasdk.WaitStrategy._ 7 | import com.hashicorp.nomad.testutils.NomadAgentConfiguration.Builder 8 | import com.hashicorp.nomad.testutils.NomadAgentProcess 9 | import org.scalatest.FunSuite 10 | 11 | class NomadScalaApiTest extends FunSuite { 12 | 13 | def withClientServer[A](use: NomadAgentProcess => A): A = { 14 | val serverLog = new StringWriter 15 | val agent = new NomadAgentProcess(new PrintWriter(serverLog), new Builder().setClientEnabled(true).build()) 16 | try { 17 | use(agent) 18 | } catch { 19 | case e: Throwable => 20 | throw new RuntimeException(s"Error during server use: $e\nServer log follows:\n$serverLog", e) 21 | } 22 | finally agent.close() 23 | } 24 | 25 | def withApi[A](agent: NomadAgentProcess)(use: NomadScalaApi => A): A = { 26 | val nomadApi = NomadScalaApi(agent.getHttpAddress) 27 | try { 28 | use(nomadApi) 29 | } finally 30 | nomadApi.close() 31 | } 32 | 33 | test("Should be able to run a job") { 34 | 35 | val task = new Task() 36 | .setName("Do the Thing") 37 | .setDriver("mock_driver") 38 | .addConfig("run_for", "20s") 39 | .setLogConfig(new LogConfig() 40 | .setMaxFiles(1) 41 | .setMaxFileSizeMb(1) 42 | ) 43 | 44 | val job = new Job() 45 | .setId("run-some-stuff") 46 | .setName("Run Some Stuff") 47 | .setType("batch") 48 | .setPriority(1) 49 | .addTaskGroups( 50 | new TaskGroup() 51 | .setName("Group") 52 | .setCount(1) 53 | .addTasks(task) 54 | ) 55 | 56 | withClientServer { agent => 57 | withApi(agent) { api => 58 | agent.pollUntilReady(api.apiClient, waitForMilliseconds(20000, 200)) 59 | 60 | val Seq(region) = api.regions.list().getValue 61 | val Seq(node) = api.nodes.list().getValue 62 | 63 | val evalId = api.jobs.register(job.setRegion(region).addDatacenters(node.getDatacenter)).getValue 64 | val e = api.evaluations.pollForCompletion(evalId, waitForSeconds(10)).getValue 65 | assert(e.getFailedTgAllocs == null || e.getFailedTgAllocs.isEmpty) 66 | assert(e.getBlockedEval == null || e.getBlockedEval.isEmpty) 67 | assert(e.getNextEval == null || e.getNextEval.isEmpty) 68 | 69 | val Seq(allocation) = api.evaluations.allocations(e.getId).getValue 70 | api.lookupClientApiByNodeId(allocation.getNodeId) 71 | } 72 | } 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /version.sbt: -------------------------------------------------------------------------------- 1 | version in ThisBuild := "0.9.7.1-SNAPSHOT" 2 | --------------------------------------------------------------------------------