├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── bin ├── setup_rails_test.sh └── test.sh └── src ├── build.rs ├── exec ├── executor.rs ├── executors │ ├── bash.rs │ ├── mod.rs │ └── sidekiq.rs ├── job.rs ├── job_type.rs ├── mod.rs ├── node.rs └── node_type.rs ├── http ├── controllers │ ├── api │ │ ├── job_types.rs │ │ ├── jobs.rs │ │ ├── mod.rs │ │ ├── node_types.rs │ │ ├── nodes.rs │ │ └── schedule.rs │ ├── health.rs │ └── mod.rs ├── helpers │ ├── control.rs │ ├── mod.rs │ └── post_wrapper.rs ├── middleware │ ├── api_auth.rs │ ├── assert_json.rs │ ├── logger.rs │ ├── mod.rs │ └── redis.rs ├── mod.rs └── routes.rs ├── main.rs ├── scheduler └── mod.rs ├── store ├── mod.rs └── redis.rs ├── threads ├── mod.rs ├── ping_thread.rs ├── scheduler_thread.rs └── worker_thread.rs └── util ├── config.rs ├── mod.rs └── time.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | /rails_test -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "synchrony" 3 | version = "0.1.0" 4 | authors = ["Protryon "] 5 | edition = "2018" 6 | publish = false 7 | build = "src/build.rs" 8 | 9 | [dependencies] 10 | lazy_static = "1.4.0" 11 | serde = { version = "1.0", features = ["derive"] } 12 | serde_json = "1.0" 13 | log = "0.4.8" 14 | env_logger = "0.6.1" 15 | either = "1.5.0" 16 | redis = "0.13.0" 17 | uuid = { version = "0.5.1", features = ["serde", "v4"] } 18 | regex = "1" 19 | time = { version = "0.2.6", features = ["serde"] } 20 | iron = "0.6" 21 | iron-test = "0.6" 22 | router = "0.6" 23 | persistent = "0.4" 24 | bodyparser = "0.8.0" 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Synchrony 2 | Synchrony is a distributed job management engine inspired in part by Sidekiq. 3 | 4 | ## Goals 5 | 6 | * Provide a highly stable job management engine that can scale to millions of jobs/second. 7 | * Provide a robust architecture allowing endless customization. 8 | * Allow easy migration from other job management engines. 9 | 10 | ## Status 11 | 12 | Synchrony is in a beta stage. 13 | 14 | ## Building 15 | 16 | Prerequisites: 17 | * Rust 1.40+ Stable 18 | 19 | 1. Clone the synchrony repository: 20 | ``` 21 | $ git clone git@github.com:Protryon/synchrony.git 22 | ``` 23 | 24 | 2. Within the `synchrony` directory, run `$ crate build`. 25 | 3. Run Synchrony with `$ ./target/debug/synchrony`. 26 | 27 | ## Running Synchrony 28 | 29 | Synchrony is designed to be a minimally-local configuration in order to ease scaling pains. 30 | 31 | Environment variables are used to provide parameters to connect to a given store (Redis is supported and selected by default), and tell the node what kind of node it is, and therefore what kinds of jobs it should process. 32 | 33 | * `NODE_TYPE`: Default value is `default`. This value must match a name within the `node_types` hash key in Redis or equivalent. 34 | * `STORE_TYPE`: Default value is `redis`. Currently only `redis` is supported. 35 | * `REDIS_HOST`: Default value is `127.0.0.1`. 36 | * `REDIS_PORT`: Default value is `6379`. 37 | * `REDIS_DATABASE`: Default value is ``. 38 | 39 | ### Redis configuration 40 | 41 | In order to get jobs flowing, you first must describe your jobs within Redis or equivalent. 42 | 43 | There are 2 important keys that you must create in order to do this. 44 | 45 | 1. `node_types`: A hash, mapping a node type name to a JSON object describing it's configuration. 46 | ``` 47 | { 48 | "name": "default", 49 | "uuid": "1bd2bf95-868a-4212-8a0a-82c7f442848e", 50 | "thread_count": 1 51 | } 52 | ``` 53 | * `name`: Must match the name given in the redis hash key. 54 | * `uuid`: A random UUID to uniquely identify a node type. 55 | * `thread_count`: An integer specifying the maximum number of concurrent jobs nodes of this type may process. 56 | 57 | Node types are essentially independent queues for job processing. 58 | 59 | 2. `job_types`: A hash, mapping a job type UUID to a JSON object describing it's configuration. 60 | ``` 61 | { 62 | "uuid": "80d1c95a-a9cc-4dbb-a3fb-ff0f6b7d2c06", 63 | "name": "test_job", 64 | "executor": "bash", 65 | "metadata": {"command": "ls -l /"}, 66 | "unique": false, 67 | "node_type": "default", 68 | "timeout": null 69 | } 70 | ``` 71 | * `uuid`: A random UUID to uniquely identify a job type. 72 | * `name`: A human-useful name to describe the job type. 73 | * `executor`: A string enum value specifying the module needed to execute jobs of this type. See below. 74 | * `metadata`: A JSON object to be passed to the executor. 75 | * `unique`: Not yet implemented: A boolean value specifying that a given job type can have more than 1 active job across all nodes. 76 | * `node_type`: A reference to the name of a given node type that jobs of this type belong to. 77 | * `timeout`: Not yet implemented: A null or integer value specifying the maximum duration, in milliseconds, that this job can take before being forcefully terminated. 78 | 79 | ### Executors 80 | Synchrony is built around the idea of end-use language agnosticism. Executors were created to support that idea, where a given job can have it's method of execution defined in a variety of ways. 81 | 82 | * `bash`: Bash takes two parameters in `job_type`'s metadata, concatenates with the same two parameters from a given `job`'s arguments: 83 | 1. `command`: Either a JSON array or a string representing the command. Required for `job_type`s, not for `job`s. 84 | 2. `environment`: A JSON map specifying the environment variables to set when running the job. Never required. 85 | * `sidekiq`: Sidekiq takes up to 6 parameters: 86 | * `job_type`'s metadata: 87 | 1. `rails_dir`: Path to rails primary application directory containing a Sidekiq installation. 88 | 2. `sidekiq_worker`: Ruby class name of the specified worker (i.e. `TestWorker`). 89 | 3. `ruby_executable`: Defaults to `ruby`. May be necessary to control in some version controlled environments. 90 | 4. `environment`: equivalent to `bash`'s `environment`. 91 | * `job`'s arguments: 92 | 5. `sidekiq_arguments`: An optional JSON blob representing the arguments to pass into the Sidekiq worker. 93 | 6. `environment`: equivalent to `bash`'s `environment`. 94 | * Custom Executors 95 | Synchrony only has builtin support for the above executors at the moment, which allows a wide range of integrations with other systems. Other, more specialized executors can be created by contributing to this project. Planned future builtin executors: 96 | * `http` 97 | 98 | ### Scheduling Jobs 99 | 100 | Synchrony has the ability to automatically schedule jobs in a cron-like fashion. 101 | 102 | Scheduled jobs can be easily managed directly through the store, or through the HTTP API. The interval (in milliseconds) specifies how often a job should run. 103 | 104 | Note that there is no notion of catching up jobs if workers have been offline for some time, so do not rely on execution counts based on time. 105 | 106 | ### Running Jobs 107 | 108 | Work in progress. 109 | 110 | There are 2 ways to manually queue a job in Synchrony: 111 | 1. Use the HTTP API provided by all Synchrony nodes to create a new job. 112 | 2. Use a client implementation of the chosen store you are using, and add jobs directly to the relevant queue (i.e. `jobs_waiting_`). 113 | 114 | ### Data formats 115 | 116 | The following are standard formats used to represent various data types with Synchrony. 117 | 118 | #### Job Type 119 | ``` 120 | { 121 | "uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 122 | "name": "test_job_type", 123 | "executor": "bash", 124 | "metadata": { command: "echo 'test'" }, 125 | "unique": false, 126 | "node_type": "default", 127 | "timeout": null 128 | } 129 | ``` 130 | 131 | * `uuid`: Universally Unique ID 132 | * `name`: Human readable name for convenience 133 | * `executor`: String enum value for current executor 134 | * `metadata`: Arguments to be used by the specified executor 135 | * `unique`: If true, only one job can execute across the network at one time 136 | * `node_type`: The type of nodes this job type can execute on 137 | * `timeout`: `null` or a time in milliseconds specifying how long the executor should wait before killing the job 138 | 139 | #### Job 140 | ``` 141 | { 142 | "uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 143 | "job_type_uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 144 | "arguments": {}, 145 | "executing_node": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 146 | "enqueued_at": 1580651664039, 147 | "started_at": 1580651664039, 148 | "ended_at": 1580651664039, 149 | "results": { stdout: "test\n", stderr: "", exit_code: 0 }, 150 | "errors": null 151 | } 152 | ``` 153 | 154 | * `uuid`: Universally Unique ID 155 | * `job_type_uuid`: UUID of job type accompying the job 156 | * `arguments`: Arguments to be used by the specified executor within the job type 157 | * `executing_node`: If already executing or finished, the node's UUID that is or has executed the job 158 | * `enqueued_at`: At what time the job was created, milliseconds UNIX epoch 159 | * `started_at`: At what time the job was started by a node, milliseconds UNIX epoch 160 | * `ended_at`: At what time the job was finished by a node, milliseconds UNIX epoch 161 | * `results`: An executor defined field upon job completion, or `null` if none provided 162 | * `errors`: An executor defined field upon job completion, or `null` if none provided 163 | 164 | #### Node Type 165 | ``` 166 | { 167 | "uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 168 | "name": "default", 169 | "thread_count": 16 170 | } 171 | ``` 172 | 173 | * `uuid`: Universally Unique ID 174 | * `name`: Human readable name for convenience 175 | * `thread_count`: An integer specifying how many concurrent jobs nodes of this type can process 176 | 177 | #### Node 178 | ``` 179 | { 180 | "uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 181 | "node_type_uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 182 | "last_ping": 1580651664039 183 | } 184 | ``` 185 | 186 | * `uuid`: Universally Unique ID 187 | * `node_type_uuid`: UUID of node type accompying the node, decided by the node on startup 188 | * `last_ping`: At what time the node last sent a ping to the store (by default every 5 seconds), milliseconds UNIX epoch 189 | 190 | #### Schedule Item 191 | ``` 192 | { 193 | "uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 194 | "interval": 60000, 195 | "last_scheduled_by": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 196 | "last_scheduled_at": 1580651664039, 197 | "job_type_uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 198 | "job_arguments": {} 199 | } 200 | ``` 201 | 202 | * `uuid`: Universally Unique ID 203 | * `interval`: Minimum number of milliseconds between job runs 204 | * `last_scheduled_by`: `null` if not previously run, or the uuid of the node that last scheduled (not run) this job 205 | * `last_scheduled_at`: `null` if not previously run, or the time in milliseconds UNIX epoch when the job was last scheduled (not run) 206 | * `job_type_uuid`: UUID of job type accompying the job 207 | * `job_arguments`: Arguments to be passed to the job upon being enqueued 208 | 209 | #### 210 | 211 | ### HTTP API 212 | * All requests are authenticated with an `Authorization: Bearer ` header, as specified via environment variable or defaulted to `dev_key`. 213 | * All post requests must have `Content-Type: application/json`. 214 | * All responses other than `GET /health` are JSON responses. `200 OK` status indicates success, anything else is failure. 215 | 216 | #### GET /health 217 | A simple endpoint that returns a `200 OK` response with payload of `ok`. 218 | 219 | #### GET /api/job_types 220 | Gets a list of all defined job types. 221 | 222 | Response format: 223 | ``` 224 | { 225 | job_types: [ 226 | 227 | ] 228 | } 229 | ``` 230 | 231 | #### GET /api/job_types/:uuid 232 | Gets a single job type. 233 | 234 | Response format: 235 | ``` 236 | 237 | ``` 238 | 239 | #### POST /api/job_types 240 | Creates a new job type. 241 | 242 | Request format: 243 | ``` 244 | 245 | ``` 246 | 247 | Response format: 248 | ``` 249 | { 250 | status: "ok", 251 | uuid: "b30833c1-83b0-4dda-a439-97e3c97bbaa5" 252 | } 253 | ``` 254 | 255 | #### GET /api/jobs/:node_type_uuid/queued 256 | Gets all enqueued jobs for a given node type. 257 | 258 | Response format: 259 | ``` 260 | { 261 | jobs: [ 262 | 263 | ] 264 | } 265 | ``` 266 | 267 | #### GET /api/jobs/:node_type_uuid/in_progress 268 | Gets all currently executing jobs for a given node type. 269 | 270 | Response format: 271 | Same as `GET /api/jobs/:node_type_uuid/queued` above. 272 | 273 | #### GET /api/jobs/:node_type_uuid/finished 274 | Gets all finished jobs for a given node type. 275 | 276 | Response format: 277 | Same as `GET /api/jobs/:node_type_uuid/queued` above. 278 | 279 | Note that `results` and `errors` are replaced with `true`/`false`. To get the full results or errors, get the specific job via `GET /api/jobs/:node_type_uuid/:uuid` below. 280 | 281 | #### GET /api/jobs/:node_type_uuid/:uuid 282 | Gets a finished job's extended data, including full results/errors. 283 | 284 | Response format: 285 | ``` 286 | 287 | ``` 288 | 289 | #### POST /api/jobs 290 | Enqueues a new job to be executed. Note that the node that receives this request is not necessarily the node that will execute it. 291 | 292 | Request format: 293 | ``` 294 | { 295 | "job_type_uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 296 | "arguments": {} 297 | } 298 | ``` 299 | 300 | Response format: 301 | ``` 302 | { 303 | status: "ok", 304 | uuid: "b30833c1-83b0-4dda-a439-97e3c97bbaa5" 305 | } 306 | ``` 307 | 308 | #### GET /api/node_types 309 | Gets a list of all defined node types. 310 | 311 | Response format: 312 | ``` 313 | { 314 | node_types: [ 315 | 316 | ] 317 | } 318 | ``` 319 | 320 | #### GET /api/node_types/:uuid 321 | Gets a single node type. 322 | 323 | Response format: 324 | ``` 325 | 326 | ``` 327 | 328 | #### POST /api/node_types/:uuid 329 | Creates a new node type, or updates an existing one. Note that the UUID must remain unchanged. 330 | 331 | Request format: 332 | ``` 333 | 334 | ``` 335 | 336 | Response format: 337 | ``` 338 | { 339 | "status": "ok" 340 | } 341 | ``` 342 | 343 | #### GET /api/nodes 344 | Gets a list of all nodes that have been active in the last 20 seconds. 345 | 346 | Response format: 347 | ``` 348 | { 349 | nodes: [ 350 | 351 | ] 352 | } 353 | ``` 354 | 355 | #### GET /api/nodes/:uuid 356 | Gets information on a specific node. 357 | 358 | Response format: 359 | ``` 360 | 361 | ``` 362 | 363 | #### GET /api/schedules 364 | Gets a list of all schedule items. 365 | 366 | Response format: 367 | ``` 368 | { 369 | schedules: [ 370 | 371 | ] 372 | } 373 | ``` 374 | 375 | #### GET /api/schedules/:uuid 376 | Gets a single schedule item. 377 | 378 | Response format: 379 | ``` 380 | 381 | ``` 382 | 383 | #### POST /api/schedules 384 | Creates a new schedule item. 385 | 386 | Request format: 387 | ``` 388 | { 389 | "interval": 60000, 390 | "job_type_uuid": "b30833c1-83b0-4dda-a439-97e3c97bbaa5", 391 | "job_arguments": {} 392 | } 393 | ``` 394 | 395 | Response format: 396 | ``` 397 | { 398 | status: "ok", 399 | uuid: "b30833c1-83b0-4dda-a439-97e3c97bbaa5" 400 | } 401 | ``` 402 | 403 | #### DELETE /api/schedules/:uuid 404 | Deletes a schedule item permanently. 405 | 406 | Response format: 407 | ``` 408 | { 409 | status: "ok", 410 | uuid: "b30833c1-83b0-4dda-a439-97e3c97bbaa5" 411 | } 412 | ``` 413 | 414 | ## Future Work 415 | * Create a watchdog thread that looks for jobs claimed by dead nodes and requeues them depending on job configuration. 416 | * Build out independent frontend that interfaces with the HTTP API. 417 | * Create logging client to export logs from finished jobs in Redis. 418 | * Create `http` executor. 419 | * Create client language implementations for direct communication. 420 | -------------------------------------------------------------------------------- /bin/setup_rails_test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | rm -rf rails_test 3 | mkdir rails_test 4 | cd rails_test 5 | cat << EOF > ./Gemfile 6 | source 'https://rubygems.org' 7 | 8 | ruby '2.5.5' 9 | 10 | gem 'rails', '~> 5.2.2', '>= 5.2.2.1' 11 | gem 'sidekiq' 12 | gem 'bootsnap' 13 | gem 'listen' 14 | EOF 15 | bundle install 16 | rails new -s . 17 | mkdir app/workers 18 | cat << EOF > ./app/workers/test_worker.rb 19 | class TestWorker 20 | include Sidekiq::Worker 21 | 22 | def perform(arg) 23 | puts "test successful #{arg.to_json}" 24 | end 25 | end 26 | EOF 27 | # ruby << EOF 28 | # require './config/environment' 29 | # TestWorker.new.perform 30 | # EOF 31 | cd .. 32 | -------------------------------------------------------------------------------- /bin/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | cargo test -- --test-threads=1 3 | -------------------------------------------------------------------------------- /src/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | } 3 | -------------------------------------------------------------------------------- /src/exec/executor.rs: -------------------------------------------------------------------------------- 1 | use super::job::Job; 2 | use serde_json::Value; 3 | 4 | pub trait ExecutionContext { 5 | fn result(&mut self, job: &Job, is_async: bool) -> Option, Value>>; 6 | } 7 | 8 | pub trait Executor { 9 | type Context: ExecutionContext; 10 | 11 | fn execute(&mut self, job: &Job) -> Self::Context; 12 | } -------------------------------------------------------------------------------- /src/exec/executors/bash.rs: -------------------------------------------------------------------------------- 1 | use std::process::*; 2 | use crate::exec::executor::*; 3 | use std::env; 4 | use crate::exec::job::Job; 5 | use log::*; 6 | use serde_json::{Value, json}; 7 | use regex::Regex; 8 | use serde_json::map::Map; 9 | 10 | pub struct BashExecutor { 11 | 12 | } 13 | 14 | pub struct BashExecutorContext { 15 | pub internal_failure: bool, 16 | pub handle: Option, 17 | pub timeout: Option, 18 | } 19 | 20 | impl ExecutionContext for BashExecutorContext { 21 | fn result(&mut self, job: &Job, is_async: bool) -> Option, Value>> { 22 | //TODO: handle timeouts, async? 23 | if self.internal_failure { 24 | return Some(Err(Value::Null)); 25 | } 26 | let handle = self.handle.as_mut().unwrap(); 27 | let status = if is_async { 28 | let waited = handle.try_wait(); 29 | if waited.is_ok() && waited.as_ref().unwrap().is_none() { 30 | return None; 31 | } 32 | waited.map(|i| i.unwrap()) 33 | } else { 34 | handle.wait() 35 | }; 36 | return match status { 37 | Err(e) => { 38 | error!("Failed to wait for bash process completion in job '{}', job type '{}' / '{}': {:?}", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated(), e); 39 | Some(Err(Value::Null)) 40 | } 41 | Ok(status) => { 42 | let mut output = Map::new(); 43 | let process_out = self.handle.take().unwrap().wait_with_output().expect("wait_with_output failed after wait succeeded"); 44 | output.insert("stdout".to_string(), Value::String(String::from_utf8_lossy(process_out.stdout.as_slice()).to_string())); 45 | output.insert("stderr".to_string(), Value::String(String::from_utf8_lossy(process_out.stderr.as_slice()).to_string())); 46 | output.insert("exit_code".to_string(), status.code().map(|code| json!(code)).unwrap_or(Value::Null)); 47 | Some(Ok(Some(Value::Object(output)))) 48 | } 49 | } 50 | } 51 | } 52 | 53 | impl Executor for BashExecutor { 54 | type Context = BashExecutorContext; 55 | 56 | fn execute(&mut self, job: &Job) -> BashExecutorContext { 57 | lazy_static! { 58 | static ref SAFE_ARG_REGEX: Regex = Regex::new("\\\\|\"").unwrap(); 59 | } 60 | let metadata = &job.job_type.as_ref().unwrap().metadata; 61 | let meta_command = metadata.get("command"); 62 | let meta_environment = metadata.get("environment"); 63 | let timeout = job.job_type.as_ref().unwrap().timeout; 64 | if meta_command.is_none() || !(meta_command.unwrap().is_string() || meta_command.unwrap().is_array()) { 65 | error!("No command found in job type in bash execution for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 66 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 67 | } 68 | let command = job.arguments.get("command"); 69 | let environment = job.arguments.get("environment"); 70 | if command.is_some() && !(command.unwrap().is_string() || command.unwrap().is_array()) { 71 | error!("Invalid command arguments found in job in bash execution for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 72 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 73 | } 74 | let mut environment = match environment { 75 | None => Map::new(), 76 | Some(Value::Object(value)) => value.clone(), 77 | _ => { 78 | warn!("Invalid environment parameter in job for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 79 | Map::new() 80 | } 81 | }; 82 | let mut meta_environment = match meta_environment { 83 | None => Map::new(), 84 | Some(Value::Object(value)) => value.clone(), 85 | _ => { 86 | warn!("Invalid environment parameter in job type for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 87 | Map::new() 88 | } 89 | }; 90 | meta_environment.append(&mut environment); 91 | environment = meta_environment; 92 | let empty_array = Value::Array(vec![]); 93 | let command_unwrapped = command.unwrap_or(&empty_array); 94 | let command_unwrapped_meta = meta_command.unwrap(); 95 | let mut builder = Command::new(env::var("SHELL").unwrap_or("/bin/bash".to_string())); 96 | builder 97 | .stderr(Stdio::piped()) 98 | .stdout(Stdio::piped()) 99 | .arg("-c") 100 | .stdin(Stdio::null()); 101 | environment.iter().for_each(|(key, value)| { 102 | match value { 103 | Value::String(s) => { 104 | builder.env(key, s); 105 | } 106 | _ => { 107 | warn!("Non-string environment parameter '{}' for job '{}', job type '{}' / '{}'", key, job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 108 | } 109 | } 110 | } ); 111 | let mut total_command: Vec = vec![]; 112 | for unwrapped in vec![command_unwrapped_meta, command_unwrapped] { 113 | let arg = match unwrapped { 114 | Value::String(s) => s.clone(), 115 | Value::Array(arr) => { 116 | if arr.iter().any({ |arg| !arg.is_string()}) { 117 | error!("Invalid non-string argument in arguments for bash command for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 118 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 119 | } 120 | arr.iter().map({ |arg| match arg { 121 | Value::String(s) => format!("\"{}\"", &SAFE_ARG_REGEX.replace_all(s, "\\$0")), 122 | _ => "".to_string(), 123 | } }).collect::>().join(" ") 124 | } 125 | _ => "".to_string() 126 | }; 127 | total_command.push(arg); 128 | } 129 | builder.arg(total_command.join(" ")); 130 | let handle = builder.spawn(); 131 | if handle.is_err() { 132 | error!("Failed to spawn bash in bash execution for job '{}', job type '{}' / '{}': {:?}", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated(), handle.unwrap_err()); 133 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 134 | } 135 | return BashExecutorContext { internal_failure: false, handle: handle.ok(), timeout: timeout } 136 | } 137 | } 138 | 139 | #[cfg(test)] 140 | mod tests { 141 | use super::*; 142 | use uuid::Uuid; 143 | use crate::exec::job_type::JobType; 144 | use std::collections::HashMap; 145 | use serde_json::Number; 146 | 147 | fn make_job_type(command: Value, environment: Option>) -> JobType { 148 | let mut job_type = JobType { 149 | executor: "bash".to_string(), 150 | name: "test".to_string(), 151 | node_type: "default".to_string(), 152 | timeout: None, 153 | unique: false, 154 | uuid: Uuid::new_v4(), 155 | metadata: HashMap::new(), 156 | }; 157 | job_type.metadata.insert("command".to_string(), command); 158 | if environment.is_some() { 159 | job_type.metadata.insert("environment".to_string(), Value::Object(environment.unwrap())); 160 | } 161 | return job_type; 162 | } 163 | 164 | fn make_job(job_type: &JobType, command: Option, environment: Option>) -> Job { 165 | let mut job = Job { 166 | uuid: Uuid::new_v4(), 167 | job_type_uuid: job_type.uuid, 168 | job_type: Some(job_type.clone()), 169 | arguments: HashMap::new(), 170 | executing_node: None, 171 | enqueued_at: None, 172 | started_at: None, 173 | ended_at: None, 174 | results: None, 175 | errors: None, 176 | }; 177 | if command.is_some() { 178 | job.arguments.insert("command".to_string(), command.unwrap()); 179 | } 180 | if environment.is_some() { 181 | job.arguments.insert("environment".to_string(), Value::Object(environment.unwrap())); 182 | } 183 | return job; 184 | } 185 | 186 | #[test] 187 | fn can_execute_command() { 188 | let mut executor = BashExecutor {}; 189 | let job_type = make_job_type(Value::String("echo 'test'".to_string()), None); 190 | let job = make_job(&job_type, None, None); 191 | let mut context = executor.execute(&job); 192 | let result = context.result(&job, false); 193 | let mut output = Map::new(); 194 | output.insert("stdout".to_string(), Value::String("test\n".to_string())); 195 | output.insert("stderr".to_string(), Value::String("".to_string())); 196 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 197 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 198 | } 199 | 200 | #[test] 201 | fn can_execute_commands() { 202 | let mut executor = BashExecutor {}; 203 | let job_type = make_job_type(Value::String("echo 'test'; echo 'test2'; echo 'test_err' 1>&2; exit 1;".to_string()), None); 204 | let job = make_job(&job_type, None, None); 205 | let mut context = executor.execute(&job); 206 | let result = context.result(&job, false); 207 | let mut output = Map::new(); 208 | output.insert("stdout".to_string(), Value::String("test\ntest2\n".to_string())); 209 | output.insert("stderr".to_string(), Value::String("test_err\n".to_string())); 210 | output.insert("exit_code".to_string(), Value::Number(Number::from(1))); 211 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 212 | } 213 | 214 | #[test] 215 | fn can_execute_array_command() { 216 | let mut executor = BashExecutor {}; 217 | let job_type = make_job_type(Value::Array(vec![Value::String("echo".to_string()), Value::String("test complex".to_string())]), None); 218 | let job = make_job(&job_type, None, None); 219 | let mut context = executor.execute(&job); 220 | let result = context.result(&job, false); 221 | let mut output = Map::new(); 222 | output.insert("stdout".to_string(), Value::String("test complex\n".to_string())); 223 | output.insert("stderr".to_string(), Value::String("".to_string())); 224 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 225 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 226 | } 227 | 228 | #[test] 229 | fn can_execute_parameterized_command() { 230 | let mut executor = BashExecutor {}; 231 | let job_type = make_job_type(Value::Array(vec![Value::String("echo".to_string()), Value::String("test complex".to_string())]), None); 232 | let job = make_job(&job_type, Some(Value::Array(vec![Value::String("part 2".to_string()), Value::String("part 3".to_string())])), None); 233 | let mut context = executor.execute(&job); 234 | let result = context.result(&job, false); 235 | let mut output = Map::new(); 236 | output.insert("stdout".to_string(), Value::String("test complex part 2 part 3\n".to_string())); 237 | output.insert("stderr".to_string(), Value::String("".to_string())); 238 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 239 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 240 | } 241 | 242 | #[test] 243 | fn can_execute_mixed_parameterized_command() { 244 | let mut executor = BashExecutor {}; 245 | let job_type = make_job_type(Value::String("echo test".to_string()), None); 246 | let job = make_job(&job_type, Some(Value::Array(vec![Value::String("part 2".to_string()), Value::String("part 3".to_string())])), None); 247 | let mut context = executor.execute(&job); 248 | let result = context.result(&job, false); 249 | let mut output = Map::new(); 250 | output.insert("stdout".to_string(), Value::String("test part 2 part 3\n".to_string())); 251 | output.insert("stderr".to_string(), Value::String("".to_string())); 252 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 253 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 254 | } 255 | 256 | #[test] 257 | fn can_execute_mixed2_parameterized_command() { 258 | let mut executor = BashExecutor {}; 259 | let job_type = make_job_type(Value::Array(vec![Value::String("echo".to_string()), Value::String("test complex".to_string())]), None); 260 | // spaces here are ignored when arguments are parsed in bash 261 | let job = make_job(&job_type, Some(Value::String("part 2 part 3".to_string())), None); 262 | let mut context = executor.execute(&job); 263 | let result = context.result(&job, false); 264 | let mut output = Map::new(); 265 | output.insert("stdout".to_string(), Value::String("test complex part 2 part 3\n".to_string())); 266 | output.insert("stderr".to_string(), Value::String("".to_string())); 267 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 268 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 269 | } 270 | 271 | #[test] 272 | fn can_execute_quoted_command() { 273 | let mut executor = BashExecutor {}; 274 | let job_type = make_job_type(Value::Array(vec![Value::String("echo".to_string()), Value::String("new\\nline".to_string()), Value::String("\"test\"".to_string())]), None); 275 | let job = make_job(&job_type, None, None); 276 | let mut context = executor.execute(&job); 277 | let result = context.result(&job, false); 278 | let mut output = Map::new(); 279 | output.insert("stdout".to_string(), Value::String("new\nline \"test\"\n".to_string())); 280 | output.insert("stderr".to_string(), Value::String("".to_string())); 281 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 282 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 283 | } 284 | 285 | #[test] 286 | fn can_execute_command_environment() { 287 | let mut executor = BashExecutor {}; 288 | let mut environment = Map::new(); 289 | environment.insert("test_env".to_string(), Value::String("test value".to_string())); 290 | let job_type = make_job_type(Value::String("echo $test_env".to_string()), Some(environment)); 291 | let job = make_job(&job_type, None, None); 292 | let mut context = executor.execute(&job); 293 | let result = context.result(&job, false); 294 | let mut output = Map::new(); 295 | output.insert("stdout".to_string(), Value::String("test value\n".to_string())); 296 | output.insert("stderr".to_string(), Value::String("".to_string())); 297 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 298 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 299 | } 300 | 301 | #[test] 302 | fn can_execute_command_parameterized_environment() { 303 | let mut executor = BashExecutor {}; 304 | let job_type = make_job_type(Value::String("echo $test_env".to_string()), None); 305 | let mut environment = Map::new(); 306 | environment.insert("test_env".to_string(), Value::String("test value".to_string())); 307 | let job = make_job(&job_type, None, Some(environment)); 308 | let mut context = executor.execute(&job); 309 | let result = context.result(&job, false); 310 | let mut output = Map::new(); 311 | output.insert("stdout".to_string(), Value::String("test value\n".to_string())); 312 | output.insert("stderr".to_string(), Value::String("".to_string())); 313 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 314 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 315 | } 316 | 317 | #[test] 318 | fn can_execute_command_overridden_environment() { 319 | let mut executor = BashExecutor {}; 320 | let mut meta_environment = Map::new(); 321 | meta_environment.insert("test_env".to_string(), Value::String("bad test".to_string())); 322 | let job_type = make_job_type(Value::String("echo $test_env".to_string()), Some(meta_environment)); 323 | let mut environment = Map::new(); 324 | environment.insert("test_env".to_string(), Value::String("test value".to_string())); 325 | let job = make_job(&job_type, None, Some(environment)); 326 | let mut context = executor.execute(&job); 327 | let result = context.result(&job, false); 328 | let mut output = Map::new(); 329 | output.insert("stdout".to_string(), Value::String("test value\n".to_string())); 330 | output.insert("stderr".to_string(), Value::String("".to_string())); 331 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 332 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 333 | } 334 | 335 | } 336 | -------------------------------------------------------------------------------- /src/exec/executors/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod bash; 2 | pub mod sidekiq; 3 | 4 | use super::job::Job; 5 | use crate::store::StoreRef; 6 | use super::executor::*; 7 | use log::*; 8 | use serde_json::Value; 9 | 10 | fn finish_job_execution(store: &mut StoreRef, job: Job, result: Option, Value>>) { 11 | let finish_result = match result { 12 | Some(Err(e)) => { 13 | store.finish_job(job, None, Some(e)) 14 | }, 15 | Some(Ok(value)) => { 16 | store.finish_job(job, value, None) 17 | }, 18 | _ => { 19 | store.finish_job(job, None, Some(Value::String("invalid executor context [async not supported]".to_string()))) 20 | }, 21 | }; 22 | if finish_result.is_err() { 23 | error!("Error finishing bash task from redis server: {}", finish_result.err().unwrap()); 24 | return; 25 | } 26 | } 27 | 28 | pub fn run_job(store: &mut StoreRef, job: Job) { 29 | let job_type = job.job_type.as_ref().unwrap(); 30 | if job_type.executor == "bash" { 31 | let mut executor = bash::BashExecutor {}; 32 | let mut context = executor.execute(&job); 33 | let result = context.result(&job, false); 34 | finish_job_execution(store, job, result); 35 | } else if job_type.executor == "sidekiq" { 36 | let mut executor = sidekiq::SidekiqExecutor {}; 37 | let mut context = executor.execute(&job); 38 | let result = context.result(&job, false); 39 | finish_job_execution(store, job, result); 40 | } else { 41 | error!("Invalid executor type for job type '{}' / '{}' on job '{}': '{}'", job_type.name, job_type.uuid.hyphenated(), job.uuid.hyphenated(), job_type.executor); 42 | let finish_result = store.finish_job(job, None, None); 43 | if finish_result.is_err() { 44 | error!("Error finishing bash task from redis server: {}", finish_result.err().unwrap()); 45 | return; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /src/exec/executors/sidekiq.rs: -------------------------------------------------------------------------------- 1 | use std::process::*; 2 | use crate::exec::executor::*; 3 | use std::env; 4 | use crate::exec::job::Job; 5 | use log::*; 6 | use serde_json::{Value}; 7 | use regex::Regex; 8 | use serde_json::map::Map; 9 | use super::bash::BashExecutorContext; 10 | use std::io::{ BufWriter, Write }; 11 | 12 | pub struct SidekiqExecutor { 13 | 14 | } 15 | 16 | impl Executor for SidekiqExecutor { 17 | type Context = BashExecutorContext; 18 | 19 | fn execute(&mut self, job: &Job) -> BashExecutorContext { 20 | lazy_static! { 21 | static ref SAFE_WORKER_REGEX: Regex = Regex::new("^[a-zA-Z0-9]+$").unwrap(); 22 | } 23 | let job_type = job.job_type.as_ref().unwrap(); 24 | let metadata = &job_type.metadata; 25 | let timeout = job_type.timeout; 26 | let rails_dir = match metadata.get("rails_dir") { 27 | Some(Value::String(s)) => { 28 | s 29 | }, 30 | _ => { 31 | error!("No rails_dir found in job type in sidekiq execution for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 32 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 33 | }, 34 | }; 35 | let sidekiq_worker = match metadata.get("sidekiq_worker") { 36 | Some(Value::String(s)) => { 37 | s 38 | }, 39 | _ => { 40 | error!("No sidekiq_worker found in job type in sidekiq execution for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 41 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 42 | }, 43 | }; 44 | if !SAFE_WORKER_REGEX.is_match(sidekiq_worker) { 45 | error!("Invalid sidekiq_worker for job '{}', job type '{}' / '{}': '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated(), sidekiq_worker); 46 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 47 | } 48 | let ruby_executable = match metadata.get("ruby_executable") { 49 | Some(Value::String(s)) => { 50 | s 51 | }, 52 | None => { 53 | "ruby" 54 | }, 55 | _ => { 56 | warn!("No valid ruby_executable described for job '{}', job type '{}' / '{}', using 'ruby'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 57 | "ruby" 58 | }, 59 | }; 60 | 61 | let sidekiq_arguments = match job.arguments.get("sidekiq_arguments") { 62 | Some(value) => { 63 | Some(serde_json::to_string(&value).unwrap()) 64 | }, 65 | _ => { 66 | None 67 | }, 68 | }; 69 | 70 | let meta_environment = metadata.get("environment"); 71 | let environment = job.arguments.get("environment"); 72 | let mut environment = match environment { 73 | None => Map::new(), 74 | Some(Value::Object(value)) => value.clone(), 75 | _ => { 76 | warn!("Invalid environment parameter in job for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 77 | Map::new() 78 | } 79 | }; 80 | let mut meta_environment = match meta_environment { 81 | None => Map::new(), 82 | Some(Value::Object(value)) => value.clone(), 83 | _ => { 84 | warn!("Invalid environment parameter in job type for job '{}', job type '{}' / '{}'", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 85 | Map::new() 86 | } 87 | }; 88 | meta_environment.append(&mut environment); 89 | environment = meta_environment; 90 | let mut builder = Command::new(env::var("SHELL").unwrap_or("/bin/bash".to_string())); 91 | builder 92 | .stderr(Stdio::piped()) 93 | .stdout(Stdio::piped()) 94 | .arg("-c") 95 | .stdin(Stdio::piped()) 96 | .current_dir(rails_dir); 97 | environment.iter().for_each(|(key, value)| { 98 | match value { 99 | Value::String(s) => { 100 | builder.env(key, s); 101 | } 102 | _ => { 103 | warn!("Non-string environment parameter '{}' for job '{}', job type '{}' / '{}'", key, job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated()); 104 | } 105 | } 106 | } ); 107 | builder.arg(ruby_executable); 108 | let handle = builder.spawn(); 109 | if handle.is_err() { 110 | error!("Failed to spawn bash in bash execution for job '{}', job type '{}' / '{}': {:?}", job.uuid.hyphenated(), job.job_type.as_ref().unwrap().name, job.job_type_uuid.hyphenated(), handle.unwrap_err()); 111 | return BashExecutorContext { internal_failure: true, handle: None, timeout: timeout }; 112 | } 113 | let mut handle = handle.unwrap(); 114 | { 115 | let stdin = handle 116 | .stdin 117 | .as_mut() 118 | .expect("failed to open stdin for sidekiq executor"); 119 | let mut stdin_writer = BufWriter::new(stdin); 120 | stdin_writer 121 | .write_all(format!(" 122 | require './config/environment' 123 | {}.new.perform({}) 124 | ", sidekiq_worker, sidekiq_arguments.map(|args| format!("JSON.parse('{}')", args.replace('\\', "\\\\").replace("'", "\\'"))).unwrap_or("nil".to_string())).as_bytes()) 125 | .expect("failed to write to sidekiq executor stdin"); 126 | stdin_writer 127 | .flush() 128 | .expect("failed to write to sidekiq executor stdin"); 129 | } 130 | drop(handle.stdin.take()); 131 | return BashExecutorContext { internal_failure: false, handle: Some(handle), timeout: timeout } 132 | } 133 | } 134 | 135 | 136 | #[cfg(test)] 137 | mod tests { 138 | use super::*; 139 | use uuid::Uuid; 140 | use crate::exec::job_type::JobType; 141 | use std::collections::HashMap; 142 | use serde_json::Number; 143 | 144 | fn make_job_type(environment: Option>) -> JobType { 145 | let mut job_type = JobType { 146 | executor: "sidekiq".to_string(), 147 | name: "test".to_string(), 148 | node_type: "default".to_string(), 149 | timeout: None, 150 | unique: false, 151 | uuid: Uuid::new_v4(), 152 | metadata: HashMap::new(), 153 | }; 154 | job_type.metadata.insert("rails_dir".to_string(), Value::String("./rails_test".to_string())); 155 | job_type.metadata.insert("sidekiq_worker".to_string(), Value::String("TestWorker".to_string())); 156 | 157 | if environment.is_some() { 158 | job_type.metadata.insert("environment".to_string(), Value::Object(environment.unwrap())); 159 | } 160 | return job_type; 161 | } 162 | 163 | fn make_job(job_type: &JobType, arguments: Option, environment: Option>) -> Job { 164 | let mut job = Job { 165 | uuid: Uuid::new_v4(), 166 | job_type_uuid: job_type.uuid, 167 | job_type: Some(job_type.clone()), 168 | arguments: HashMap::new(), 169 | executing_node: None, 170 | enqueued_at: None, 171 | started_at: None, 172 | ended_at: None, 173 | results: None, 174 | errors: None, 175 | }; 176 | if arguments.is_some() { 177 | job.arguments.insert("sidekiq_arguments".to_string(), arguments.unwrap()); 178 | } 179 | if environment.is_some() { 180 | job.arguments.insert("environment".to_string(), Value::Object(environment.unwrap())); 181 | } 182 | return job; 183 | } 184 | 185 | fn init_rails() { 186 | Command::new("./bin/setup_rails_test.sh").output().expect("failed to initialize rails environment for testing"); 187 | } 188 | 189 | fn rails_test(job_type: &JobType, value: Option, raw_value: &'static str) { 190 | let job = make_job(job_type, value, None); 191 | let mut context = (SidekiqExecutor {}).execute(&job); 192 | let result = context.result(&job, false); 193 | let mut output = Map::new(); 194 | output.insert("stdout".to_string(), Value::String(format!("test successful {}\n", raw_value))); 195 | output.insert("stderr".to_string(), Value::String("".to_string())); 196 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 197 | assert_eq!(result, Some(Ok(Some(Value::Object(output))))); 198 | } 199 | 200 | // if this test is failing, it probably has to due with a lack of rails installation 201 | #[test] 202 | fn can_execute_sidekiq_job() { 203 | init_rails(); 204 | let job_type = make_job_type(None); 205 | rails_test(&job_type, None, "null"); 206 | rails_test(&job_type, Some(Value::Bool(true)), "true"); 207 | let mut map = Map::new(); 208 | map.insert("test_key".to_string(), Value::String("test_value".to_string())); 209 | rails_test(&job_type, Some(Value::Object(map)), "{\"test_key\":\"test_value\"}"); 210 | } 211 | 212 | } -------------------------------------------------------------------------------- /src/exec/job.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use serde::{Deserialize, Serialize}; 3 | use uuid::Uuid; 4 | use serde_json::Value; 5 | use super::job_type::JobType; 6 | 7 | #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)] 8 | pub struct Job { 9 | pub uuid: Uuid, 10 | pub job_type_uuid: Uuid, 11 | #[serde(skip)] pub job_type: Option, 12 | pub arguments: HashMap, 13 | pub executing_node: Option, 14 | pub enqueued_at: Option, 15 | pub started_at: Option, 16 | pub ended_at: Option, 17 | pub results: Option, 18 | pub errors: Option, 19 | } 20 | -------------------------------------------------------------------------------- /src/exec/job_type.rs: -------------------------------------------------------------------------------- 1 | use uuid::Uuid; 2 | use serde_json::Value; 3 | use serde::{ Deserialize, Serialize }; 4 | use std::collections::HashMap; 5 | 6 | #[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] 7 | pub struct JobType { 8 | pub uuid: Uuid, 9 | pub name: String, 10 | pub executor: String, 11 | pub metadata: HashMap, 12 | pub unique: bool, 13 | pub node_type: String, // name not UUID to avoid versioning issues until node_types have more attached data 14 | pub timeout: Option, 15 | } -------------------------------------------------------------------------------- /src/exec/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod job; 2 | pub mod job_type; 3 | pub mod node_type; 4 | pub mod executor; 5 | pub mod executors; 6 | pub mod node; -------------------------------------------------------------------------------- /src/exec/node.rs: -------------------------------------------------------------------------------- 1 | use uuid::Uuid; 2 | use serde::{Deserialize, Serialize}; 3 | use super::node_type::NodeType; 4 | 5 | #[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] 6 | pub struct Node { 7 | pub uuid: Uuid, 8 | pub node_type_uuid: Option, 9 | #[serde(skip)] pub node_type: Option, 10 | pub last_ping: u64, 11 | } -------------------------------------------------------------------------------- /src/exec/node_type.rs: -------------------------------------------------------------------------------- 1 | use uuid::Uuid; 2 | use serde::{ Deserialize, Serialize }; 3 | 4 | #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)] 5 | pub struct NodeType { 6 | pub uuid: Uuid, 7 | pub name: String, 8 | pub thread_count: u32, 9 | } -------------------------------------------------------------------------------- /src/http/controllers/api/job_types.rs: -------------------------------------------------------------------------------- 1 | use crate::http::middleware::redis::IronRedis; 2 | use iron::prelude::*; 3 | use serde::{Deserialize, Serialize}; 4 | use crate::exec::job_type::JobType; 5 | use uuid::Uuid; 6 | use std::collections::HashMap; 7 | use serde_json::Value; 8 | use super::{ get_uuid_from_arg, redis_error_translate, option_translate }; 9 | 10 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] 11 | pub struct IndexResponse { 12 | job_types: Vec, 13 | } 14 | 15 | pub fn index( 16 | req: &mut Request, 17 | _: &(), 18 | ) -> Result> { 19 | let mut store = req.extensions 20 | .get::() 21 | .unwrap() 22 | .lock() 23 | .unwrap(); 24 | let job_types = redis_error_translate(store.get_job_types())?; 25 | Ok(IndexResponse { 26 | job_types: job_types, 27 | }) 28 | } 29 | 30 | pub fn get( 31 | req: &mut Request, 32 | _: &(), 33 | ) -> Result> { 34 | let uuid = get_uuid_from_arg(req, "uuid")?; 35 | let mut store = req.extensions 36 | .get::() 37 | .unwrap() 38 | .lock() 39 | .unwrap(); 40 | let job_type = option_translate( 41 | redis_error_translate(store.get_job_type(uuid))? 42 | )?; 43 | Ok(job_type) 44 | } 45 | 46 | #[derive(Debug, Clone, Serialize, Deserialize)] 47 | pub struct PostResponse { 48 | status: String, 49 | uuid: Uuid, 50 | } 51 | 52 | #[derive(Debug, Clone, Serialize, Deserialize)] 53 | pub struct PostBody { 54 | pub name: String, 55 | pub executor: String, 56 | pub metadata: HashMap, 57 | pub unique: bool, 58 | pub node_type: String, 59 | pub timeout: Option, 60 | } 61 | 62 | pub fn post( 63 | req: &mut Request, 64 | body: &PostBody, 65 | ) -> Result> { 66 | let mut store = req.extensions 67 | .get::() 68 | .unwrap() 69 | .lock() 70 | .unwrap(); 71 | let job_type = JobType { 72 | uuid: Uuid::new_v4(), 73 | name: body.name.clone(), 74 | executor: body.executor.clone(), 75 | metadata: body.metadata.clone(), 76 | unique: body.unique, 77 | node_type: body.node_type.clone(), 78 | timeout: body.timeout, 79 | }; 80 | redis_error_translate(store.new_job_type(&job_type))?; 81 | Ok(PostResponse { 82 | status: "ok".to_string(), 83 | uuid: job_type.uuid, 84 | }) 85 | } 86 | 87 | 88 | #[cfg(test)] 89 | mod tests { 90 | use super::*; 91 | use iron_test::request::{ post, get }; 92 | use iron::{ Headers, headers::ContentType }; 93 | use crate::http::controllers::tests::*; 94 | use crate::config; 95 | use iron::status; 96 | use crate::http::tests::initialize_tests; 97 | use crate::store::{ self, StoreRef, tests::* }; 98 | 99 | #[test] 100 | fn test_job_types_index() -> Result<(), String> { 101 | let mut store: StoreRef = store::init_store_untyped(); 102 | store.clean(); 103 | let test_node_type = make_node_type(&mut store)?; 104 | store.set_node_type(test_node_type.uuid)?; 105 | let test_job_type = make_job_type(&mut store)?; 106 | 107 | let response = iron_error_translate(get(&*format!("http://{}/api/job_types", &*config::HTTP_BIND_ADDRESS), Headers::new(), &initialize_tests(store)))?; 108 | assert_eq!(response.status, Some(status::Ok)); 109 | let body: IndexResponse = parse_body(response.body)?; 110 | assert_eq!(body, IndexResponse { 111 | job_types: vec![test_job_type], 112 | }); 113 | Ok(()) 114 | } 115 | 116 | #[test] 117 | fn test_job_types_get() -> Result<(), String> { 118 | let mut store: StoreRef = store::init_store_untyped(); 119 | store.clean(); 120 | let test_node_type = make_node_type(&mut store)?; 121 | store.set_node_type(test_node_type.uuid)?; 122 | let test_job_type = make_job_type(&mut store)?; 123 | 124 | let response = iron_error_translate(get(&*format!("http://{}/api/job_types/{}", &*config::HTTP_BIND_ADDRESS, test_job_type.uuid.hyphenated()), Headers::new(), &initialize_tests(store)))?; 125 | assert_eq!(response.status, Some(status::Ok)); 126 | let body: JobType = parse_body(response.body)?; 127 | assert_eq!(body, test_job_type); 128 | Ok(()) 129 | } 130 | 131 | #[test] 132 | fn test_job_types_post() -> Result<(), String> { 133 | let mut store: StoreRef = store::init_store_untyped(); 134 | store.clean(); 135 | let test_node_type = make_node_type(&mut store)?; 136 | store.set_node_type(test_node_type.uuid)?; 137 | 138 | let test_job_type = PostBody { 139 | executor: "bash".to_string(), 140 | name: "test".to_string(), 141 | node_type: "default".to_string(), 142 | timeout: None, 143 | unique: false, 144 | metadata: HashMap::new(), 145 | }; 146 | let job_type_serialized = serde_json::to_string(&test_job_type).unwrap(); 147 | 148 | let mut headers = Headers::new(); 149 | headers.set::(ContentType::json()); 150 | let response = iron_error_translate(post(&*format!("http://{}/api/job_types", &*config::HTTP_BIND_ADDRESS), headers, &*job_type_serialized, &initialize_tests(store.replicate()?)))?; 151 | assert_eq!(response.status, Some(status::Ok)); 152 | let body: PostResponse = parse_body(response.body)?; 153 | let new_job = store.get_job_type(body.uuid)?.unwrap(); 154 | assert_eq!(new_job, JobType { 155 | uuid: body.uuid, 156 | executor: test_job_type.executor, 157 | name: test_job_type.name, 158 | node_type: test_job_type.node_type, 159 | timeout: test_job_type.timeout, 160 | unique: test_job_type.unique, 161 | metadata: test_job_type.metadata, 162 | }); 163 | Ok(()) 164 | } 165 | 166 | } 167 | -------------------------------------------------------------------------------- /src/http/controllers/api/jobs.rs: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | router.get("/api/jobs/:node_type_uuid/:uuid", serialize_wrap(api::jobs::get), "jobs#get"); 4 | router.post("/api/jobs/:node_type_uuid", json_wrap(api::jobs::post), "jobs#post"); 5 | */ 6 | 7 | use crate::http::middleware::redis::IronRedis; 8 | use iron::prelude::*; 9 | use serde::{Deserialize, Serialize}; 10 | use crate::exec::job::Job; 11 | use uuid::Uuid; 12 | use std::collections::HashMap; 13 | use serde_json::Value; 14 | use super::{ get_uuid_from_arg, redis_error_translate, option_translate }; 15 | 16 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] 17 | pub struct IndexResponse { 18 | jobs: Vec, 19 | } 20 | 21 | pub fn index_queued( 22 | req: &mut Request, 23 | _: &(), 24 | ) -> Result> { 25 | let mut store = req.extensions 26 | .get::() 27 | .unwrap() 28 | .lock() 29 | .unwrap(); 30 | let current_node_type_uuid = store.get_node().node_type_uuid.unwrap(); 31 | let node_type_uuid = get_uuid_from_arg(req, "node_type_uuid")?; 32 | option_translate(redis_error_translate(store.set_node_type_soft(node_type_uuid))?)?; 33 | let jobs = redis_error_translate(store.get_all_jobs_waiting()); 34 | option_translate(redis_error_translate(store.set_node_type_soft(current_node_type_uuid))?)?; 35 | if jobs.is_err() { 36 | return Err(jobs.err().unwrap()); 37 | } 38 | Ok(IndexResponse { 39 | jobs: jobs.unwrap(), 40 | }) 41 | } 42 | 43 | pub fn index_in_progress( 44 | req: &mut Request, 45 | _: &(), 46 | ) -> Result> { 47 | let mut store = req.extensions 48 | .get::() 49 | .unwrap() 50 | .lock() 51 | .unwrap(); 52 | let current_node_type_uuid = store.get_node().node_type_uuid.unwrap(); 53 | let node_type_uuid = get_uuid_from_arg(req, "node_type_uuid")?; 54 | option_translate(redis_error_translate(store.set_node_type_soft(node_type_uuid))?)?; 55 | let jobs = redis_error_translate(store.get_all_jobs_in_progress()); 56 | option_translate(redis_error_translate(store.set_node_type_soft(current_node_type_uuid))?)?; 57 | if jobs.is_err() { 58 | return Err(jobs.err().unwrap()); 59 | } 60 | Ok(IndexResponse { 61 | jobs: jobs.unwrap(), 62 | }) 63 | } 64 | 65 | pub fn index_finished( 66 | req: &mut Request, 67 | _: &(), 68 | ) -> Result> { 69 | let mut store = req.extensions 70 | .get::() 71 | .unwrap() 72 | .lock() 73 | .unwrap(); 74 | let current_node_type_uuid = store.get_node().node_type_uuid.unwrap(); 75 | let node_type_uuid = get_uuid_from_arg(req, "node_type_uuid")?; 76 | option_translate(redis_error_translate(store.set_node_type_soft(node_type_uuid))?)?; 77 | let jobs = redis_error_translate(store.get_all_jobs_finished()); 78 | option_translate(redis_error_translate(store.set_node_type_soft(current_node_type_uuid))?)?; 79 | if jobs.is_err() { 80 | return Err(jobs.err().unwrap()); 81 | } 82 | let jobs_unwrapped = jobs.unwrap().iter().map(|job| { 83 | Job { 84 | uuid: job.uuid, 85 | job_type_uuid: job.job_type_uuid, 86 | job_type: None, 87 | arguments: job.arguments.clone(), 88 | executing_node: job.executing_node, 89 | enqueued_at: job.enqueued_at, 90 | started_at: job.started_at, 91 | ended_at: job.ended_at, 92 | results: Some(Value::Bool(job.results.is_some())), 93 | errors: Some(Value::Bool(job.errors.is_some())), 94 | } 95 | }).collect(); 96 | Ok(IndexResponse { 97 | jobs: jobs_unwrapped, 98 | }) 99 | } 100 | 101 | pub fn get( 102 | req: &mut Request, 103 | _: &(), 104 | ) -> Result> { 105 | let node_type_uuid = get_uuid_from_arg(req, "node_type_uuid")?; 106 | let job_uuid = get_uuid_from_arg(req, "uuid")?; 107 | let mut store = req.extensions 108 | .get::() 109 | .unwrap() 110 | .lock() 111 | .unwrap(); 112 | let current_node_type_uuid = store.get_node().node_type_uuid.unwrap(); 113 | option_translate(redis_error_translate(store.set_node_type_soft(node_type_uuid))?)?; 114 | let job = redis_error_translate(store.get_finished_job(job_uuid)); 115 | option_translate(redis_error_translate(store.set_node_type_soft(current_node_type_uuid))?)?; 116 | if job.is_err() { 117 | return Err(job.err().unwrap()); 118 | } 119 | Ok(option_translate(job.unwrap())?) 120 | } 121 | 122 | #[derive(Debug, Clone, Serialize, Deserialize)] 123 | pub struct PostResponse { 124 | status: String, 125 | uuid: Uuid, 126 | } 127 | 128 | #[derive(Debug, Clone, Serialize, Deserialize)] 129 | pub struct PostBody { 130 | pub job_type_uuid: Uuid, 131 | pub arguments: HashMap, 132 | } 133 | 134 | pub fn post( 135 | req: &mut Request, 136 | body: &PostBody, 137 | ) -> Result> { 138 | let mut store = req.extensions 139 | .get::() 140 | .unwrap() 141 | .lock() 142 | .unwrap(); 143 | let job_type = option_translate(redis_error_translate(store.get_job_type(body.job_type_uuid))?)?; 144 | let job_uuid = Uuid::new_v4(); 145 | let job = Job { 146 | uuid: job_uuid, 147 | job_type_uuid: body.job_type_uuid, 148 | job_type: Some(job_type), 149 | arguments: body.arguments.clone(), 150 | executing_node: None, 151 | enqueued_at: None, 152 | started_at: None, 153 | ended_at: None, 154 | results: None, 155 | errors: None, 156 | }; 157 | redis_error_translate(store.enqueue_job(job))?; 158 | Ok(PostResponse { 159 | status: "ok".to_string(), 160 | uuid: job_uuid, 161 | }) 162 | } 163 | 164 | 165 | #[cfg(test)] 166 | mod tests { 167 | use super::*; 168 | use iron_test::request::{ post, get }; 169 | use iron::{ Headers, headers::ContentType }; 170 | use crate::http::controllers::tests::*; 171 | use crate::config; 172 | use iron::status; 173 | use crate::http::tests::initialize_tests; 174 | use crate::store::{ self, StoreRef, tests::* }; 175 | 176 | #[test] 177 | fn test_jobs_index_queued() -> Result<(), String> { 178 | let mut store: StoreRef = store::init_store_untyped(); 179 | store.clean(); 180 | let test_node_type = make_node_type(&mut store)?; 181 | store.set_node_type(test_node_type.uuid)?; 182 | let test_job_type = make_job_type(&mut store)?; 183 | let mut test_job = make_job(&mut store, &test_job_type)?; 184 | let response = iron_error_translate(get(&*format!("http://{}/api/jobs/{}/queued", &*config::HTTP_BIND_ADDRESS, test_node_type.uuid.hyphenated()), Headers::new(), &initialize_tests(store.replicate()?)))?; 185 | assert_eq!(response.status, Some(status::Ok)); 186 | let body: IndexResponse = parse_body(response.body)?; 187 | test_job.job_type = None; 188 | assert_eq!(body.jobs.len(), 1); 189 | test_job.enqueued_at = body.jobs[0].enqueued_at; 190 | assert_eq!(body, IndexResponse { 191 | jobs: vec![test_job], 192 | }); 193 | assert_eq!(store.get_node().node_type_uuid.unwrap(), test_node_type.uuid); 194 | Ok(()) 195 | } 196 | 197 | #[test] 198 | fn test_jobs_index_in_progress() -> Result<(), String> { 199 | let mut store: StoreRef = store::init_store_untyped(); 200 | store.clean(); 201 | let test_node_type = make_node_type(&mut store)?; 202 | store.set_node_type(test_node_type.uuid)?; 203 | let test_job_type = make_job_type(&mut store)?; 204 | let mut test_job = make_job(&mut store, &test_job_type)?; 205 | store.dequeue_job()?; 206 | let response = iron_error_translate(get(&*format!("http://{}/api/jobs/{}/in_progress", &*config::HTTP_BIND_ADDRESS, test_node_type.uuid.hyphenated()), Headers::new(), &initialize_tests(store.replicate()?)))?; 207 | assert_eq!(response.status, Some(status::Ok)); 208 | let body: IndexResponse = parse_body(response.body)?; 209 | test_job.job_type = None; 210 | assert_eq!(body.jobs.len(), 1); 211 | test_job.enqueued_at = body.jobs[0].enqueued_at; 212 | test_job.started_at = body.jobs[0].started_at; 213 | test_job.executing_node = body.jobs[0].executing_node; 214 | assert_eq!(body, IndexResponse { 215 | jobs: vec![test_job], 216 | }); 217 | assert_eq!(store.get_node().node_type_uuid.unwrap(), test_node_type.uuid); 218 | Ok(()) 219 | } 220 | 221 | #[test] 222 | fn test_jobs_index_finished() -> Result<(), String> { 223 | let mut store: StoreRef = store::init_store_untyped(); 224 | store.clean(); 225 | let test_node_type = make_node_type(&mut store)?; 226 | store.set_node_type(test_node_type.uuid)?; 227 | let test_job_type = make_job_type(&mut store)?; 228 | let mut test_job = make_job(&mut store, &test_job_type)?; 229 | store.dequeue_job()?; 230 | store.finish_job(test_job.clone(), Some(Value::String("output".to_string())), Some(Value::String("errors".to_string())))?; 231 | 232 | let response = iron_error_translate(get(&*format!("http://{}/api/jobs/{}/finished", &*config::HTTP_BIND_ADDRESS, test_node_type.uuid.hyphenated()), Headers::new(), &initialize_tests(store.replicate()?)))?; 233 | assert_eq!(response.status, Some(status::Ok)); 234 | let body: IndexResponse = parse_body(response.body)?; 235 | test_job.job_type = None; 236 | assert_eq!(body.jobs.len(), 1); 237 | test_job.enqueued_at = body.jobs[0].enqueued_at; 238 | test_job.started_at = body.jobs[0].started_at; 239 | test_job.ended_at = body.jobs[0].ended_at; 240 | test_job.executing_node = body.jobs[0].executing_node; 241 | test_job.results = Some(Value::Bool(true)); 242 | test_job.errors = Some(Value::Bool(true)); 243 | assert_eq!(body, IndexResponse { 244 | jobs: vec![test_job], 245 | }); 246 | assert_eq!(store.get_node().node_type_uuid.unwrap(), test_node_type.uuid); 247 | Ok(()) 248 | } 249 | 250 | #[test] 251 | fn test_jobs_get() -> Result<(), String> { 252 | let mut store: StoreRef = store::init_store_untyped(); 253 | store.clean(); 254 | let test_node_type = make_node_type(&mut store)?; 255 | store.set_node_type(test_node_type.uuid)?; 256 | let test_job_type = make_job_type(&mut store)?; 257 | let mut test_job = make_job(&mut store, &test_job_type)?; 258 | store.dequeue_job()?; 259 | store.finish_job(test_job.clone(), Some(Value::String("output".to_string())), Some(Value::String("errors".to_string())))?; 260 | 261 | let response = iron_error_translate(get(&*format!("http://{}/api/jobs/{}/{}", &*config::HTTP_BIND_ADDRESS, test_node_type.uuid.hyphenated(), test_job.uuid.hyphenated()), Headers::new(), &initialize_tests(store)))?; 262 | assert_eq!(response.status, Some(status::Ok)); 263 | let body: Job = parse_body(response.body)?; 264 | test_job.job_type = None; 265 | test_job.enqueued_at = body.enqueued_at; 266 | test_job.started_at = body.started_at; 267 | test_job.ended_at = body.ended_at; 268 | test_job.executing_node = body.executing_node; 269 | test_job.results = Some(Value::String("output".to_string())); 270 | test_job.errors = Some(Value::String("errors".to_string())); 271 | assert_eq!(body, test_job); 272 | Ok(()) 273 | } 274 | 275 | #[test] 276 | fn test_jobs_post() -> Result<(), String> { 277 | let mut store: StoreRef = store::init_store_untyped(); 278 | store.clean(); 279 | let test_node_type = make_node_type(&mut store)?; 280 | store.set_node_type(test_node_type.uuid)?; 281 | let test_job_type = make_job_type(&mut store)?; 282 | 283 | let test_job = PostBody { 284 | job_type_uuid: test_job_type.uuid, 285 | arguments: HashMap::new(), 286 | }; 287 | let test_job_serialized = serde_json::to_string(&test_job).unwrap(); 288 | 289 | let mut headers = Headers::new(); 290 | headers.set::(ContentType::json()); 291 | let response = iron_error_translate(post(&*format!("http://{}/api/jobs", &*config::HTTP_BIND_ADDRESS), headers, &*test_job_serialized, &initialize_tests(store.replicate()?)))?; 292 | assert_eq!(response.status, Some(status::Ok)); 293 | let body: PostResponse = parse_body(response.body)?; 294 | let new_job = store.dequeue_job()?; 295 | assert_eq!(new_job.uuid, body.uuid); 296 | assert_eq!(new_job.job_type_uuid, test_job_type.uuid); 297 | assert_eq!(new_job.arguments, test_job.arguments); 298 | Ok(()) 299 | } 300 | 301 | } 302 | -------------------------------------------------------------------------------- /src/http/controllers/api/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod job_types; 2 | pub mod jobs; 3 | pub mod node_types; 4 | pub mod nodes; 5 | pub mod schedule; 6 | 7 | use router::Router; 8 | use crate::http::helpers::control::status_error; 9 | use iron::prelude::*; 10 | use iron::status; 11 | use uuid::Uuid; 12 | use log::*; 13 | 14 | pub fn get_uuid_from_arg(req: &Request, key: &str) -> Result> { 15 | let uuid_str = req.extensions.get::().unwrap().find(key); 16 | if uuid_str.is_none() { 17 | return Err(status_error(status::BadRequest)); 18 | } 19 | let uuid = Uuid::parse_str(uuid_str.unwrap()); 20 | if uuid.is_err() { 21 | warn!("Invalid UUID: {}", uuid_str.unwrap()); 22 | return Err(status_error(status::BadRequest)); 23 | } 24 | return Ok(uuid.unwrap()); 25 | } 26 | 27 | pub fn redis_error_translate(result: Result) -> Result> { 28 | match result { 29 | Err(e) => { 30 | error!("Redis server failed during API request: {}", e); 31 | Err(status_error(status::InternalServerError)) 32 | }, 33 | Ok(value) => { 34 | Ok(value) 35 | }, 36 | } 37 | } 38 | 39 | pub fn option_translate(option: Option) -> Result> { 40 | match option { 41 | None => Err(status_error(status::NotFound)), 42 | Some(value) => Ok(value), 43 | } 44 | } -------------------------------------------------------------------------------- /src/http/controllers/api/node_types.rs: -------------------------------------------------------------------------------- 1 | use crate::http::middleware::redis::IronRedis; 2 | use iron::prelude::*; 3 | use serde::{Deserialize, Serialize}; 4 | use crate::exec::node_type::NodeType; 5 | use iron::status; 6 | use crate::http::helpers::control::status_error; 7 | use log::*; 8 | use super::{ get_uuid_from_arg, redis_error_translate, option_translate }; 9 | 10 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] 11 | pub struct IndexResponse { 12 | node_types: Vec, 13 | } 14 | 15 | pub fn index( 16 | req: &mut Request, 17 | _: &(), 18 | ) -> Result> { 19 | let mut store = req.extensions 20 | .get::() 21 | .unwrap() 22 | .lock() 23 | .unwrap(); 24 | let node_types = redis_error_translate(store.get_node_types())?; 25 | Ok(IndexResponse { 26 | node_types: node_types, 27 | }) 28 | } 29 | 30 | pub fn get( 31 | req: &mut Request, 32 | _: &(), 33 | ) -> Result> { 34 | let uuid = get_uuid_from_arg(req, "uuid")?; 35 | let mut store = req.extensions 36 | .get::() 37 | .unwrap() 38 | .lock() 39 | .unwrap(); 40 | let node_type = option_translate(redis_error_translate(store.get_node_type(uuid))?)?; 41 | Ok(node_type) 42 | } 43 | 44 | #[derive(Debug, Clone, Serialize, Deserialize)] 45 | pub struct PostResponse { 46 | status: String, 47 | } 48 | 49 | pub fn post( 50 | req: &mut Request, 51 | body: &NodeType, 52 | ) -> Result> { 53 | let uuid = get_uuid_from_arg(req, "uuid")?; 54 | if body.uuid != uuid { 55 | warn!("UUID in POST body and URL must match."); 56 | return Err(status_error(status::BadRequest)); 57 | } 58 | let mut store = req.extensions 59 | .get::() 60 | .unwrap() 61 | .lock() 62 | .unwrap(); 63 | redis_error_translate(store.new_node_type(body))?; 64 | Ok(PostResponse { 65 | status: "ok".to_string(), 66 | }) 67 | } 68 | 69 | 70 | #[cfg(test)] 71 | mod tests { 72 | use super::*; 73 | use iron_test::request::{ post, get }; 74 | use iron::{ Headers, headers::ContentType }; 75 | use crate::http::controllers::tests::*; 76 | use crate::config; 77 | use iron::status; 78 | use crate::http::tests::initialize_tests; 79 | use crate::store::{ self, StoreRef, tests::* }; 80 | use uuid::Uuid; 81 | 82 | #[test] 83 | fn test_node_types_index() -> Result<(), String> { 84 | let mut store: StoreRef = store::init_store_untyped(); 85 | store.clean(); 86 | let test_node_type = make_node_type(&mut store)?; 87 | store.set_node_type(test_node_type.uuid)?; 88 | 89 | let response = iron_error_translate(get(&*format!("http://{}/api/node_types", &*config::HTTP_BIND_ADDRESS), Headers::new(), &initialize_tests(store)))?; 90 | assert_eq!(response.status, Some(status::Ok)); 91 | let body: IndexResponse = parse_body(response.body)?; 92 | assert_eq!(body, IndexResponse { 93 | node_types: vec![test_node_type], 94 | }); 95 | Ok(()) 96 | } 97 | 98 | #[test] 99 | fn test_node_types_get() -> Result<(), String> { 100 | let mut store: StoreRef = store::init_store_untyped(); 101 | store.clean(); 102 | let test_node_type = make_node_type(&mut store)?; 103 | store.set_node_type(test_node_type.uuid)?; 104 | let store_node = store.get_node().clone(); 105 | 106 | let response = iron_error_translate(get(&*format!("http://{}/api/node_types/{}", &*config::HTTP_BIND_ADDRESS, store_node.node_type_uuid.unwrap().hyphenated()), Headers::new(), &initialize_tests(store)))?; 107 | assert_eq!(response.status, Some(status::Ok)); 108 | let body: NodeType = parse_body(response.body)?; 109 | assert_eq!(body, store_node.node_type.unwrap()); 110 | Ok(()) 111 | } 112 | 113 | #[test] 114 | fn test_node_types_post() -> Result<(), String> { 115 | let mut store: StoreRef = store::init_store_untyped(); 116 | store.clean(); 117 | let test_node_type = NodeType { 118 | name: "test_node_type".to_string(), 119 | uuid: Uuid::new_v4(), 120 | thread_count: 1, 121 | }; 122 | let node_type_serialized = serde_json::to_string(&test_node_type).unwrap(); 123 | 124 | let mut headers = Headers::new(); 125 | headers.set::(ContentType::json()); 126 | let response = iron_error_translate(post(&*format!("http://{}/api/node_types/{}", &*config::HTTP_BIND_ADDRESS, test_node_type.uuid.hyphenated()), headers, &*node_type_serialized, &initialize_tests(store.replicate()?)))?; 127 | assert_eq!(response.status, Some(status::Ok)); 128 | store.set_node_type(test_node_type.uuid)?; 129 | assert_eq!(store.get_node().node_type.as_ref().unwrap().clone(), test_node_type); 130 | Ok(()) 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/http/controllers/api/nodes.rs: -------------------------------------------------------------------------------- 1 | use crate::http::middleware::redis::IronRedis; 2 | use iron::prelude::*; 3 | use serde::{Deserialize, Serialize}; 4 | use crate::exec::node::Node; 5 | use super::{ get_uuid_from_arg, redis_error_translate, option_translate }; 6 | 7 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] 8 | pub struct IndexResponse { 9 | nodes: Vec, 10 | } 11 | 12 | pub fn index( 13 | req: &mut Request, 14 | _: &(), 15 | ) -> Result> { 16 | let mut store = req.extensions 17 | .get::() 18 | .unwrap() 19 | .lock() 20 | .unwrap(); 21 | let nodes = redis_error_translate(store.get_nodes())?; 22 | Ok(IndexResponse { 23 | nodes: nodes, 24 | }) 25 | } 26 | 27 | pub fn get( 28 | req: &mut Request, 29 | _: &(), 30 | ) -> Result> { 31 | let uuid = get_uuid_from_arg(req, "uuid")?; 32 | let mut store = req.extensions 33 | .get::() 34 | .unwrap() 35 | .lock() 36 | .unwrap(); 37 | let node = option_translate(redis_error_translate(store.get_other_node(uuid))?)?; 38 | Ok(node) 39 | } 40 | 41 | 42 | #[cfg(test)] 43 | mod tests { 44 | use super::*; 45 | use iron_test::request::get; 46 | use iron::Headers; 47 | use crate::http::controllers::tests::*; 48 | use crate::config; 49 | use iron::status; 50 | use crate::http::tests::initialize_tests; 51 | use crate::store::{ self, StoreRef, tests::* }; 52 | 53 | #[test] 54 | fn test_nodes_index() -> Result<(), String> { 55 | let mut store: StoreRef = store::init_store_untyped(); 56 | store.clean(); 57 | let test_node_type = make_node_type(&mut store)?; 58 | store.set_node_type(test_node_type.uuid)?; 59 | let nodes = store.get_nodes()?; 60 | assert_eq!(nodes.len(), 1); 61 | let store_node = store.get_node().clone(); 62 | 63 | let response = iron_error_translate(get(&*format!("http://{}/api/nodes", &*config::HTTP_BIND_ADDRESS), Headers::new(), &initialize_tests(store)))?; 64 | assert_eq!(response.status, Some(status::Ok)); 65 | let body: IndexResponse = parse_body(response.body)?; 66 | assert_eq!(body, IndexResponse { 67 | nodes: vec![Node { node_type: None, ..store_node }], 68 | }); 69 | Ok(()) 70 | } 71 | 72 | #[test] 73 | fn test_nodes_get() -> Result<(), String> { 74 | let mut store: StoreRef = store::init_store_untyped(); 75 | store.clean(); 76 | let test_node_type = make_node_type(&mut store)?; 77 | store.set_node_type(test_node_type.uuid)?; 78 | let nodes = store.get_nodes()?; 79 | assert_eq!(nodes.len(), 1); 80 | let store_node = store.get_node().clone(); 81 | 82 | let response = iron_error_translate(get(&*format!("http://{}/api/nodes/{}", &*config::HTTP_BIND_ADDRESS, store_node.uuid.hyphenated()), Headers::new(), &initialize_tests(store)))?; 83 | assert_eq!(response.status, Some(status::Ok)); 84 | let body: Node = parse_body(response.body)?; 85 | assert_eq!(body, Node { node_type: None, ..store_node }); 86 | Ok(()) 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/http/controllers/api/schedule.rs: -------------------------------------------------------------------------------- 1 | /* 2 | router.get("/api/schedules", serialize_wrap(api::schedule::index), "schedule#index"); 3 | router.get("/api/schedules/:uuid", serialize_wrap(api::schedule::get), "schedule#get"); 4 | router.delete("/api/schedules/:uuid", serialize_wrap(api::schedule::get), "schedule#delete"); 5 | router.post("/api/schedules", json_wrap(api::schedule::post), "schedule#post"); 6 | 7 | */ 8 | 9 | use crate::http::middleware::redis::IronRedis; 10 | use iron::prelude::*; 11 | use serde::{Deserialize, Serialize}; 12 | use crate::scheduler::ScheduleItem; 13 | use uuid::Uuid; 14 | use std::collections::HashMap; 15 | use serde_json::Value; 16 | use super::{ get_uuid_from_arg, redis_error_translate, option_translate }; 17 | 18 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] 19 | pub struct IndexResponse { 20 | schedules: Vec, 21 | } 22 | 23 | pub fn index( 24 | req: &mut Request, 25 | _: &(), 26 | ) -> Result> { 27 | let mut store = req.extensions 28 | .get::() 29 | .unwrap() 30 | .lock() 31 | .unwrap(); 32 | let job_types = redis_error_translate(store.get_job_schedule())?; 33 | Ok(IndexResponse { 34 | schedules: job_types, 35 | }) 36 | } 37 | 38 | pub fn get( 39 | req: &mut Request, 40 | _: &(), 41 | ) -> Result> { 42 | let uuid = get_uuid_from_arg(req, "uuid")?; 43 | let mut store = req.extensions 44 | .get::() 45 | .unwrap() 46 | .lock() 47 | .unwrap(); 48 | let schedule_item = option_translate( 49 | redis_error_translate(store.get_job_schedule_item(uuid))? 50 | )?; 51 | Ok(schedule_item) 52 | } 53 | 54 | #[derive(Debug, Clone, Serialize, Deserialize)] 55 | pub struct PostResponse { 56 | status: String, 57 | uuid: Uuid, 58 | } 59 | 60 | #[derive(Debug, Clone, Serialize, Deserialize)] 61 | pub struct PostBody { 62 | pub interval: u64, 63 | pub job_type_uuid: Uuid, 64 | pub job_arguments: HashMap, 65 | } 66 | 67 | pub fn post( 68 | req: &mut Request, 69 | body: &PostBody, 70 | ) -> Result> { 71 | let mut store = req.extensions 72 | .get::() 73 | .unwrap() 74 | .lock() 75 | .unwrap(); 76 | option_translate( 77 | redis_error_translate(store.get_job_type(body.job_type_uuid))? 78 | )?; 79 | let schedule_item = ScheduleItem { 80 | uuid: Uuid::new_v4(), 81 | interval: body.interval, 82 | job_type_uuid: body.job_type_uuid, 83 | job_arguments: body.job_arguments.clone(), 84 | last_scheduled_at: None, 85 | last_scheduled_by: None, 86 | }; 87 | redis_error_translate(store.new_job_schedule_item(&schedule_item))?; 88 | Ok(PostResponse { 89 | status: "ok".to_string(), 90 | uuid: schedule_item.uuid, 91 | }) 92 | } 93 | 94 | pub fn delete( 95 | req: &mut Request, 96 | _: &(), 97 | ) -> Result> { 98 | let uuid = get_uuid_from_arg(req, "uuid")?; 99 | let mut store = req.extensions 100 | .get::() 101 | .unwrap() 102 | .lock() 103 | .unwrap(); 104 | redis_error_translate(store.delete_job_schedule_item(uuid))?; 105 | Ok(PostResponse { 106 | status: "ok".to_string(), 107 | uuid: uuid, 108 | }) 109 | } 110 | 111 | #[cfg(test)] 112 | mod tests { 113 | use super::*; 114 | use iron_test::request::{ post, get, delete }; 115 | use iron::{ Headers, headers::ContentType }; 116 | use crate::http::controllers::tests::*; 117 | use crate::config; 118 | use iron::status; 119 | use crate::http::tests::initialize_tests; 120 | use crate::store::{ self, StoreRef, tests::* }; 121 | 122 | #[test] 123 | fn test_schedule_item_index() -> Result<(), String> { 124 | let mut store: StoreRef = store::init_store_untyped(); 125 | store.clean(); 126 | let test_node_type = make_node_type(&mut store)?; 127 | store.set_node_type(test_node_type.uuid)?; 128 | let test_job_type = make_job_type(&mut store)?; 129 | let test_schedule = make_schedule_item(&mut store, test_job_type.uuid, None, None)?; 130 | 131 | let response = iron_error_translate(get(&*format!("http://{}/api/schedules", &*config::HTTP_BIND_ADDRESS), Headers::new(), &initialize_tests(store)))?; 132 | assert_eq!(response.status, Some(status::Ok)); 133 | let body: IndexResponse = parse_body(response.body)?; 134 | assert_eq!(body, IndexResponse { 135 | schedules: vec![test_schedule], 136 | }); 137 | Ok(()) 138 | } 139 | 140 | #[test] 141 | fn test_schedule_item_get() -> Result<(), String> { 142 | let mut store: StoreRef = store::init_store_untyped(); 143 | store.clean(); 144 | let test_node_type = make_node_type(&mut store)?; 145 | store.set_node_type(test_node_type.uuid)?; 146 | let test_job_type = make_job_type(&mut store)?; 147 | let test_schedule = make_schedule_item(&mut store, test_job_type.uuid, None, None)?; 148 | 149 | let response = iron_error_translate(get(&*format!("http://{}/api/schedules/{}", &*config::HTTP_BIND_ADDRESS, test_schedule.uuid.hyphenated()), Headers::new(), &initialize_tests(store)))?; 150 | assert_eq!(response.status, Some(status::Ok)); 151 | let body: ScheduleItem = parse_body(response.body)?; 152 | assert_eq!(body, test_schedule); 153 | Ok(()) 154 | } 155 | 156 | #[test] 157 | fn test_schedule_item_post() -> Result<(), String> { 158 | let mut store: StoreRef = store::init_store_untyped(); 159 | store.clean(); 160 | let test_node_type = make_node_type(&mut store)?; 161 | store.set_node_type(test_node_type.uuid)?; 162 | let test_job_type = make_job_type(&mut store)?; 163 | 164 | let test_schedule_item = PostBody { 165 | interval: 1000, 166 | job_type_uuid: test_job_type.uuid, 167 | job_arguments: HashMap::new(), 168 | }; 169 | let test_schedule_item_serialized = serde_json::to_string(&test_schedule_item).unwrap(); 170 | 171 | let mut headers = Headers::new(); 172 | headers.set::(ContentType::json()); 173 | let response = iron_error_translate(post(&*format!("http://{}/api/schedules", &*config::HTTP_BIND_ADDRESS), headers, &*test_schedule_item_serialized, &initialize_tests(store.replicate()?)))?; 174 | assert_eq!(response.status, Some(status::Ok)); 175 | let body: PostResponse = parse_body(response.body)?; 176 | let new_job = store.get_job_schedule_item(body.uuid)?.unwrap(); 177 | assert_eq!(new_job, ScheduleItem { 178 | uuid: body.uuid, 179 | interval: test_schedule_item.interval, 180 | job_type_uuid: test_schedule_item.job_type_uuid, 181 | job_arguments: test_schedule_item.job_arguments, 182 | last_scheduled_at: None, 183 | last_scheduled_by: None, 184 | }); 185 | Ok(()) 186 | } 187 | 188 | #[test] 189 | fn test_schedule_item_delete() -> Result<(), String> { 190 | let mut store: StoreRef = store::init_store_untyped(); 191 | store.clean(); 192 | let test_node_type = make_node_type(&mut store)?; 193 | store.set_node_type(test_node_type.uuid)?; 194 | let test_job_type = make_job_type(&mut store)?; 195 | let test_schedule = make_schedule_item(&mut store, test_job_type.uuid, None, None)?; 196 | 197 | let response = iron_error_translate(delete(&*format!("http://{}/api/schedules/{}", &*config::HTTP_BIND_ADDRESS, test_schedule.uuid.hyphenated()), Headers::new(), &initialize_tests(store.replicate()?)))?; 198 | assert_eq!(response.status, Some(status::Ok)); 199 | assert_eq!(store.get_job_schedule_item(test_schedule.uuid)?, None); 200 | Ok(()) 201 | } 202 | 203 | } 204 | -------------------------------------------------------------------------------- /src/http/controllers/health.rs: -------------------------------------------------------------------------------- 1 | use iron::mime::*; 2 | use iron::prelude::*; 3 | use iron::status; 4 | 5 | pub fn handle(_: &mut Request) -> IronResult { 6 | Ok(Response::with(( 7 | Mime(TopLevel::Text, SubLevel::Plain, vec![]), 8 | status::Ok, 9 | "ok", 10 | ))) 11 | } 12 | 13 | #[cfg(test)] 14 | mod tests { 15 | use super::*; 16 | use iron_test::request::get; 17 | use iron::Headers; 18 | use crate::http::controllers::tests::stringify_body; 19 | use crate::config; 20 | 21 | const ROUTE: &str = "/health"; 22 | 23 | #[test] 24 | fn test_can_get_health() -> Result<(), IronError> { 25 | let response = get(&*format!("http://{}{}", &*config::HTTP_BIND_ADDRESS, ROUTE), Headers::new(), &super::handle)?; 26 | assert_eq!(response.status, Some(status::Ok)); 27 | let body = stringify_body(response.body); 28 | assert_eq!(body, "ok"); 29 | Ok(()) 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/http/controllers/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod health; 2 | pub mod api; 3 | 4 | #[cfg(test)] 5 | mod tests { 6 | use iron::response::WriteBody; 7 | use std::io::{ self, Write }; 8 | use serde::de; 9 | use iron::IronError; 10 | 11 | struct WriteProxy { 12 | all_data: Vec, 13 | } 14 | 15 | impl Write for WriteProxy { 16 | fn write(&mut self, data: &[u8]) -> Result { 17 | self.all_data.append(&mut data.to_vec()); 18 | Ok(data.len()) 19 | } 20 | 21 | fn flush(&mut self) -> Result<(), io::Error> { 22 | Ok(()) 23 | } 24 | } 25 | 26 | pub fn stringify_body(body: Option>) -> String { 27 | let mut write_proxy = WriteProxy { 28 | all_data: vec![] 29 | }; 30 | match body { 31 | Some(mut write_body) => { 32 | write_body.write_body(&mut write_proxy).unwrap(); 33 | } 34 | None => () 35 | } 36 | return (&*String::from_utf8_lossy(&write_proxy.all_data)).to_string(); 37 | } 38 | 39 | pub fn parse_body(body: Option>) -> Result { 40 | let stringified = stringify_body(body); 41 | let deserialized = serde_json::from_str(&*stringified); 42 | match deserialized { 43 | Err(e) => { 44 | Err(format!("{:?}", e)) 45 | } 46 | Ok(value) => { 47 | Ok(value) 48 | } 49 | } 50 | } 51 | 52 | pub fn iron_error_translate(result: Result) -> Result { 53 | match result { 54 | Err(e) => { 55 | Err(format!("{:?}", e)) 56 | }, 57 | Ok(value) => { 58 | Ok(value) 59 | }, 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/http/helpers/control.rs: -------------------------------------------------------------------------------- 1 | use iron::error::Error; 2 | use iron::prelude::*; 3 | use iron::status; 4 | use std::fmt; 5 | 6 | struct StatusError { 7 | status: String, 8 | } 9 | 10 | impl Error for StatusError { 11 | fn description(&self) -> &str { 12 | return &*self.status; 13 | } 14 | } 15 | 16 | impl fmt::Display for StatusError { 17 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 18 | write!(f, "{}", self.status) 19 | } 20 | } 21 | 22 | impl fmt::Debug for StatusError { 23 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 24 | write!(f, "{}", self.status) 25 | } 26 | } 27 | 28 | pub fn status_error(http_status: status::Status) -> Result { 29 | return Err(IronError::new( 30 | Box::new(StatusError { 31 | status: format!("{}", http_status), 32 | }), 33 | http_status, 34 | )); 35 | } 36 | -------------------------------------------------------------------------------- /src/http/helpers/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod control; 2 | pub mod post_wrapper; 3 | -------------------------------------------------------------------------------- /src/http/helpers/post_wrapper.rs: -------------------------------------------------------------------------------- 1 | use super::control::status_error; 2 | use iron::mime::*; 3 | use iron::prelude::*; 4 | use iron::status; 5 | use iron::Handler; 6 | use log::*; 7 | use serde::{de, Serialize}; 8 | use std::fmt::Debug; 9 | 10 | pub struct WrappedHandler { 11 | handler: fn(&mut Request, &T) -> Result>, 12 | allow_empty: bool, 13 | empty_default: Option, 14 | } 15 | 16 | impl Handler 17 | for WrappedHandler 18 | { 19 | fn handle(&self, req: &mut Request) -> IronResult { 20 | let maybe_body = req.get::>(); 21 | if maybe_body.is_err() { 22 | error!("decoding body failed: {:?}", maybe_body); 23 | return status_error(status::BadRequest); 24 | } 25 | let optionally_body = maybe_body.unwrap(); 26 | let body = if self.allow_empty { 27 | match optionally_body { 28 | Some(s) => s, 29 | None => self.empty_default.clone().unwrap(), 30 | } 31 | } else { 32 | if optionally_body.is_none() { 33 | return status_error(status::BadRequest); 34 | } 35 | optionally_body.unwrap() 36 | }; 37 | let response = (self.handler)(req, &body); 38 | match response { 39 | Ok(data) => Ok(Response::with(( 40 | Mime(TopLevel::Application, SubLevel::Json, vec![]), 41 | status::Ok, 42 | serde_json::to_string(&data).unwrap(), 43 | ))), 44 | Err(data) => data, 45 | } 46 | } 47 | } 48 | 49 | type HandleFunc = fn(&mut Request, &T) -> Result>; 50 | 51 | pub fn json_wrap( 52 | handler: HandleFunc, 53 | ) -> WrappedHandler { 54 | WrappedHandler { handler, allow_empty: false, empty_default: None } 55 | } 56 | 57 | // NoDeserialize 58 | pub fn serialize_wrap(handler: HandleFunc<(), K>) -> WrappedHandler<(), K> { 59 | WrappedHandler { handler, allow_empty: true, empty_default: Some(()) } 60 | } 61 | -------------------------------------------------------------------------------- /src/http/middleware/api_auth.rs: -------------------------------------------------------------------------------- 1 | use super::super::helpers::control::status_error; 2 | use crate::util::config; 3 | use iron::headers::{Authorization, Bearer}; 4 | use iron::prelude::*; 5 | use iron::status; 6 | 7 | pub struct ApiAuth; 8 | 9 | impl iron::BeforeMiddleware for ApiAuth { 10 | fn before(&self, req: &mut Request) -> IronResult<()> { 11 | let maybe_auth = req.headers.get::>(); 12 | if maybe_auth.is_none() { 13 | return status_error(status::Unauthorized); 14 | } 15 | let auth = maybe_auth.unwrap(); 16 | if (*auth).token != *config::HTTP_API_KEY { 17 | return status_error(status::Unauthorized); 18 | } 19 | return Ok(()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/http/middleware/assert_json.rs: -------------------------------------------------------------------------------- 1 | use super::super::helpers::control::status_error; 2 | use iron::headers::ContentType; 3 | use iron::method::Method; 4 | use iron::prelude::*; 5 | use iron::status; 6 | 7 | pub struct AssertJson; 8 | 9 | impl iron::BeforeMiddleware for AssertJson { 10 | fn before(&self, req: &mut Request) -> IronResult<()> { 11 | if req.method == Method::Post 12 | && !req 13 | .headers 14 | .get::() 15 | .map(|t| *t == ContentType::json()) 16 | .unwrap_or(false) 17 | { 18 | status_error(status::UnsupportedMediaType) 19 | } else { 20 | Ok(()) 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/http/middleware/logger.rs: -------------------------------------------------------------------------------- 1 | use iron::prelude::*; 2 | use iron::status; 3 | use log::*; 4 | use crate::util::time::epoch_us; 5 | 6 | pub struct Logger; 7 | 8 | impl iron::typemap::Key for Logger { 9 | type Value = u64; 10 | } 11 | 12 | impl iron::BeforeMiddleware for Logger { 13 | fn before(&self, req: &mut Request) -> IronResult<()> { 14 | req.extensions.insert::(epoch_us()); 15 | Ok(()) 16 | } 17 | } 18 | 19 | impl iron::AfterMiddleware for Logger { 20 | fn after(&self, req: &mut Request, res: Response) -> IronResult { 21 | let delta = epoch_us() - *req.extensions.get::().unwrap(); 22 | info!( 23 | "'{}': {} /{}, got {}, took: {} ms", 24 | req.remote_addr.ip(), 25 | req.method.as_ref(), 26 | req.url.path().join("/"), 27 | res.status.unwrap_or(status::Ok), 28 | (delta as f64) / 1000.0 29 | ); 30 | Ok(res) 31 | } 32 | 33 | fn catch(&self, req: &mut Request, err: IronError) -> IronResult { 34 | let delta = epoch_us() - *req.extensions.get::().unwrap(); 35 | warn!( 36 | "'{}': {} /{}, got {}, took: {} ms, error: {}", 37 | req.remote_addr.ip(), 38 | req.method.as_ref(), 39 | req.url.path().join("/"), 40 | err.response.status.unwrap_or(status::Ok), 41 | (delta as f64) / 1000.0, 42 | err.error 43 | ); 44 | Ok(err.response) // avoid iron's default log 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/http/middleware/mod.rs: -------------------------------------------------------------------------------- 1 | mod api_auth; 2 | mod assert_json; 3 | mod logger; 4 | pub mod redis; 5 | 6 | use iron::prelude::*; 7 | use persistent::Read; 8 | use std::sync::{ Arc, Mutex }; 9 | use crate::store::StoreRef; 10 | 11 | pub fn add_middleware(chain: &mut Chain, store: Arc>) { 12 | chain.link_before(logger::Logger); 13 | chain.link_before(api_auth::ApiAuth); 14 | chain.link_before(Read::::one(1024 * 1024 * 50)); 15 | chain.link_before(assert_json::AssertJson); 16 | chain.link_before(redis::IronRedis { binder: store }); 17 | chain.link_after(logger::Logger); 18 | } 19 | 20 | #[cfg(test)] 21 | pub mod tests { 22 | use super::*; 23 | 24 | pub fn add_middleware_test(chain: &mut Chain, store: Arc>) { 25 | chain.link_before(logger::Logger); 26 | chain.link_before(Read::::one(1024 * 1024 * 50)); 27 | chain.link_before(assert_json::AssertJson); 28 | chain.link_before(redis::IronRedis { binder: store }); 29 | chain.link_after(logger::Logger); 30 | } 31 | } -------------------------------------------------------------------------------- /src/http/middleware/redis.rs: -------------------------------------------------------------------------------- 1 | use iron::prelude::*; 2 | use std::sync::{ Arc, Mutex }; 3 | use crate::store::StoreRef; 4 | 5 | pub struct IronRedis { 6 | pub binder: Arc>, 7 | } 8 | 9 | impl iron::typemap::Key for IronRedis { 10 | type Value = Arc>; 11 | } 12 | 13 | impl iron::BeforeMiddleware for IronRedis { 14 | fn before(&self, req: &mut Request) -> IronResult<()> { 15 | req.extensions.insert::(self.binder.clone()); 16 | Ok(()) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/http/mod.rs: -------------------------------------------------------------------------------- 1 | mod routes; 2 | mod middleware; 3 | mod helpers; 4 | mod controllers; 5 | 6 | use router::Router; 7 | use iron::prelude::*; 8 | use std::thread; 9 | use crate::util::config; 10 | use crate::store::StoreRef; 11 | use log::*; 12 | use std::sync::{ Arc, Mutex }; 13 | 14 | pub fn initialize(store: StoreRef) { 15 | // routes 16 | let mut router = Router::new(); 17 | routes::add_routes(&mut router); 18 | 19 | // middleware 20 | let mut chain = Chain::new(router); 21 | middleware::add_middleware(&mut chain, Arc::new(Mutex::new(store))); 22 | 23 | info!("Listening on {}!", &*config::HTTP_BIND_ADDRESS); 24 | Iron::new(chain).http(&*config::HTTP_BIND_ADDRESS).unwrap(); 25 | } 26 | 27 | 28 | pub fn start_thread(store: StoreRef) { 29 | thread::spawn(move || { 30 | initialize(store); 31 | }); 32 | } 33 | 34 | #[cfg(test)] 35 | pub mod tests { 36 | use super::*; 37 | use iron::Handler; 38 | 39 | pub fn initialize_tests(store: StoreRef) -> Box { 40 | // routes 41 | let mut router = Router::new(); 42 | routes::add_routes(&mut router); 43 | 44 | // middleware 45 | let mut chain = Chain::new(router); 46 | middleware::tests::add_middleware_test(&mut chain, Arc::new(Mutex::new(store))); 47 | Box::new(chain) 48 | } 49 | } -------------------------------------------------------------------------------- /src/http/routes.rs: -------------------------------------------------------------------------------- 1 | use super::controllers::*; 2 | use super::helpers::post_wrapper::*; 3 | use router::Router; 4 | 5 | pub fn add_routes(router: &mut Router) { 6 | router.get("/api/node_types", serialize_wrap(api::node_types::index), "node_types#index"); 7 | router.get("/api/node_types/:uuid", serialize_wrap(api::node_types::get), "node_types#get"); 8 | router.post("/api/node_types/:uuid", json_wrap(api::node_types::post), "node_types#post"); 9 | 10 | router.get("/api/nodes", serialize_wrap(api::nodes::index), "nodes#index"); 11 | router.get("/api/nodes/:uuid", serialize_wrap(api::nodes::get), "nodes#get"); 12 | 13 | router.get("/api/job_types", serialize_wrap(api::job_types::index), "job_types#index"); 14 | router.get("/api/job_types/:uuid", serialize_wrap(api::job_types::get), "job_types#get"); 15 | router.post("/api/job_types", json_wrap(api::job_types::post), "job_types#post"); 16 | 17 | router.get("/api/jobs/:node_type_uuid/queued", serialize_wrap(api::jobs::index_queued), "jobs#index_queued"); 18 | router.get("/api/jobs/:node_type_uuid/in_progress", serialize_wrap(api::jobs::index_in_progress), "jobs#index_in_progress"); 19 | router.get("/api/jobs/:node_type_uuid/finished", serialize_wrap(api::jobs::index_finished), "jobs#index_finished"); 20 | router.get("/api/jobs/:node_type_uuid/:uuid", serialize_wrap(api::jobs::get), "jobs#get"); // gets only finished jobs, but includes all results/errors, not a boolean presence summary 21 | router.post("/api/jobs", json_wrap(api::jobs::post), "jobs#post"); 22 | 23 | router.get("/api/schedules", serialize_wrap(api::schedule::index), "schedule#index"); 24 | router.get("/api/schedules/:uuid", serialize_wrap(api::schedule::get), "schedule#get"); 25 | router.delete("/api/schedules/:uuid", serialize_wrap(api::schedule::delete), "schedule#delete"); 26 | router.post("/api/schedules", json_wrap(api::schedule::post), "schedule#post"); 27 | 28 | router.get("/health", health::handle, "health"); 29 | } 30 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate lazy_static; 3 | extern crate log; 4 | extern crate serde; 5 | extern crate uuid; 6 | extern crate redis; 7 | extern crate time; 8 | 9 | use env_logger::Builder; 10 | use log::LevelFilter; 11 | use log::*; 12 | use std::thread; 13 | use util::config; 14 | 15 | mod util; 16 | mod store; 17 | mod exec; 18 | mod scheduler; 19 | mod threads; 20 | mod http; 21 | 22 | use store::*; 23 | use store::init_store; 24 | 25 | fn main() { 26 | Builder::from_default_env() 27 | .filter_level(LevelFilter::Info) 28 | .filter_module("hyper::server", LevelFilter::Warn) 29 | .init(); 30 | let mut store = init_store(); 31 | let thread_count = store.get_node().node_type.as_ref().unwrap().thread_count; 32 | info!("Started node '{}'", store.get_node().uuid.hyphenated().to_string()); 33 | threads::ping_thread::start_thread(store.replicate().expect("failed to reconnect to redis")); 34 | threads::scheduler_thread::start_thread(store.replicate().expect("failed to reconnect to redis")); 35 | for _ in 0..thread_count { 36 | threads::worker_thread::start_thread(store.replicate().expect("failed to reconnect to redis")); 37 | } 38 | 39 | if &*config::HTTP_SERVER_ENABLED == "true" { 40 | http::start_thread(store.replicate().expect("failed to reconnect to redis")); 41 | } 42 | 43 | loop { 44 | thread::sleep_ms(1000); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/scheduler/mod.rs: -------------------------------------------------------------------------------- 1 | use serde_json::Value; 2 | use std::collections::HashMap; 3 | use serde::{Deserialize, Serialize}; 4 | use uuid::Uuid; 5 | 6 | #[derive(Deserialize, Serialize, PartialEq, Clone, Debug)] 7 | pub struct ScheduleItem { 8 | pub uuid: Uuid, 9 | pub interval: u64, 10 | pub last_scheduled_by: Option, 11 | pub last_scheduled_at: Option, 12 | pub job_type_uuid: Uuid, 13 | pub job_arguments: HashMap, 14 | } -------------------------------------------------------------------------------- /src/store/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod redis; 2 | 3 | use crate::exec::node_type::NodeType; 4 | use crate::exec::job_type::JobType; 5 | use crate::exec::job::Job; 6 | use crate::scheduler::ScheduleItem; 7 | use uuid::Uuid; 8 | use crate::exec::node::Node; 9 | use serde_json::Value; 10 | use log::*; 11 | use crate::util::config; 12 | use std::process::exit; 13 | 14 | pub trait Store { 15 | fn connect() -> Result where Self: std::marker::Sized; 16 | fn replicate(&self) -> Result; 17 | fn get_node_types(&mut self) -> Result, String>; 18 | fn get_node_type(&mut self, node_type_uuid: Uuid) -> Result, String>; 19 | fn new_node_type(&mut self, node_type: &NodeType) -> Result<(), String>; 20 | fn set_node_type(&mut self, node_type_uuid: Uuid) -> Result, String>; 21 | fn set_node_type_soft(&mut self, node_type_uuid: Uuid) -> Result, String>; // used in some api calls to pretend to be other node types. does not update store. 22 | fn get_job_types(&mut self) -> Result, String>; 23 | // used when we encounter a job in our queue we don't know about 24 | fn get_job_type(&mut self, uuid: Uuid) -> Result, String>; 25 | fn new_job_type(&mut self, job_type: &JobType) -> Result<(), String>; 26 | fn get_job_schedule(&mut self) -> Result, String>; 27 | fn get_job_schedule_item(&mut self, uuid: Uuid) -> Result, String>; 28 | fn delete_job_schedule_item(&mut self, uuid: Uuid) -> Result<(), String>; 29 | fn new_job_schedule_item(&mut self, schedule_item: &ScheduleItem) -> Result<(), String>; 30 | fn claim_job_scheduled(&mut self, schedule_item: &ScheduleItem) -> Result, String>; 31 | fn enqueue_job(&mut self, job: Job) -> Result<(), String>; 32 | fn dequeue_job(&mut self) -> Result; 33 | fn get_all_jobs_waiting(&mut self) -> Result, String>; 34 | fn get_all_jobs_in_progress(&mut self) -> Result, String>; 35 | fn get_all_jobs_finished(&mut self) -> Result, String>; 36 | fn get_finished_job(&mut self, uuid: Uuid) -> Result, String>; 37 | fn finish_job(&mut self, job: Job, results: Option, errors: Option) -> Result<(), String>; 38 | fn ping(&mut self) -> Result<(), String>; 39 | fn get_ping_interval_ms(&self) -> u32; 40 | fn get_node(&mut self) -> &mut Node; 41 | fn get_nodes(&mut self) -> Result, String>; 42 | fn get_other_node(&mut self, uuid: Uuid) -> Result, String>; 43 | fn clean(&mut self); 44 | } 45 | 46 | pub type StoreRef = Box; 47 | 48 | pub fn init_store_untyped() -> StoreRef { 49 | let store: StoreRef; 50 | if &*config::STORE_TYPE == "redis" { 51 | let redis_connected = redis::RedisStore::connect(); 52 | match redis_connected { 53 | Err(e) => { 54 | error!("Error connecting to redis: {}", e); 55 | exit(1); 56 | } 57 | Ok(redis_store) => { 58 | store = Box::new(redis_store); 59 | } 60 | } 61 | } else { 62 | error!("Invalid STORE_TYPE configuration option: {}", &*config::STORE_TYPE); 63 | exit(1); 64 | } 65 | return store; 66 | } 67 | 68 | pub fn init_store() -> StoreRef { 69 | let mut store = init_store_untyped(); 70 | let node_types = store.get_node_types(); 71 | if node_types.is_err() { 72 | error!("Failed to get node types from store: {}", node_types.err().unwrap()); 73 | exit(1); 74 | } 75 | let our_node_type = node_types.as_ref().unwrap().iter().find(|item| item.name == *config::NODE_TYPE); 76 | if our_node_type.is_none() { 77 | error!("Invalid node type specified, not found: {}", *config::NODE_TYPE); 78 | exit(1); 79 | } 80 | let raw_node_type = our_node_type.unwrap(); 81 | let updated_redis_result = store.set_node_type(raw_node_type.uuid); 82 | if updated_redis_result.is_err() { 83 | error!("Failed to update node_type for node in store: {}", updated_redis_result.err().unwrap()); 84 | exit(1); 85 | } 86 | if updated_redis_result.unwrap().is_none() { 87 | error!("Node type UUID was not found: {}", raw_node_type.uuid); 88 | exit(1); 89 | } 90 | return store; 91 | } 92 | 93 | #[cfg(test)] 94 | pub mod tests { 95 | use super::*; 96 | use std::collections::HashMap; 97 | 98 | pub fn make_node_type(store: &mut StoreRef) -> Result { 99 | let test_node_type = NodeType { 100 | name: "test_node_type".to_string(), 101 | uuid: Uuid::new_v4(), 102 | thread_count: 1, 103 | }; 104 | store.new_node_type(&test_node_type)?; 105 | return Ok(test_node_type); 106 | } 107 | 108 | pub fn make_job_type(store: &mut StoreRef) -> Result { 109 | let mut test_job_type = JobType { 110 | executor: "bash".to_string(), 111 | name: "test".to_string(), 112 | node_type: "default".to_string(), 113 | timeout: None, 114 | unique: false, 115 | uuid: Uuid::new_v4(), 116 | metadata: HashMap::new(), 117 | }; 118 | test_job_type.metadata.insert("command".to_string(), Value::String("echo 'test'".to_string())); 119 | store.new_job_type(&test_job_type)?; 120 | return Ok(test_job_type); 121 | } 122 | 123 | pub fn make_job(store: &mut StoreRef, job_type: &JobType) -> Result { 124 | let job = Job { 125 | uuid: Uuid::new_v4(), 126 | job_type_uuid: job_type.uuid, 127 | job_type: Some(job_type.clone()), 128 | arguments: HashMap::new(), 129 | executing_node: None, 130 | enqueued_at: None, 131 | started_at: None, 132 | ended_at: None, 133 | results: None, 134 | errors: None, 135 | }; 136 | store.enqueue_job(job.clone())?; 137 | return Ok(job); 138 | } 139 | 140 | pub fn make_schedule_item(store: &mut StoreRef, job_type_uuid: Uuid, last_scheduled_by: Option, last_scheduled_at: Option) -> Result { 141 | let mut test_schedule_item = ScheduleItem { 142 | uuid: Uuid::new_v4(), 143 | interval: 500, 144 | last_scheduled_by: last_scheduled_by, 145 | last_scheduled_at: last_scheduled_at, 146 | job_type_uuid: job_type_uuid, 147 | job_arguments: HashMap::new(), 148 | }; 149 | test_schedule_item.job_arguments.insert("command".to_string(), Value::String("echo 'test'".to_string())); 150 | store.new_job_schedule_item(&test_schedule_item)?; 151 | return Ok(test_schedule_item); 152 | } 153 | 154 | } -------------------------------------------------------------------------------- /src/store/redis.rs: -------------------------------------------------------------------------------- 1 | use crate::store::*; 2 | use crate::util::config; 3 | use ::redis::{ Client, Connection, Commands }; 4 | use crate::exec::node::Node; 5 | use uuid::Uuid; 6 | use serde_json::Value; 7 | use crate::util::time::epoch; 8 | use std::collections::HashMap; 9 | 10 | pub struct RedisStore { 11 | client: Client, 12 | connection: Connection, 13 | node: Node, 14 | ping_interval: u32, 15 | job_types: HashMap, 16 | } 17 | 18 | fn redis_hcheck_set(connection: &mut Connection, key: String, hkey: String, old_value: Option, new_value: Option) -> Result { 19 | let mut command = ::redis::cmd("EVAL"); 20 | let mut builder = command.arg(" 21 | local c = tostring(redis.call('hget', KEYS[1], KEYS[2])); 22 | if c == ARGV[1] then 23 | redis.call('hset', KEYS[1], KEYS[2], ARGV[2]); 24 | return 'true'; 25 | end 26 | return 'false'; 27 | ").arg(2).arg(key).arg(hkey); 28 | builder = match old_value { 29 | None => builder.arg(false), 30 | Some(s) => builder.arg(s), 31 | }; 32 | builder = match new_value { 33 | None => builder.arg(false), 34 | Some(s) => builder.arg(s), 35 | }; 36 | let redis_result: Result, ::redis::RedisError> = builder.query(connection); 37 | if redis_result.is_err() { 38 | return Err(format!("{:?}", redis_result.err().unwrap())); 39 | } 40 | return Ok(redis_result.unwrap().unwrap_or("false".to_string()) == "true"); 41 | } 42 | 43 | impl Store for RedisStore { 44 | fn connect() -> Result { 45 | let client = Client::open(&*format!("redis://{}:{}/{}", &*config::REDIS_HOST, &*config::REDIS_PORT, &*config::REDIS_DATABASE)); 46 | if client.is_err() { 47 | return Err(format!("{:?}", client.unwrap_err())); 48 | } 49 | let mut connection = client.as_ref().unwrap().get_connection(); 50 | if connection.is_err() { 51 | return Err(format!("{:?}", connection.err().unwrap())); 52 | } 53 | let new_node = Node { uuid: Uuid::new_v4(), last_ping: epoch(), node_type_uuid: None, node_type: None }; 54 | let redis_result: Result<(), ::redis::RedisError> = connection.as_mut().unwrap().hset("nodes", new_node.uuid.hyphenated().to_string(), serde_json::to_string(&new_node).unwrap()); 55 | if redis_result.is_err() { 56 | return Err(format!("{:?}", redis_result.err().unwrap())); 57 | } 58 | return Ok(RedisStore { client: client.unwrap(), connection: connection.unwrap(), node: new_node, ping_interval: 5000, job_types: HashMap::new() }); 59 | } 60 | 61 | fn get_node_types(&mut self) -> Result, String> { 62 | let redis_result: Result, ::redis::RedisError> = self.connection.hgetall("node_types"); 63 | if redis_result.is_err() { 64 | return Err(format!("{:?}", redis_result.err().unwrap())); 65 | } 66 | let raw_redis = redis_result.unwrap(); 67 | let mut output: Vec = vec![]; 68 | let mut current_uuid: &String = &"".to_string(); 69 | for i in 0..raw_redis.len() { 70 | if i % 2 == 0 { 71 | current_uuid = &raw_redis[i]; 72 | } else { 73 | let raw_node_type: Result = serde_json::from_str(&*raw_redis[i]); 74 | if raw_node_type.is_err() { 75 | return Err(format!("{:?}", raw_node_type.err().unwrap())); 76 | } 77 | let node_type = raw_node_type.unwrap(); 78 | if node_type.uuid.hyphenated().to_string() != *current_uuid { 79 | return Err(format!("redis consistency error: hash key '{}' not equal data given name '{}'", node_type.name, *current_uuid)); 80 | } 81 | output.push(node_type); 82 | } 83 | } 84 | return Ok(output); 85 | } 86 | 87 | fn get_node_type(&mut self, node_type_uuid: Uuid) -> Result, String> { 88 | let redis_result: Result, ::redis::RedisError> = self.connection.hget("node_types", node_type_uuid.hyphenated().to_string()); 89 | if redis_result.is_err() { 90 | return Err(format!("{:?}", redis_result.err().unwrap())); 91 | } 92 | if redis_result.as_ref().unwrap().is_none() { 93 | return Ok(None); 94 | } 95 | let raw_node_type: Result = serde_json::from_str(&*redis_result.unwrap().unwrap()); 96 | if raw_node_type.is_err() { 97 | return Err(format!("{:?}", raw_node_type.err().unwrap())); 98 | } 99 | return Ok(Some(raw_node_type.unwrap())); 100 | } 101 | 102 | fn new_node_type(&mut self, node_type: &NodeType) -> Result<(), String> { 103 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hset("node_types", node_type.uuid.hyphenated().to_string(), serde_json::to_string(&node_type).unwrap()); 104 | if redis_result.is_err() { 105 | return Err(format!("{:?}", redis_result.err().unwrap())); 106 | } 107 | return Ok(()); 108 | } 109 | 110 | fn set_node_type(&mut self, node_type_uuid: Uuid) -> Result, String> { 111 | let node_type = self.get_node_type(node_type_uuid)?; 112 | if node_type.is_none() { 113 | return Ok(None); 114 | } 115 | self.node.node_type_uuid = Some(node_type_uuid); 116 | self.node.node_type = node_type; 117 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hset("nodes", self.node.uuid.hyphenated().to_string(), serde_json::to_string(&self.node).unwrap()); 118 | if redis_result.is_err() { 119 | return Err(format!("{:?}", redis_result.err().unwrap())); 120 | } 121 | return Ok(Some(())); 122 | } 123 | 124 | fn set_node_type_soft(&mut self, node_type_uuid: Uuid) -> Result, String> { 125 | let node_type = self.get_node_type(node_type_uuid)?; 126 | if node_type.is_none() { 127 | return Ok(None); 128 | } 129 | self.node.node_type_uuid = Some(node_type_uuid); 130 | self.node.node_type = node_type; 131 | return Ok(Some(())); 132 | } 133 | 134 | fn get_job_types(&mut self) -> Result, String> { 135 | let redis_result: Result, ::redis::RedisError> = self.connection.hgetall("job_types"); 136 | if redis_result.is_err() { 137 | return Err(format!("{:?}", redis_result.err().unwrap())); 138 | } 139 | let raw_redis = redis_result.unwrap(); 140 | let mut output: Vec = vec![]; 141 | let mut current_uuid: &String = &"".to_string(); 142 | for i in 0..raw_redis.len() { 143 | if i % 2 == 0 { 144 | current_uuid = &raw_redis[i]; 145 | } else { 146 | let raw_job_type: Result = serde_json::from_str(&*raw_redis[i]); 147 | if raw_job_type.is_err() { 148 | return Err(format!("{:?}", raw_job_type.err().unwrap())); 149 | } 150 | let job_type = raw_job_type.unwrap(); 151 | let hyphenated_uuid = job_type.uuid.hyphenated().to_string(); 152 | if hyphenated_uuid != *current_uuid { 153 | return Err(format!("redis consistency error: hash key '{}' not equal data given uuid '{}'", hyphenated_uuid, *current_uuid)); 154 | } 155 | output.push(job_type); 156 | } 157 | } 158 | return Ok(output); 159 | } 160 | 161 | fn get_job_type(&mut self, uuid: Uuid) -> Result, String> { 162 | let redis_result: Result, ::redis::RedisError> = self.connection.hget("job_types", uuid.hyphenated().to_string()); 163 | if redis_result.is_err() { 164 | return Err(format!("{:?}", redis_result.err().unwrap())); 165 | } 166 | if redis_result.as_ref().unwrap().is_none() { 167 | return Ok(None); 168 | } 169 | let raw_job_type: Result = serde_json::from_str(&*redis_result.unwrap().unwrap()); 170 | if raw_job_type.is_err() { 171 | return Err(format!("{:?}", raw_job_type.err().unwrap())); 172 | } 173 | return Ok(Some(raw_job_type.unwrap())); 174 | } 175 | 176 | fn new_job_type(&mut self, job_type: &JobType) -> Result<(), String> { 177 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hset("job_types", job_type.uuid.hyphenated().to_string(), serde_json::to_string(&job_type).unwrap()); 178 | if redis_result.is_err() { 179 | return Err(format!("{:?}", redis_result.err().unwrap())); 180 | } 181 | return Ok(()); 182 | } 183 | 184 | fn get_job_schedule(&mut self) -> Result, String> { 185 | let redis_result: Result, ::redis::RedisError> = self.connection.hgetall("schedule_items"); 186 | if redis_result.is_err() { 187 | return Err(format!("{:?}", redis_result.err().unwrap())); 188 | } 189 | let raw_redis = redis_result.unwrap(); 190 | let mut output: Vec = vec![]; 191 | let mut current_uuid: &String = &"".to_string(); 192 | for i in 0..raw_redis.len() { 193 | if i % 2 == 0 { 194 | current_uuid = &raw_redis[i]; 195 | } else { 196 | let raw_schedule_item: Result = serde_json::from_str(&*raw_redis[i]); 197 | if raw_schedule_item.is_err() { 198 | return Err(format!("{:?}", raw_schedule_item.err().unwrap())); 199 | } 200 | let schedule_item = raw_schedule_item.unwrap(); 201 | let hyphenated_uuid = schedule_item.uuid.hyphenated().to_string(); 202 | if hyphenated_uuid != *current_uuid { 203 | return Err(format!("redis consistency error: hash key '{}' not equal data given uuid '{}'", hyphenated_uuid, *current_uuid)); 204 | } 205 | output.push(schedule_item); 206 | } 207 | } 208 | return Ok(output); 209 | } 210 | 211 | fn get_job_schedule_item(&mut self, uuid: Uuid) -> Result, String> { 212 | let redis_result: Result, ::redis::RedisError> = self.connection.hget("schedule_items", uuid.hyphenated().to_string()); 213 | if redis_result.is_err() { 214 | return Err(format!("{:?}", redis_result.err().unwrap())); 215 | } 216 | if redis_result.as_ref().unwrap().is_none() { 217 | return Ok(None); 218 | } 219 | let raw_schedule_item: Result = serde_json::from_str(&*redis_result.unwrap().unwrap()); 220 | if raw_schedule_item.is_err() { 221 | return Err(format!("{:?}", raw_schedule_item.err().unwrap())); 222 | } 223 | return Ok(Some(raw_schedule_item.unwrap())); 224 | } 225 | 226 | fn delete_job_schedule_item(&mut self, uuid: Uuid) -> Result<(), String> { 227 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hdel("schedule_items", uuid.hyphenated().to_string()); 228 | if redis_result.is_err() { 229 | return Err(format!("{:?}", redis_result.err().unwrap())); 230 | } 231 | return Ok(()); 232 | } 233 | 234 | fn new_job_schedule_item(&mut self, schedule_item: &ScheduleItem) -> Result<(), String> { 235 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hset("schedule_items", schedule_item.uuid.hyphenated().to_string(), serde_json::to_string(&schedule_item).unwrap()); 236 | if redis_result.is_err() { 237 | return Err(format!("{:?}", redis_result.err().unwrap())); 238 | } 239 | return Ok(()); 240 | } 241 | 242 | fn claim_job_scheduled(&mut self, schedule_item: &ScheduleItem) -> Result, String> { 243 | let mut new_schedule_item = schedule_item.clone(); 244 | new_schedule_item.last_scheduled_by = Some(self.node.uuid); 245 | new_schedule_item.last_scheduled_at = Some(epoch()); 246 | let updated = redis_hcheck_set(&mut self.connection, "schedule_items".to_string(), schedule_item.uuid.hyphenated().to_string(), Some(serde_json::to_string(schedule_item).unwrap()), Some(serde_json::to_string(&new_schedule_item).unwrap()))?; 247 | if updated { 248 | return Ok(Some(new_schedule_item)); // we claimed it 249 | } else { 250 | return Ok(None); // someone else modified/claimed it 251 | } 252 | } 253 | 254 | fn enqueue_job(&mut self, mut job: Job) -> Result<(), String> { 255 | job.enqueued_at = Some(epoch()); 256 | let node_type_uuid = self.node.node_type_uuid.unwrap().hyphenated().to_string(); 257 | let redis_result: Result = self.connection.rpush(format!("jobs_waiting_{}", node_type_uuid), serde_json::to_string(&job).unwrap()); 258 | if redis_result.is_err() { 259 | return Err(format!("{:?}", redis_result.err().unwrap())); 260 | } 261 | return Ok(()); 262 | } 263 | 264 | fn dequeue_job(&mut self) -> Result { 265 | let node_type_uuid = self.node.node_type_uuid.unwrap().hyphenated().to_string(); 266 | let redis_result: Result, ::redis::RedisError> = self.connection.blpop(format!("jobs_waiting_{}", node_type_uuid), 0); 267 | if redis_result.is_err() { 268 | return Err(format!("{:?}", redis_result.err().unwrap())); 269 | } 270 | let raw_job: Result = serde_json::from_str(&*(redis_result.unwrap())[1]); 271 | if raw_job.is_err() { 272 | return Err(format!("{:?}", raw_job.err().unwrap())); 273 | } 274 | let mut job = raw_job.unwrap(); 275 | job.started_at = Some(epoch()); 276 | job.executing_node = Some(self.node.node_type_uuid.unwrap()); 277 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hset(format!("jobs_in_progress_{}", node_type_uuid), job.uuid.hyphenated().to_string(), serde_json::to_string(&job).unwrap()); 278 | if redis_result.is_err() { 279 | return Err(format!("{:?}", redis_result.err().unwrap())); 280 | } 281 | job.job_type = Some(self.get_cached_job_type(job.job_type_uuid)?); 282 | return Ok(job); 283 | } 284 | 285 | fn finish_job(&mut self, mut job: Job, results: Option, errors: Option) -> Result<(), String> { 286 | let node_type_uuid = self.node.node_type_uuid.unwrap().hyphenated().to_string(); 287 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hdel(format!("jobs_in_progress_{}", node_type_uuid), job.uuid.hyphenated().to_string()); 288 | if redis_result.is_err() { 289 | return Err(format!("{:?}", redis_result.err().unwrap())); 290 | } 291 | job.ended_at = Some(epoch()); 292 | job.results = results; 293 | job.errors = errors; 294 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hset(format!("jobs_finished_{}", node_type_uuid), job.uuid.hyphenated().to_string(), serde_json::to_string(&job).unwrap()); 295 | if redis_result.is_err() { 296 | return Err(format!("{:?}", redis_result.err().unwrap())); 297 | } 298 | return Ok(()); 299 | } 300 | 301 | fn get_all_jobs_waiting(&mut self) -> Result, String> { 302 | let node_type_uuid = self.node.node_type_uuid.unwrap().hyphenated().to_string(); 303 | let redis_result: Result, ::redis::RedisError> = self.connection.lrange(format!("jobs_waiting_{}", node_type_uuid), 0, -1); 304 | if redis_result.is_err() { 305 | return Err(format!("{:?}", redis_result.err().unwrap())); 306 | } 307 | let raw_jobs = redis_result.unwrap(); 308 | let mut jobs: Vec = vec![]; 309 | for job in raw_jobs { 310 | let raw_job: Result = serde_json::from_str(&*job); 311 | if raw_job.is_err() { 312 | return Err(format!("{:?}", raw_job.err().unwrap())); 313 | } 314 | let mut job = raw_job.unwrap(); 315 | job.job_type = Some(self.get_cached_job_type(job.job_type_uuid)?); 316 | jobs.push(job); 317 | } 318 | return Ok(jobs); 319 | } 320 | 321 | fn get_all_jobs_in_progress(&mut self) -> Result, String> { 322 | let node_type_uuid = self.node.node_type_uuid.unwrap().hyphenated().to_string(); 323 | return self.get_all_jobs_in(format!("jobs_in_progress_{}", node_type_uuid)); 324 | } 325 | 326 | fn get_all_jobs_finished(&mut self) -> Result, String> { 327 | let node_type_uuid = self.node.node_type_uuid.unwrap().hyphenated().to_string(); 328 | return self.get_all_jobs_in(format!("jobs_finished_{}", node_type_uuid)); 329 | } 330 | 331 | fn get_finished_job(&mut self, uuid: Uuid) -> Result, String> { 332 | let node_type_uuid = self.node.node_type_uuid.unwrap().hyphenated().to_string(); 333 | let redis_result: Result, ::redis::RedisError> = self.connection.hget(format!("jobs_finished_{}", node_type_uuid), uuid.hyphenated().to_string()); 334 | if redis_result.is_err() { 335 | return Err(format!("{:?}", redis_result.err().unwrap())); 336 | } 337 | let redis_result_maybe = redis_result.unwrap(); 338 | if redis_result_maybe.is_none() { 339 | return Ok(None); 340 | } 341 | let raw_job: Result = serde_json::from_str(&*redis_result_maybe.unwrap()); 342 | if raw_job.is_err() { 343 | return Err(format!("{:?}", raw_job.err().unwrap())); 344 | } 345 | let mut job = raw_job.unwrap(); 346 | job.job_type = Some(self.get_cached_job_type(job.job_type_uuid)?); 347 | return Ok(Some(job)); 348 | } 349 | 350 | fn ping(&mut self) -> Result<(), String> { 351 | self.node.last_ping = epoch(); 352 | let redis_result: Result<(), ::redis::RedisError> = self.connection.hset("nodes", self.node.uuid.hyphenated().to_string(), serde_json::to_string(&self.node).unwrap()); 353 | if redis_result.is_err() { 354 | return Err(format!("{:?}", redis_result.err().unwrap())); 355 | } 356 | return Ok(()); 357 | } 358 | 359 | fn get_ping_interval_ms(&self) -> u32 { 360 | return self.ping_interval; 361 | } 362 | 363 | fn get_node(&mut self) -> &mut Node { 364 | return &mut self.node; 365 | } 366 | 367 | fn get_nodes(&mut self) -> Result, String> { 368 | let redis_result: Result, ::redis::RedisError> = self.connection.hgetall("nodes"); 369 | if redis_result.is_err() { 370 | return Err(format!("{:?}", redis_result.err().unwrap())); 371 | } 372 | let request_finish_epoch = epoch(); 373 | let raw_redis = redis_result.unwrap(); 374 | let mut output: Vec = vec![]; 375 | let mut current_uuid: &String = &"".to_string(); 376 | for i in 0..raw_redis.len() { 377 | if i % 2 == 0 { 378 | current_uuid = &raw_redis[i]; 379 | } else { 380 | let raw_node: Result = serde_json::from_str(&*raw_redis[i]); 381 | if raw_node.is_err() { 382 | return Err(format!("{:?}", raw_node.err().unwrap())); 383 | } 384 | let node = raw_node.unwrap(); 385 | if node.uuid.hyphenated().to_string() != *current_uuid { 386 | return Err(format!("redis consistency error: hash key '{}' not equal data given uuid '{}'", node.uuid.hyphenated(), *current_uuid)); 387 | } 388 | // 20 seconds leeway (pings are every 5 seconds) 389 | if node.last_ping + 20000 < request_finish_epoch { 390 | continue; 391 | } 392 | output.push(node); 393 | } 394 | } 395 | return Ok(output); 396 | } 397 | 398 | fn get_other_node(&mut self, uuid: Uuid) -> Result, String> { 399 | let redis_result: Result, ::redis::RedisError> = self.connection.hget("nodes", uuid.hyphenated().to_string()); 400 | if redis_result.is_err() { 401 | return Err(format!("{:?}", redis_result.err().unwrap())); 402 | } 403 | let request_finish_epoch = epoch(); 404 | if redis_result.as_ref().unwrap().is_none() { 405 | return Ok(None); 406 | } 407 | let raw_node: Result = serde_json::from_str(&*redis_result.unwrap().unwrap()); 408 | if raw_node.is_err() { 409 | return Err(format!("{:?}", raw_node.err().unwrap())); 410 | } 411 | let node = raw_node.unwrap(); 412 | if node.last_ping + 20000 < request_finish_epoch { 413 | return Ok(None); 414 | } 415 | return Ok(Some(node)); 416 | } 417 | 418 | fn replicate(&self) -> Result { 419 | let new_client = self.client.clone(); 420 | let connection = new_client.get_connection(); 421 | if connection.is_err() { 422 | return Err(format!("{:?}", connection.err().unwrap())); 423 | } 424 | return Ok(Box::new(RedisStore { 425 | client: new_client, 426 | connection: connection.unwrap(), 427 | ping_interval: self.ping_interval, 428 | node: self.node.clone(), 429 | job_types: self.job_types.clone(), 430 | })); 431 | } 432 | 433 | fn clean(&mut self) { 434 | let _: Result<(), ::redis::RedisError> = ::redis::cmd("FLUSHDB").query(&mut self.connection); 435 | } 436 | } 437 | 438 | impl RedisStore { 439 | 440 | fn get_all_jobs_in(&mut self, key: String) -> Result, String> { 441 | let redis_result: Result, ::redis::RedisError> = self.connection.hgetall(key); 442 | if redis_result.is_err() { 443 | return Err(format!("{:?}", redis_result.err().unwrap())); 444 | } 445 | let raw_redis = redis_result.unwrap(); 446 | let mut output: Vec = vec![]; 447 | let mut current_uuid: &String = &"".to_string(); 448 | for i in 0..raw_redis.len() { 449 | if i % 2 == 0 { 450 | current_uuid = &raw_redis[i]; 451 | } else { 452 | let raw_job: Result = serde_json::from_str(&*raw_redis[i]); 453 | if raw_job.is_err() { 454 | return Err(format!("{:?}", raw_job.err().unwrap())); 455 | } 456 | let mut job = raw_job.unwrap(); 457 | if job.uuid.hyphenated().to_string() != *current_uuid { 458 | return Err(format!("redis consistency error: hash key '{}' not equal data given uuid '{}'", job.uuid.hyphenated(), *current_uuid)); 459 | } 460 | job.job_type = Some(self.get_cached_job_type(job.job_type_uuid)?); 461 | output.push(job); 462 | } 463 | } 464 | return Ok(output); 465 | } 466 | 467 | fn get_cached_job_type(&mut self, uuid: Uuid) -> Result { 468 | let cached = self.job_types.get(&uuid); 469 | if cached.is_some() { 470 | return Ok(cached.unwrap().clone()); 471 | } 472 | let retrieved = self.get_job_type(uuid)?; 473 | if retrieved.is_none() { 474 | return Err(format!("invalid job type: '{}'", uuid.hyphenated().to_string())); 475 | } 476 | self.job_types.insert(uuid, retrieved.as_ref().unwrap().clone()); 477 | return Ok(retrieved.unwrap()); 478 | } 479 | } 480 | 481 | #[cfg(test)] 482 | mod tests { 483 | use super::*; 484 | use crate::store::tests::*; 485 | 486 | #[test] 487 | fn can_connect() -> Result<(), String> { 488 | let _store = RedisStore::connect()?; 489 | // we successfully connected (this test is mostly to ensure redis is available in the testing environment) 490 | Ok(()) 491 | } 492 | 493 | #[test] 494 | fn can_get_node_types() -> Result<(), String> { 495 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 496 | store.clean(); 497 | let node_types = store.get_node_types()?; 498 | assert_eq!(node_types, vec![]); 499 | let test_node_type = make_node_type(&mut store)?; 500 | let node_types_new = store.get_node_types()?; 501 | assert_eq!(node_types_new, vec![test_node_type.clone()]); 502 | let node_types_singular_new = store.get_node_type(test_node_type.uuid)?; 503 | assert_eq!(node_types_singular_new, Some(test_node_type)); 504 | Ok(()) 505 | } 506 | 507 | #[test] 508 | fn can_set_node_type() -> Result<(), String> { 509 | let mut store = RedisStore::connect()?; 510 | let mut boxed_store: StoreRef = store.replicate()?; 511 | boxed_store.clean(); 512 | let test_node_type = make_node_type(&mut boxed_store)?; 513 | boxed_store.set_node_type(test_node_type.uuid)?; 514 | let redis_result: Result = store.connection.hget("nodes", boxed_store.get_node().uuid.hyphenated().to_string()); 515 | assert_eq!(redis_result.unwrap(), serde_json::to_string(boxed_store.get_node()).unwrap()); 516 | Ok(()) 517 | } 518 | 519 | #[test] 520 | fn can_get_job_types() -> Result<(), String> { 521 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 522 | store.clean(); 523 | let test_node_type = make_node_type(&mut store)?; 524 | store.set_node_type(test_node_type.uuid)?; 525 | let job_types = store.get_job_types()?; 526 | assert_eq!(job_types, vec![]); 527 | let test_job_type = make_job_type(&mut store)?; 528 | let job_types_new = store.get_job_types()?; 529 | assert_eq!(job_types_new, vec![test_job_type]); 530 | Ok(()) 531 | } 532 | 533 | #[test] 534 | fn can_get_job_schedule() -> Result<(), String> { 535 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 536 | store.clean(); 537 | let test_node_type = make_node_type(&mut store)?; 538 | store.set_node_type(test_node_type.uuid)?; 539 | let schedule = store.get_job_schedule()?; 540 | assert_eq!(schedule, vec![]); 541 | let test_job_type = make_job_type(&mut store)?; 542 | let test_schedule_item = make_schedule_item(&mut store, test_job_type.uuid, None, None)?; 543 | let schedule_new = store.get_job_schedule()?; 544 | assert_eq!(schedule_new, vec![test_schedule_item]); 545 | Ok(()) 546 | } 547 | 548 | #[test] 549 | fn can_get_and_delete_job_schedule_item() -> Result<(), String> { 550 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 551 | store.clean(); 552 | let test_node_type = make_node_type(&mut store)?; 553 | store.set_node_type(test_node_type.uuid)?; 554 | let test_job_type = make_job_type(&mut store)?; 555 | let test_schedule_item = make_schedule_item(&mut store, test_job_type.uuid, None, None)?; 556 | let schedule_new = store.get_job_schedule_item(test_schedule_item.uuid)?; 557 | assert_eq!(schedule_new, Some(test_schedule_item.clone())); 558 | store.delete_job_schedule_item(test_schedule_item.uuid)?; 559 | let schedule = store.get_job_schedule()?; 560 | assert_eq!(schedule, vec![]); 561 | Ok(()) 562 | } 563 | 564 | #[test] 565 | fn can_claim_job_schedule() -> Result<(), String> { 566 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 567 | store.clean(); 568 | let test_node_type = make_node_type(&mut store)?; 569 | store.set_node_type(test_node_type.uuid)?; 570 | let test_job_type = make_job_type(&mut store)?; 571 | let mut test_schedule_item = make_schedule_item(&mut store, test_job_type.uuid, None, None)?; 572 | let claimed = store.claim_job_scheduled(&test_schedule_item)?; 573 | assert_ne!(claimed, Some(test_schedule_item.clone())); 574 | assert_ne!(claimed, None); 575 | test_schedule_item.last_scheduled_at = claimed.as_ref().unwrap().last_scheduled_at; 576 | test_schedule_item.last_scheduled_by = claimed.as_ref().unwrap().last_scheduled_by; 577 | assert_eq!(claimed, Some(test_schedule_item)); 578 | Ok(()) 579 | } 580 | 581 | #[test] 582 | fn can_enqueue_dequeue_jobs() -> Result<(), String> { 583 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 584 | store.clean(); 585 | let test_node_type = make_node_type(&mut store)?; 586 | store.set_node_type(test_node_type.uuid)?; 587 | let test_job_type = make_job_type(&mut store)?; 588 | let mut test_job = make_job(&mut store, &test_job_type)?; 589 | assert_eq!(test_job.enqueued_at, None); 590 | assert_eq!(test_job.started_at, None); 591 | assert_eq!(test_job.executing_node, None); 592 | let enqueued_jobs = store.get_all_jobs_waiting()?; 593 | assert_eq!(enqueued_jobs.len(), 1); 594 | let dequeued_job = store.dequeue_job()?; 595 | test_job.enqueued_at = dequeued_job.enqueued_at; 596 | assert_eq!(enqueued_jobs[0], test_job); 597 | test_job.started_at = dequeued_job.started_at; 598 | test_job.executing_node = dequeued_job.executing_node; 599 | let all_jobs_waiting = store.get_all_jobs_in_progress()?; 600 | assert_eq!(all_jobs_waiting, vec![test_job.clone()]); 601 | assert_eq!(dequeued_job, test_job); 602 | Ok(()) 603 | } 604 | 605 | #[test] 606 | fn can_enqueue_dequeue_finish_jobs() -> Result<(), String> { 607 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 608 | store.clean(); 609 | let test_node_type = make_node_type(&mut store)?; 610 | store.set_node_type(test_node_type.uuid)?; 611 | let test_job_type = make_job_type(&mut store)?; 612 | make_job(&mut store, &test_job_type)?; 613 | let dequeued_job = store.dequeue_job()?; 614 | store.finish_job(dequeued_job.clone(), Some(Value::Bool(true)), Some(Value::Bool(false)))?; 615 | let all_jobs_finished = store.get_all_jobs_finished()?; 616 | let mut theoretical_finished_job = dequeued_job.clone(); 617 | assert_eq!(all_jobs_finished.len(), 1); 618 | theoretical_finished_job.ended_at = all_jobs_finished[0].ended_at; 619 | theoretical_finished_job.results = Some(Value::Bool(true)); 620 | theoretical_finished_job.errors = Some(Value::Bool(false)); 621 | assert_eq!(all_jobs_finished, vec![theoretical_finished_job.clone()]); 622 | assert_eq!(store.get_finished_job(theoretical_finished_job.uuid), Ok(Some(theoretical_finished_job))); 623 | Ok(()) 624 | } 625 | 626 | #[test] 627 | fn can_ping() -> Result<(), String> { 628 | let mut store = RedisStore::connect()?; 629 | let mut boxed_store: StoreRef = store.replicate()?; 630 | boxed_store.clean(); 631 | let test_node_type = make_node_type(&mut boxed_store)?; 632 | boxed_store.set_node_type(test_node_type.uuid)?; 633 | boxed_store.ping()?; 634 | let redis_result: Result = store.connection.hget("nodes".to_string(), boxed_store.get_node().uuid.hyphenated().to_string()); 635 | if redis_result.is_err() { 636 | return Err(format!("{:?}", redis_result.err().unwrap())); 637 | } 638 | let raw_node: Result = serde_json::from_str(&*redis_result.unwrap()); 639 | if raw_node.is_err() { 640 | return Err(format!("{:?}", raw_node.err().unwrap())); 641 | } 642 | let mut node = raw_node.unwrap(); 643 | node.node_type = boxed_store.get_node().node_type.clone(); 644 | assert_eq!(node, *boxed_store.get_node()); 645 | Ok(()) 646 | } 647 | 648 | 649 | #[test] 650 | fn can_get_all_nodes() -> Result<(), String> { 651 | let mut store: StoreRef = Box::new(RedisStore::connect()?); 652 | store.clean(); 653 | let test_node_type = make_node_type(&mut store)?; 654 | store.set_node_type(test_node_type.uuid)?; 655 | let nodes = store.get_nodes()?; 656 | assert_eq!(nodes.len(), 1); 657 | let mut store_node = store.get_node().clone(); 658 | assert!(nodes.iter().any(|node| node.uuid == store_node.uuid)); 659 | let test_other_node = store.get_other_node(store_node.uuid)?; 660 | store_node.node_type = None; 661 | assert_eq!(test_other_node.unwrap(), store_node); 662 | Ok(()) 663 | } 664 | 665 | } -------------------------------------------------------------------------------- /src/threads/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod ping_thread; 2 | pub mod scheduler_thread; 3 | pub mod worker_thread; -------------------------------------------------------------------------------- /src/threads/ping_thread.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::thread; 3 | use crate::StoreRef; 4 | use log::*; 5 | 6 | pub fn start_thread(mut store: StoreRef) { 7 | thread::spawn(move || { 8 | let interval = store.get_ping_interval_ms(); 9 | loop { 10 | let ping_result = store.ping(); 11 | if ping_result.is_err() { 12 | error!("Error pinging redis server: {}", ping_result.err().unwrap()); 13 | } 14 | thread::sleep_ms(interval); 15 | } 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /src/threads/scheduler_thread.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::thread; 3 | use crate::StoreRef; 4 | use log::*; 5 | use crate::util::time::epoch; 6 | use crate::exec::job::Job; 7 | use uuid::Uuid; 8 | 9 | fn run_loop(store: &mut StoreRef) { 10 | let job_schedule = store.get_job_schedule(); 11 | if job_schedule.is_err() { 12 | error!("Error getting job schedule from redis server: {}", job_schedule.err().unwrap()); 13 | return; 14 | } 15 | let eval_time = epoch(); 16 | for schedule_item in job_schedule.unwrap() { 17 | let current_chunk = eval_time / schedule_item.interval; 18 | if schedule_item.last_scheduled_at.is_none() || current_chunk > (schedule_item.last_scheduled_at.unwrap() / schedule_item.interval) { 19 | let claim_result = store.claim_job_scheduled(&schedule_item); 20 | match claim_result { 21 | Err(e) => { error!("Error claiming job schedule from redis server: {}", e); }, 22 | Ok(None) => {}, 23 | Ok(Some(_)) => { 24 | let job_type = store.get_job_type(schedule_item.job_type_uuid); 25 | if job_type.is_err() || job_type.as_ref().unwrap().is_none() { 26 | error!("Error getting job type from redis server: {}", job_type.err().unwrap()); 27 | return; 28 | } 29 | let enqueue_result = store.enqueue_job(Job { 30 | uuid: Uuid::new_v4(), 31 | job_type_uuid: schedule_item.job_type_uuid, 32 | job_type: Some(job_type.unwrap().unwrap()), 33 | arguments: schedule_item.job_arguments, 34 | executing_node: None, 35 | enqueued_at: None, 36 | started_at: None, 37 | ended_at: None, 38 | results: None, 39 | errors: None, 40 | }); 41 | if enqueue_result.is_err() { 42 | error!("Error enqueuing job from redis server: {}", enqueue_result.err().unwrap()); 43 | return; 44 | } 45 | }, 46 | }; 47 | } 48 | } 49 | } 50 | 51 | pub fn start_thread(mut store: StoreRef) { 52 | thread::spawn(move || { 53 | let interval = store.get_ping_interval_ms(); 54 | loop { 55 | thread::sleep_ms(interval); 56 | 57 | run_loop(&mut store); 58 | } 59 | }); 60 | } 61 | 62 | 63 | #[cfg(test)] 64 | mod tests { 65 | use super::*; 66 | use crate::store::tests::*; 67 | use crate::store::init_store_untyped; 68 | 69 | #[test] 70 | fn can_schedule_first_time() -> Result<(), String> { 71 | let mut store = init_store_untyped(); 72 | store.clean(); 73 | let test_node_type = make_node_type(&mut store)?; 74 | store.set_node_type(test_node_type.uuid)?; 75 | let test_job_type = make_job_type(&mut store)?; 76 | make_schedule_item(&mut store, test_job_type.uuid, None, None)?; 77 | run_loop(&mut store); 78 | let queued_jobs = store.get_all_jobs_waiting()?; 79 | assert_eq!(queued_jobs.len(), 1); 80 | assert_eq!(queued_jobs[0].job_type_uuid, test_job_type.uuid); 81 | Ok(()) 82 | } 83 | 84 | #[test] 85 | fn can_schedule_when_expired() -> Result<(), String> { 86 | let mut store = init_store_untyped(); 87 | store.clean(); 88 | let test_node_type = make_node_type(&mut store)?; 89 | store.set_node_type(test_node_type.uuid)?; 90 | let test_job_type = make_job_type(&mut store)?; 91 | let node_uuid = store.get_node().uuid; 92 | make_schedule_item(&mut store, test_job_type.uuid, Some(node_uuid), Some(0))?; 93 | run_loop(&mut store); 94 | let queued_jobs = store.get_all_jobs_waiting()?; 95 | assert_eq!(queued_jobs.len(), 1); 96 | assert_eq!(queued_jobs[0].job_type_uuid, test_job_type.uuid); 97 | Ok(()) 98 | } 99 | 100 | #[test] 101 | fn will_not_schedule_when_not_expired() -> Result<(), String> { 102 | let mut store = init_store_untyped(); 103 | store.clean(); 104 | let test_node_type = make_node_type(&mut store)?; 105 | store.set_node_type(test_node_type.uuid)?; 106 | let test_job_type = make_job_type(&mut store)?; 107 | let node_uuid = store.get_node().uuid; 108 | // assumption: the following 3 lines execute in < 500 ms (the default interval for make_schedule_item) 109 | make_schedule_item(&mut store, test_job_type.uuid, Some(node_uuid), Some(epoch() + 100))?; 110 | run_loop(&mut store); 111 | let mut queued_jobs = store.get_all_jobs_waiting()?; 112 | assert_eq!(queued_jobs.len(), 0); 113 | 114 | thread::sleep_ms(1000); 115 | run_loop(&mut store); 116 | queued_jobs = store.get_all_jobs_waiting()?; 117 | assert_eq!(queued_jobs.len(), 1); 118 | assert_eq!(queued_jobs[0].job_type_uuid, test_job_type.uuid); 119 | Ok(()) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/threads/worker_thread.rs: -------------------------------------------------------------------------------- 1 | 2 | use std::thread; 3 | use crate::StoreRef; 4 | use log::*; 5 | use crate::exec::executors::*; 6 | use crate::exec::executor::*; 7 | use serde_json::Value; 8 | 9 | fn run_loop(store: &mut StoreRef) { 10 | let dequeued_item = store.dequeue_job(); 11 | if dequeued_item.is_err() { 12 | error!("Error getting job schedule from redis server: {}", dequeued_item.err().unwrap()); 13 | return; 14 | } 15 | let job = dequeued_item.unwrap(); 16 | let job_type = job.job_type.as_ref().unwrap(); 17 | info!("Starting job '{}' of type '{}' / '{}'", job.uuid.hyphenated(), job_type.name, job.job_type_uuid.hyphenated()); 18 | run_job(store, job); 19 | } 20 | 21 | pub fn start_thread(mut store: StoreRef) { 22 | thread::spawn(move || { 23 | loop { 24 | run_loop(&mut store); 25 | } 26 | }); 27 | } 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use super::*; 32 | use crate::store::tests::*; 33 | use crate::store::init_store_untyped; 34 | use serde_json::{ Map, Number }; 35 | 36 | #[test] 37 | fn can_execute_job() -> Result<(), String> { 38 | let mut store = init_store_untyped(); 39 | store.clean(); 40 | let test_node_type = make_node_type(&mut store)?; 41 | store.set_node_type(test_node_type.uuid)?; 42 | let test_job_type = make_job_type(&mut store)?; 43 | let mut test_job = make_job(&mut store, &test_job_type)?; 44 | run_loop(&mut store); 45 | let finished_jobs = store.get_all_jobs_finished()?; 46 | assert_eq!(finished_jobs.len(), 1); 47 | test_job.enqueued_at = finished_jobs[0].enqueued_at; 48 | test_job.started_at = finished_jobs[0].started_at; 49 | test_job.executing_node = finished_jobs[0].executing_node; 50 | test_job.ended_at = finished_jobs[0].ended_at; 51 | let mut output = Map::new(); 52 | output.insert("stdout".to_string(), Value::String("test\n".to_string())); 53 | output.insert("stderr".to_string(), Value::String("".to_string())); 54 | output.insert("exit_code".to_string(), Value::Number(Number::from(0))); 55 | test_job.results = Some(Value::Object(output)); 56 | assert_eq!(finished_jobs[0], test_job); 57 | Ok(()) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/util/config.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | 3 | fn default_env(name: &str, default: &str) -> String { 4 | env::var(name).unwrap_or(default.to_string()) 5 | } 6 | 7 | lazy_static! { 8 | pub static ref NODE_TYPE: String = { default_env("NODE_TYPE", "default") }; 9 | pub static ref STORE_TYPE: String = { default_env("STORE_TYPE", "redis") }; 10 | pub static ref REDIS_HOST: String = { default_env("REDIS_HOST", "127.0.0.1") }; 11 | pub static ref REDIS_PORT: String = { default_env("REDIS_PORT", "6379") }; 12 | pub static ref REDIS_DATABASE: String = { default_env("REDIS_DATABASE", "") }; 13 | pub static ref HTTP_SERVER_ENABLED: String = { default_env("HTTP_SERVER_ENABLED", "true") }; 14 | pub static ref HTTP_BIND_ADDRESS: String = { default_env("HTTP_BIND_ADDRESS", "127.0.0.1:23071") }; 15 | pub static ref HTTP_API_KEY: String = { default_env("HTTP_API_KEY", "dev_key") }; 16 | } 17 | -------------------------------------------------------------------------------- /src/util/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod config; 2 | pub mod time; -------------------------------------------------------------------------------- /src/util/time.rs: -------------------------------------------------------------------------------- 1 | use std::time::{SystemTime, UNIX_EPOCH}; 2 | 3 | pub fn epoch() -> u64 { 4 | let start = SystemTime::now(); 5 | let duration = start.duration_since(UNIX_EPOCH).unwrap(); 6 | return duration.as_millis() as u64; 7 | } 8 | 9 | 10 | pub fn epoch_us() -> u64 { 11 | let start = SystemTime::now(); 12 | let duration = start.duration_since(UNIX_EPOCH).unwrap(); 13 | return duration.as_micros() as u64; 14 | } --------------------------------------------------------------------------------