├── .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 [](https://travis-ci.org/hashicorp/nomad-scala-sdk) [](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 |
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/
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/
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 |
--------------------------------------------------------------------------------