├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.rst ├── deploy ├── cloudformation.yaml └── deployment.yaml ├── kube_aws_autoscaler ├── __init__.py ├── __main__.py └── main.py ├── requirements.txt ├── setup.py ├── tests └── test_autoscaler.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | *.swp 3 | *.pyc 4 | .idea/ 5 | .tox/ 6 | *.egg* 7 | dist/ 8 | scm-source.json 9 | .cache/ 10 | .coverage 11 | *.bak 12 | htmlcov/ 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | install: 5 | - pip install tox tox-travis coveralls 6 | script: 7 | - tox 8 | after_success: 9 | - coveralls 10 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.7 2 | MAINTAINER Henning Jacobs 3 | 4 | RUN apk add --no-cache python3 ca-certificates && \ 5 | pip3 install --upgrade pip setuptools boto3 pykube Flask && \ 6 | rm -rf /var/cache/apk/* /root/.cache /tmp/* 7 | 8 | WORKDIR / 9 | 10 | COPY kube_aws_autoscaler /kube_aws_autoscaler 11 | 12 | ARG VERSION=dev 13 | RUN sed -i "s/__version__ = .*/__version__ = '${VERSION}'/" /kube_aws_autoscaler/__init__.py 14 | 15 | ENTRYPOINT ["python3", "-m", "kube_aws_autoscaler"] 16 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: test docker push 2 | 3 | IMAGE ?= hjacobs/kube-aws-autoscaler 4 | VERSION ?= $(shell git describe --tags --always --dirty) 5 | TAG ?= $(VERSION) 6 | 7 | default: docker 8 | 9 | test: 10 | tox 11 | 12 | docker: 13 | docker build --build-arg "VERSION=$(VERSION)" -t "$(IMAGE):$(TAG)" . 14 | @echo 'Docker image $(IMAGE):$(TAG) can now be used.' 15 | 16 | push: docker 17 | docker push "$(IMAGE):$(TAG)" 18 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ================================= 2 | Kubernetes AWS Cluster Autoscaler 3 | ================================= 4 | 5 | .. image:: https://travis-ci.org/hjacobs/kube-aws-autoscaler.svg?branch=master 6 | :target: https://travis-ci.org/hjacobs/kube-aws-autoscaler 7 | :alt: Travis CI Build Status 8 | 9 | .. image:: https://coveralls.io/repos/github/hjacobs/kube-aws-autoscaler/badge.svg?branch=master;_=1 10 | :target: https://coveralls.io/github/hjacobs/kube-aws-autoscaler?branch=master 11 | :alt: Code Coverage 12 | 13 | **THIS PROJECT IS NO LONGER MAINTAINED**, PLEASE USE THE `OFFICIAL CLUSTER AUTOSCALER `_ INSTEAD 14 | 15 | Simple cluster autoscaler for AWS Auto Scaling Groups which sets the ``DesiredCapacity`` of one or more ASGs to the calculated number of nodes. 16 | 17 | Goals: 18 | 19 | * support multiple Auto Scaling Groups 20 | * support resource buffer (overprovision fixed or percentage amount) 21 | * respect Availability Zones, i.e. make sure that all AZs provide enough capacity 22 | * be deterministic and predictable, i.e. the ``DesiredCapacity`` is only calculated based on the current cluster state 23 | * scale down slowly to mitigate service disruptions, i.e. at most one node at a time 24 | * support "elastic" workloads like daily up/down scaling 25 | * support AWS Spot Fleet (not yet implemented) 26 | * require a minimum amount of configuration (preferably none) 27 | * keep it simple 28 | 29 | This autoscaler was initially created as a proof of concept and born out of frustration with the `"official" cluster-autoscaler`_: 30 | 31 | * it only scales up when "it's too late" (pods are unschedulable) 32 | * it does not honor Availability Zones 33 | * it does not support multiple Auto Scaling Groups 34 | * it requires unnecessary configuration 35 | * the code is quite complex 36 | 37 | Disclaimer 38 | ========== 39 | 40 | **Use at your own risk!** 41 | This autoscaler was only tested with Kubernetes versions 1.5.2 to 1.7.7. 42 | There is no guarantee that it works in previous Kubernetes versions. 43 | 44 | **Is it production ready?** 45 | Yes, the ``kube-aws-autoscaler`` is running in production at Zalando for months, see https://github.com/zalando-incubator/kubernetes-on-aws for more information and deployment configuration. 46 | 47 | How it works 48 | ============ 49 | 50 | The autoscaler consists of a simple main loop which calls the ``autoscale`` function every 60 seconds (configurable via the ``--interval`` option). 51 | The main loop keeps no state (like history), all input for the ``autoscale`` function comes from either static configuration or the Kubernetes API server. 52 | The ``autoscale`` function performs the following task: 53 | 54 | * retrieve the list of all (worker) nodes from the Kubernetes API and group them by Auto Scaling Group (ASG) and Availability Zone (AZ) 55 | * retrieve the list of all pods from the Kubernetes API 56 | * calculate the current resource "usage" for every ASG and AZ by summing up all pod resource requests (CPU, memory and number of pods) 57 | * calculates the currently required number of nodes per AWS Auto Scaling Group: 58 | 59 | * iterate through every ASG/AZ combination 60 | * use the calculated resource usage (sum of resource requests) and add the resource requests of any unassigned pods (pods not scheduled on any node yet) 61 | * apply the configured buffer values (10% extra for CPU and memory by default) 62 | * find the `allocatable capacity`_ of the weakest node 63 | * calculate the number of required nodes by adding up the capacity of the weakest node until the sum is greater than or equal to requested+buffer for both CPU and memory 64 | * sum up the number of required nodes from all AZ for the ASG 65 | 66 | * adjust the number of required nodes if it would scale down more than one node at a time 67 | * set the ``DesiredCapacity`` for each ASG to the calculated number of required nodes 68 | 69 | The whole process relies on having properly configured resource requests for all pods. 70 | 71 | 72 | Usage 73 | ===== 74 | 75 | Create the necessary IAM role (to be used by ``kube2iam`` if you have it deployed): 76 | 77 | * Modify ``deploy/cloudformation.yaml`` and change the AWS account ID and the worker node's role name as necessary. 78 | * Create the Cloud Formation stack from ``deploy/cloudformation.yaml``. 79 | 80 | Deploy the autoscaler to your running cluster: 81 | 82 | .. code-block:: bash 83 | 84 | $ kubectl apply -f deploy/deployment.yaml 85 | 86 | See below for optional configuration parameters. 87 | 88 | 89 | Configuration 90 | ============= 91 | 92 | The following command line options are supported: 93 | 94 | ``--buffer-cpu-percentage`` 95 | Extra CPU requests % to add to calculation, defaults to 10%. 96 | ``--buffer-memory-percentage`` 97 | Extra memory requests % to add to calculation, defaults to 10%. 98 | ``--buffer-pods-percentage`` 99 | Extra pods requests % to add to calculation, defaults to 10%. 100 | ``--buffer-cpu-fixed`` 101 | Extra CPU requests to add to calculation, defaults to 200m. 102 | ``--buffer-memory-fixed`` 103 | Extra memory requests to add to calculation, defaults to 200Mi. 104 | ``--buffer-pods-fixed`` 105 | Extra number of pods to overprovision for, defaults to 10. 106 | ``--buffer-spare-nodes`` 107 | Number of extra "spare" nodes to provision per ASG/AZ, defaults to 1. 108 | ``--include-master-nodes`` 109 | Do not ignore auto scaling group with master nodes. 110 | ``--interval`` 111 | Time to sleep between runs in seconds, defaults to 60 seconds. 112 | ``--once`` 113 | Only run once and exit (useful for debugging). 114 | ``--scale-down-step-fixed`` 115 | Scale down step in terms of node count, defaults to 1. 116 | ``--scale-down-step-percentage`` 117 | Scale down step in terms of node percentage (1.0 is 100%), defaults to 0% 118 | 119 | 120 | .. _"official" cluster-autoscaler: https://github.com/kubernetes/autoscaler 121 | .. _allocatable capacity: https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node/node-allocatable.md 122 | -------------------------------------------------------------------------------- /deploy/cloudformation.yaml: -------------------------------------------------------------------------------- 1 | Description: Autoscaler IAM role 2 | Resources: 3 | AutoscalerIAMRole: 4 | Properties: 5 | RoleName: "kube-1-app-autoscaler" 6 | AssumeRolePolicyDocument: 7 | Statement: 8 | - Action: ['sts:AssumeRole'] 9 | Effect: Allow 10 | Principal: 11 | Service: [ec2.amazonaws.com] 12 | - Action: ['sts:AssumeRole'] 13 | Effect: Allow 14 | Principal: 15 | AWS: 16 | Fn::Join: 17 | - "" 18 | - 19 | - arn:aws:iam::123456789012:role/ 20 | - 21 | Ref: WorkerIAMRole 22 | Version: '2012-10-17' 23 | Path: / 24 | Policies: 25 | - PolicyDocument: 26 | Statement: 27 | - {Action: 'ec2:Describe*', Effect: Allow, Resource: '*'} 28 | - {Action: 'autoscaling:DescribeAutoScalingGroups', Effect: Allow, Resource: '*'} 29 | - {Action: 'autoscaling:DescribeAutoScalingInstances', Effect: Allow, Resource: '*'} 30 | - {Action: 'autoscaling:DescribeScalingActivities', Effect: Allow, Resource: '*'} 31 | - {Action: 'autoscaling:SetDesiredCapacity', Effect: Allow, Resource: '*'} 32 | - {Action: 'autoscaling:TerminateInstanceInAutoScalingGroup', Effect: Allow, Resource: '*'} 33 | Version: '2012-10-17' 34 | PolicyName: root 35 | Type: AWS::IAM::Role 36 | -------------------------------------------------------------------------------- /deploy/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | application: kube-aws-autoscaler 6 | version: v0.10 7 | name: kube-aws-autoscaler 8 | spec: 9 | replicas: 1 10 | selector: 11 | matchLabels: 12 | application: kube-aws-autoscaler 13 | template: 14 | metadata: 15 | labels: 16 | application: kube-aws-autoscaler 17 | version: v0.10 18 | annotations: 19 | # FIXME: using hardcoded IAM role 20 | iam.amazonaws.com/role: kube-1-app-autoscaler 21 | spec: 22 | containers: 23 | - name: autoscaler 24 | image: hjacobs/kube-aws-autoscaler:0.10 25 | resources: 26 | limits: 27 | cpu: 200m 28 | memory: 100Mi 29 | requests: 30 | cpu: 50m 31 | memory: 50Mi 32 | -------------------------------------------------------------------------------- /kube_aws_autoscaler/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.1' 2 | -------------------------------------------------------------------------------- /kube_aws_autoscaler/__main__.py: -------------------------------------------------------------------------------- 1 | from .main import main # pragma: no cover 2 | 3 | main() # pragma: no cover 4 | -------------------------------------------------------------------------------- /kube_aws_autoscaler/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import collections 5 | import itertools 6 | import logging 7 | import math 8 | import os 9 | import re 10 | import time 11 | 12 | import boto3 13 | import pykube 14 | 15 | from flask import Flask, jsonify 16 | from threading import Thread 17 | 18 | app = Flask(__name__) 19 | Healthy = True 20 | 21 | FACTORS = { 22 | 'm': 1 / 1000, 23 | 'K': 1000, 24 | 'M': 1000**2, 25 | 'G': 1000**3, 26 | 'T': 1000**4, 27 | 'P': 1000**5, 28 | 'E': 1000**6, 29 | 'Ki': 1024, 30 | 'Mi': 1024**2, 31 | 'Gi': 1024**3, 32 | 'Ti': 1024**4, 33 | 'Pi': 1024**5, 34 | 'Ei': 1024**6 35 | } 36 | 37 | RESOURCE_PATTERN = re.compile('^(\d*)(\D*)$') 38 | 39 | RESOURCES = ['cpu', 'memory', 'pods'] 40 | DEFAULT_CONTAINER_REQUESTS = {'cpu': '10m', 'memory': '50Mi'} 41 | DEFAULT_BUFFER_PERCENTAGE = {'cpu': 10, 'memory': 10, 'pods': 10} 42 | DEFAULT_BUFFER_FIXED = {'cpu': '200m', 'memory': '200Mi', 'pods': '10'} 43 | 44 | # DescribeAutoScalingInstances operation: The number of instance ids that may be passed in is limited to 50 45 | DESCRIBE_AUTO_SCALING_INSTANCES_LIMIT = 50 46 | 47 | logger = logging.getLogger('autoscaler') 48 | 49 | 50 | STATS = {} 51 | 52 | 53 | def parse_resource(v: str): 54 | '''Parse Kubernetes resource string''' 55 | match = RESOURCE_PATTERN.match(v) 56 | factor = FACTORS.get(match.group(2), 1) 57 | return int(match.group(1)) * factor 58 | 59 | 60 | def get_node_allocatable_tuple(node: dict): 61 | allocatable = node['allocatable'] 62 | return tuple(allocatable[resource] for resource in RESOURCES) 63 | 64 | 65 | def apply_buffer(requested: dict, buffer_percentage: dict, buffer_fixed: dict): 66 | requested_with_buffer = {} 67 | for resource, val in requested.items(): 68 | requested_with_buffer[resource] = val * (1. + buffer_percentage.get(resource, 0)/100) + buffer_fixed.get(resource, 0) 69 | return requested_with_buffer 70 | 71 | 72 | def find_weakest_node(nodes): 73 | return sorted(nodes, key=get_node_allocatable_tuple)[0] 74 | 75 | 76 | def is_sufficient(requested: dict, allocatable: dict): 77 | for resource, cap in allocatable.items(): 78 | if requested.get(resource, 0) > cap: 79 | return False 80 | return True 81 | 82 | 83 | def is_node_ready(node): 84 | ''' 85 | Return whether the given pykube Node has "Ready" status 86 | ''' 87 | for condition in node.obj['status'].get('conditions', []): 88 | if condition['type'] == 'Ready' and condition['status'] == 'True': 89 | return True 90 | return False 91 | 92 | 93 | def get_nodes(api, include_master_nodes: bool=False) -> dict: 94 | nodes = {} 95 | for node in pykube.Node.objects(api): 96 | region = node.labels['failure-domain.beta.kubernetes.io/region'] 97 | zone = node.labels['failure-domain.beta.kubernetes.io/zone'] 98 | instance_type = node.labels['beta.kubernetes.io/instance-type'] 99 | allocatable = {} 100 | # Use the Node Allocatable Resources to account for any kube/system reservations: 101 | # https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node-allocatable.md 102 | for key, val in node.obj['status']['allocatable'].items(): 103 | allocatable[key] = parse_resource(val) 104 | 105 | instance_id = "" 106 | 107 | if int(node.obj['status']['nodeInfo']['kubeletVersion'].split(".")[1]) < 11: 108 | instance_id = node.obj['spec']['externalID'] 109 | else: 110 | instance_id = node.obj['spec']['providerID'].split("/")[4] 111 | 112 | obj = {'name': node.name, 113 | 'region': region, 'zone': zone, 'instance_id': instance_id, 'instance_type': instance_type, 114 | 'allocatable': allocatable, 115 | 'ready': is_node_ready(node), 116 | 'unschedulable': node.obj['spec'].get('unschedulable', False), 117 | 'master': node.labels.get('master', 'false') == 'true'} 118 | if include_master_nodes or not obj['master']: 119 | nodes[node.name] = obj 120 | return nodes 121 | 122 | 123 | def chunks(l: list, n: int): 124 | '''Yield successive n-sized chunks from l.''' 125 | for i in range(0, len(l), n): 126 | yield l[i:i + n] 127 | 128 | 129 | def get_nodes_by_asg_zone(autoscaling, nodes: dict) -> dict: 130 | # first map instance_id to node object for later look up 131 | instances = {} 132 | for node in nodes.values(): 133 | instances[node['instance_id']] = node 134 | 135 | nodes_by_asg_zone = collections.defaultdict(list) 136 | 137 | for instance_ids in chunks(list(sorted(instances.keys())), DESCRIBE_AUTO_SCALING_INSTANCES_LIMIT): 138 | response = autoscaling.describe_auto_scaling_instances(InstanceIds=list(instance_ids)) 139 | for instance in response['AutoScalingInstances']: 140 | instances[instance['InstanceId']]['asg_name'] = instance['AutoScalingGroupName'] 141 | instances[instance['InstanceId']]['asg_lifecycle_state'] = instance['LifecycleState'] 142 | key = instance['AutoScalingGroupName'], instance['AvailabilityZone'] 143 | nodes_by_asg_zone[key].append(instances[instance['InstanceId']]) 144 | return nodes_by_asg_zone 145 | 146 | 147 | def calculate_usage_by_asg_zone(pods: list, nodes: dict) -> dict: 148 | usage_by_asg_zone = {} 149 | 150 | for pod in pods: 151 | phase = pod.obj['status'].get('phase') 152 | if phase == 'Succeeded': 153 | # ignore completed jobs 154 | continue 155 | elif phase == 'Failed' and pod.obj['spec'].get('restartPolicy') == 'Never': 156 | # ignore pods that won't be restarted 157 | continue 158 | 159 | node_name = pod.obj['spec'].get('nodeName') 160 | node = nodes.get(node_name) 161 | if node: 162 | asg_name = node['asg_name'] 163 | zone = node['zone'] 164 | else: 165 | if node_name and phase in ('Running', 'Unknown'): 166 | # ignore killed "ghost" pods 167 | # (pod is still returned by API, but node was terminated) 168 | continue 169 | # pod is unassigned/pending 170 | asg_name = 'unknown' 171 | # TODO: we actually might know the AZ by looking at volumes.. 172 | zone = 'unknown' 173 | requests = collections.defaultdict(int) 174 | requests['pods'] = 1 175 | for container in pod.obj['spec']['containers']: 176 | container_requests = container['resources'].get('requests', {}) 177 | for resource in RESOURCES: 178 | if resource != 'pods': 179 | value = container_requests.get(resource) 180 | if not value: 181 | logger.debug('Container {}/{} has no resource request for {}'.format( 182 | pod.name, container['name'], resource)) 183 | value = DEFAULT_CONTAINER_REQUESTS[resource] 184 | requests[resource] += parse_resource(value) 185 | key = asg_name, zone 186 | if key not in usage_by_asg_zone: 187 | usage_by_asg_zone[key] = {resource: 0 for resource in RESOURCES} 188 | for resource in usage_by_asg_zone[key]: 189 | usage_by_asg_zone[key][resource] += requests.get(resource, 0) 190 | return usage_by_asg_zone 191 | 192 | 193 | def format_resource(value: float, resource: str): 194 | if resource == 'cpu': 195 | return '{:.1f}'.format(value) 196 | elif resource == 'memory': 197 | return '{:.0f}Mi'.format(value / (1024*1024)) 198 | elif resource == 'pods': 199 | return '{:.0f}'.format(value) 200 | return '{:.0f}'.format(value) 201 | 202 | 203 | def slow_down_downscale(asg_sizes: dict, nodes_by_asg_zone: dict, scale_down_step_fixed: int, scale_down_step_percentage: float): 204 | # validate scale-down-step-fixed, must be >= 1 205 | if scale_down_step_fixed < 1: 206 | raise ValueError('scale-down-step-fixed must be >= 1') 207 | 208 | # validate scale-down-step-percentage, must be 0 <= value < 1 209 | if scale_down_step_percentage < 0 or scale_down_step_percentage >= 1: 210 | raise ValueError('scale-down-step-precentage value must be: 0 < value <= 1') 211 | 212 | node_counts_by_asg = collections.defaultdict(int) 213 | for key, nodes in sorted(nodes_by_asg_zone.items()): 214 | asg_name, zone = key 215 | node_counts_by_asg[asg_name] += len(nodes) 216 | 217 | for asg_name, desired_size in sorted(asg_sizes.items()): 218 | current_size = node_counts_by_asg[asg_name] 219 | amount_of_downscale = current_size - desired_size 220 | if amount_of_downscale >= 2: 221 | new_desired_size_fixed = current_size - scale_down_step_fixed 222 | new_desired_size_percentage = max(desired_size, int(math.ceil((1.00 - scale_down_step_percentage) * current_size))) 223 | if new_desired_size_percentage >= current_size: 224 | # percentage amount is too small, make sure we downscale by fixed amount at least 225 | new_desired_size_percentage = new_desired_size_fixed 226 | new_desired_size = min(new_desired_size_fixed, new_desired_size_percentage) 227 | logger.info('Slowing down downscale: changing desired size of ASG {} (current size is {}) from {} to {}'.format( 228 | asg_name, current_size, desired_size, new_desired_size)) 229 | asg_sizes[asg_name] = new_desired_size 230 | 231 | return asg_sizes 232 | 233 | 234 | def calculate_required_auto_scaling_group_sizes(nodes_by_asg_zone: dict, usage_by_asg_zone: dict, 235 | buffer_percentage: dict, buffer_fixed: dict, 236 | buffer_spare_nodes: int=0, disable_scale_down: bool=False): 237 | asg_size = collections.defaultdict(int) 238 | 239 | dump_info = STATS.get('last_info_dump', 0) < (time.time() - 600) 240 | 241 | for key, nodes in sorted(nodes_by_asg_zone.items()): 242 | asg_name, zone = key 243 | requested = usage_by_asg_zone.get(key) or {resource: 0 for resource in RESOURCES} 244 | pending = usage_by_asg_zone.get(('unknown', 'unknown')) 245 | if pending: 246 | # add requested resources from unassigned/pending pods 247 | for resource, val in pending.items(): 248 | requested[resource] += val 249 | requested_with_buffer = apply_buffer(requested, buffer_percentage, buffer_fixed) 250 | weakest_node = find_weakest_node(nodes) 251 | required_nodes = 0 252 | allocatable = {resource: 0 for resource in RESOURCES} 253 | while not is_sufficient(requested_with_buffer, allocatable): 254 | for resource in allocatable: 255 | allocatable[resource] += weakest_node['allocatable'][resource] 256 | required_nodes += 1 257 | 258 | for node in nodes: 259 | # compensate any manually cordoned nodes (e.g. by kubectl drain) 260 | # but only if they are "in service", i.e. not being terminated by ASG right now 261 | if node['unschedulable'] and not node['master'] and node['asg_lifecycle_state'] == 'InService': 262 | logger.info('Node {} is marked as unschedulable, compensating.'.format(node['name'])) 263 | required_nodes += 1 264 | 265 | required_nodes += buffer_spare_nodes 266 | 267 | overprovisioned = {resource: 0 for resource in RESOURCES} 268 | for resource, value in allocatable.items(): 269 | overprovisioned[resource] = value - requested[resource] 270 | 271 | if dump_info: 272 | logger.info('{}/{}: {}'.format(asg_name, zone, 273 | ' '.join([r.rjust(10).upper() for r in RESOURCES]))) 274 | logger.info('{}/{}: requested: {}'.format(asg_name, zone, 275 | ' '.join([format_resource(requested[r], r).rjust(10) for r in RESOURCES]))) 276 | logger.info('{}/{}: with buffer: {}'.format(asg_name, zone, 277 | ' '.join([format_resource(requested_with_buffer[r], r).rjust(10) for r in RESOURCES]))) 278 | logger.info('{}/{}: weakest node: {}'.format(asg_name, zone, 279 | ' '.join([format_resource(weakest_node['allocatable'][r], r).rjust(10) for r in RESOURCES]))) 280 | logger.info('{}/{}: overprovision: {}'.format(asg_name, zone, 281 | ' '.join([format_resource(overprovisioned[r], r).rjust(10) for r in RESOURCES]))) 282 | logger.info('{}/{}: => {} nodes required (current: {})'.format(asg_name, zone, required_nodes, len(nodes))) 283 | STATS['last_info_dump'] = time.time() 284 | 285 | if disable_scale_down: 286 | current_nodes = len(nodes) 287 | if dump_info and current_nodes > required_nodes: 288 | logger.info('{}/{}: scaling down is not allowed, forcing {} nodes'.format(asg_name, zone, current_nodes)) 289 | required_nodes = max(required_nodes, current_nodes) 290 | 291 | asg_size[asg_name] += required_nodes 292 | 293 | return asg_size 294 | 295 | 296 | def scaling_activity_in_progress(autoscaling, asg_name: str): 297 | ''' 298 | Return True if the given Auto Scaling Group currently has some activity in progress 299 | (e.g. replacing an instance, waiting for ELB draining or waiting for instance shut down) 300 | ''' 301 | result = autoscaling.describe_scaling_activities(AutoScalingGroupName=asg_name, MaxRecords=20) 302 | for activity in result['Activities']: 303 | # "Progress" is a % value between 0 and 100 that indicates the progress of the activity. 304 | if activity['Progress'] < 100: 305 | return True 306 | return False 307 | 308 | 309 | def resize_auto_scaling_groups(autoscaling, asg_size: dict, ready_nodes_by_asg: dict, dry_run: bool=False): 310 | asgs = {} 311 | response = autoscaling.describe_auto_scaling_groups(AutoScalingGroupNames=list(asg_size.keys())) 312 | for asg in response['AutoScalingGroups']: 313 | asgs[asg['AutoScalingGroupName']] = asg 314 | 315 | for asg_name, desired_capacity in sorted(asg_size.items()): 316 | asg = asgs[asg_name] 317 | if desired_capacity > asg['MaxSize']: 318 | logger.warn('Desired capacity for ASG {} is {}, but exceeds max {}'.format( 319 | asg_name, desired_capacity, asg['MaxSize'])) 320 | desired_capacity = asg['MaxSize'] 321 | elif desired_capacity < asg['MinSize']: 322 | logger.warn('Desired capacity for ASG {} is {}, but is lower than min {}'.format( 323 | asg_name, desired_capacity, asg['MinSize'])) 324 | desired_capacity = asg['MinSize'] 325 | if desired_capacity < asg['DesiredCapacity']: 326 | # potential scale down, let's check if it is safe.. 327 | if ready_nodes_by_asg.get(asg_name) < asg['DesiredCapacity']: 328 | logger.info('Some nodes are not ready in ASG {}, not scaling down from {} to {}'.format( 329 | asg_name, asg['DesiredCapacity'], desired_capacity)) 330 | desired_capacity = asg['DesiredCapacity'] 331 | elif scaling_activity_in_progress(autoscaling, asg_name): 332 | logger.info('Scaling activity in progress for ASG {}, not scaling down from {} to {}'.format( 333 | asg_name, asg['DesiredCapacity'], desired_capacity)) 334 | desired_capacity = asg['DesiredCapacity'] 335 | if desired_capacity != asg['DesiredCapacity']: 336 | logger.info('Changing desired capacity for ASG {} from {} to {}..'.format( 337 | asg_name, asg['DesiredCapacity'], desired_capacity)) 338 | if dry_run: 339 | logger.info('**DRY-RUN**: not performing any change') 340 | else: 341 | try: 342 | autoscaling.set_desired_capacity(AutoScalingGroupName=asg_name, DesiredCapacity=desired_capacity) 343 | except Exception: 344 | logger.exception('Failed to set desired capacity {} for ASG {}'.format(desired_capacity, asg_name)) 345 | raise 346 | 347 | 348 | def get_kube_api(): 349 | try: 350 | config = pykube.KubeConfig.from_service_account() 351 | except FileNotFoundError: 352 | # local testing 353 | config = pykube.KubeConfig.from_file(os.path.expanduser('~/.kube/config')) 354 | api = pykube.HTTPClient(config) 355 | return api 356 | 357 | 358 | def get_nodes_by_name(nodes: list): 359 | nodes_by_name = {} 360 | for node in nodes: 361 | nodes_by_name[node['name']] = node 362 | return nodes_by_name 363 | 364 | 365 | def get_ready_nodes_by_asg(nodes_by_asg_zone): 366 | ready_nodes_by_asg = collections.defaultdict(int) 367 | for key, nodes in sorted(nodes_by_asg_zone.items()): 368 | asg_name, _ = key 369 | for node in nodes: 370 | if node['ready']: 371 | ready_nodes_by_asg[asg_name] += 1 372 | return ready_nodes_by_asg 373 | 374 | 375 | @app.route('/healthz') 376 | def is_healthy(): 377 | if Healthy: 378 | return jsonify({'status': 'OK'}) 379 | else: 380 | return jsonify({'status': 'UNHEALTHY'}), 503 381 | 382 | 383 | def start_health_endpoint(): 384 | app.run(host='0.0.0.0', port=5000) 385 | 386 | 387 | def autoscale(buffer_percentage: dict, buffer_fixed: dict, 388 | scale_down_step_fixed: int, scale_down_step_percentage: float, 389 | buffer_spare_nodes: int = 0, include_master_nodes: bool=False, 390 | dry_run: bool=False, disable_scale_down: bool=False): 391 | api = get_kube_api() 392 | 393 | all_nodes = get_nodes(api, include_master_nodes) 394 | region = list(all_nodes.values())[0]['region'] 395 | autoscaling = boto3.client('autoscaling', region) 396 | nodes_by_asg_zone = get_nodes_by_asg_zone(autoscaling, all_nodes) 397 | 398 | # we only consider nodes found in an ASG (old "ghost" nodes returned from Kubernetes API are ignored) 399 | nodes_by_name = get_nodes_by_name(itertools.chain(*nodes_by_asg_zone.values())) 400 | 401 | pods = pykube.Pod.objects(api, namespace=pykube.all) 402 | 403 | usage_by_asg_zone = calculate_usage_by_asg_zone(pods, nodes_by_name) 404 | asg_size = calculate_required_auto_scaling_group_sizes(nodes_by_asg_zone, usage_by_asg_zone, buffer_percentage, buffer_fixed, 405 | buffer_spare_nodes=buffer_spare_nodes, disable_scale_down=disable_scale_down) 406 | asg_size = slow_down_downscale(asg_size, nodes_by_asg_zone, scale_down_step_fixed, scale_down_step_percentage) 407 | ready_nodes_by_asg = get_ready_nodes_by_asg(nodes_by_asg_zone) 408 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes_by_asg, dry_run) 409 | 410 | 411 | def main(): 412 | parser = argparse.ArgumentParser() 413 | parser.add_argument('--dry-run', help='Dry run mode: do not change anything, just print what would be done', 414 | action='store_true') 415 | parser.add_argument('--debug', '-d', help='Debug mode: print more information', action='store_true') 416 | parser.add_argument('--once', help='Run loop only once and exit', action='store_true') 417 | parser.add_argument('--interval', type=int, help='Loop interval (default: 60s)', default=60) 418 | parser.add_argument('--include-master-nodes', help='Do not ignore auto scaling group with master nodes', 419 | action='store_true') 420 | parser.add_argument('--buffer-spare-nodes', type=int, 421 | help='Number of extra "spare" nodes to provision per ASG/AZ (default: 1)', 422 | default=os.getenv('BUFFER_SPARE_NODES', 1)) 423 | parser.add_argument('--enable-healthcheck-endpoint', help='Enable Healtcheck', 424 | action='store_true') 425 | parser.add_argument('--no-scale-down', help='Disable scaling down', action='store_true') 426 | 427 | for resource in RESOURCES: 428 | parser.add_argument('--buffer-{}-percentage'.format(resource), type=float, 429 | help='{} buffer %%'.format(resource.capitalize()), 430 | default=os.getenv('BUFFER_{}_PERCENTAGE'.format(resource.upper()), DEFAULT_BUFFER_PERCENTAGE[resource])) 431 | parser.add_argument('--buffer-{}-fixed'.format(resource), type=str, 432 | help='{} buffer (fixed amount)'.format(resource.capitalize()), 433 | default=os.getenv('BUFFER_{}_FIXED'.format(resource.upper()), DEFAULT_BUFFER_FIXED[resource])) 434 | 435 | parser.add_argument('--scale-down-step-fixed', 436 | help='Scale down strategy expressed in terms of instances count, defaults to 1. Note: value must be >= 1', 437 | type=int, default=os.getenv('SCALE_DOWN_STEP_FIXED', 1)) 438 | parser.add_argument('--scale-down-step-percentage', 439 | help='Scale down strategy expressed in terms of instances count, defaults to 0.00, i.e. 0%%.', 440 | type=float, default=os.getenv('SCALE_DOWN_STEP_PRECENTAGE', 0.0)) 441 | 442 | args = parser.parse_args() 443 | 444 | # validate scale-down-step values 445 | if args.scale_down_step_fixed < 1: 446 | msg = 'Invalid scale-down-step-fixed value: {}'.format(args.scale_down_step_fixed) 447 | logger.exception(msg) 448 | raise ValueError(msg) 449 | if args.scale_down_step_percentage < 0 or args.scale_down_step_percentage > 1: 450 | msg = 'Invalid scale-down-step-percentage value: {}'.format(args.scale_down_step_percentage) 451 | logger.exception(msg) 452 | raise ValueError(msg) 453 | 454 | logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.DEBUG if args.debug else logging.INFO) 455 | logging.getLogger('botocore').setLevel(logging.WARN) 456 | 457 | buffer_percentage = {} 458 | buffer_fixed = {} 459 | for resource in RESOURCES: 460 | buffer_percentage[resource] = getattr(args, 'buffer_{}_percentage'.format(resource)) 461 | buffer_fixed[resource] = parse_resource(getattr(args, 'buffer_{}_fixed'.format(resource))) 462 | 463 | if args.dry_run: 464 | logger.info('**DRY-RUN**: no autoscaling will be performed!') 465 | 466 | if args.enable_healthcheck_endpoint: 467 | t = Thread(target=start_health_endpoint, daemon=True) 468 | t.start() 469 | 470 | global Healthy 471 | while True: 472 | try: 473 | autoscale(buffer_percentage, buffer_fixed, 474 | scale_down_step_fixed=args.scale_down_step_fixed, 475 | scale_down_step_percentage=args.scale_down_step_percentage, 476 | buffer_spare_nodes=args.buffer_spare_nodes, 477 | include_master_nodes=args.include_master_nodes, dry_run=args.dry_run, 478 | disable_scale_down=args.no_scale_down) 479 | Healthy = True 480 | except Exception: 481 | Healthy = False 482 | logger.exception('Failed to autoscale') 483 | if args.once: 484 | return 485 | time.sleep(args.interval) 486 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | pykube 3 | flask 4 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import io 3 | 4 | from setuptools import find_packages, setup 5 | from setuptools.command.test import test as TestCommand 6 | 7 | from pathlib import Path 8 | 9 | 10 | def read_version(package): 11 | with (Path(package) / '__init__.py').open() as fd: 12 | for line in fd: 13 | if line.startswith('__version__ = '): 14 | return line.split()[-1].strip().strip("'") 15 | 16 | 17 | version = read_version('kube_aws_autoscaler') 18 | 19 | 20 | class PyTest(TestCommand): 21 | 22 | user_options = [('cov-html=', None, 'Generate junit html report')] 23 | 24 | def initialize_options(self): 25 | TestCommand.initialize_options(self) 26 | self.cov = None 27 | self.pytest_args = ['--cov', 'kube_aws_autoscaler', '--cov-report', 'term-missing', '-v'] 28 | self.cov_html = False 29 | 30 | def finalize_options(self): 31 | TestCommand.finalize_options(self) 32 | if self.cov_html: 33 | self.pytest_args.extend(['--cov-report', 'html']) 34 | self.pytest_args.extend(['tests']) 35 | 36 | def run_tests(self): 37 | import pytest 38 | 39 | errno = pytest.main(self.pytest_args) 40 | sys.exit(errno) 41 | 42 | 43 | def readme(): 44 | return io.open('README.rst', encoding='utf-8').read() 45 | 46 | 47 | tests_require = [ 48 | 'pytest', 49 | 'pytest-cov' 50 | ] 51 | 52 | setup( 53 | name='kube-aws-autoscaler', 54 | packages=find_packages(), 55 | version=version, 56 | description='Kubernetes AWS Autoscaler', 57 | long_description=readme(), 58 | author='Henning Jacobs', 59 | url='https://github.com/hjacobs/kube-aws-autoscaler', 60 | keywords='kubernetes operations aws autoscaler', 61 | license='GNU General Public License v3 (GPLv3)', 62 | tests_require=tests_require, 63 | extras_require={'tests': tests_require}, 64 | cmdclass={'test': PyTest}, 65 | test_suite='tests', 66 | classifiers=[ 67 | 'Development Status :: 3 - Alpha', 68 | 'Intended Audience :: Developers', 69 | 'Intended Audience :: System Administrators', 70 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 71 | 'Operating System :: OS Independent', 72 | 'Programming Language :: Python', 73 | 'Programming Language :: Python :: 3.5', 74 | 'Topic :: System :: Clustering', 75 | 'Topic :: System :: Monitoring', 76 | ], 77 | entry_points={'console_scripts': ['kube-aws-autoscaler = kube_aws_autoscaler.main:main']} 78 | ) 79 | -------------------------------------------------------------------------------- /tests/test_autoscaler.py: -------------------------------------------------------------------------------- 1 | import os 2 | from unittest.mock import MagicMock 3 | import pytest 4 | from kube_aws_autoscaler.main import (apply_buffer, autoscale, 5 | calculate_required_auto_scaling_group_sizes, 6 | calculate_usage_by_asg_zone, chunks, 7 | format_resource, get_kube_api, get_nodes, 8 | get_nodes_by_asg_zone, is_node_ready, 9 | is_sufficient, main, parse_resource, 10 | resize_auto_scaling_groups, 11 | scaling_activity_in_progress, 12 | slow_down_downscale, app) 13 | import kube_aws_autoscaler.main 14 | 15 | 16 | def test_parse_resource(): 17 | assert parse_resource('100Mi') == 100*1024*1024 18 | 19 | 20 | def test_apply_buffer(): 21 | assert apply_buffer({'foo': 1}, {}, {}) == {'foo': 1} 22 | assert apply_buffer({'foo': 1}, {'foo': 10}, {}) == {'foo': 1.1} 23 | assert apply_buffer({'foo': 1}, {'foo': 10}, {'foo': 0.01}) == {'foo': 1.11} 24 | 25 | 26 | def test_is_sufficient(): 27 | assert is_sufficient({}, {}) 28 | assert is_sufficient({}, {'foo': 1}) 29 | assert is_sufficient({'foo': 0.5}, {'foo': 1}) 30 | assert is_sufficient({'foo': 1}, {'foo': 1}) 31 | assert not is_sufficient({'foo': 1.1}, {'foo': 1}) 32 | 33 | 34 | def test_calculate_usage_by_asg_zone(): 35 | assert calculate_usage_by_asg_zone([], {}) == {} 36 | 37 | pod = MagicMock() 38 | pod.obj = {'status': {}, 'spec': {'containers': []}} 39 | assert calculate_usage_by_asg_zone([pod], {}) == {('unknown', 'unknown'): {'cpu': 0, 'memory': 0, 'pods': 1}} 40 | 41 | pod = MagicMock() 42 | pod.obj = {'status': {'phase': 'Succeeded'}, 'spec': {'containers': []}} 43 | assert calculate_usage_by_asg_zone([pod], {}) == {} 44 | 45 | pod = MagicMock() 46 | pod.name = 'mypod' 47 | pod.obj = {'status': {}, 'spec': {'nodeName': 'foo', 'containers': [{'name': 'mycont', 'resources': {'requests': {'cpu': '1m'}}}]}} 48 | nodes = {'foo': {'asg_name': 'asg1', 'zone': 'z1'}} 49 | assert calculate_usage_by_asg_zone([pod], nodes) == {('asg1', 'z1'): {'cpu': 1/1000, 'memory': 52428800, 'pods': 1}} 50 | 51 | # pod is assigned to a node, but pending 52 | pod = MagicMock() 53 | pod.name = 'mypod' 54 | pod.obj = {'status': {'phase': 'Pending'}, 'spec': {'nodeName': 'foo', 'containers': [{'name': 'mycont', 'resources': {'requests': {'cpu': '1m'}}}]}} 55 | nodes = {} 56 | assert calculate_usage_by_asg_zone([pod], nodes) == {('unknown', 'unknown'): {'cpu': 1/1000, 'memory': 52428800, 'pods': 1}} 57 | 58 | # pod is a "ghost" --- returned by API but node no longer exists 59 | pod = MagicMock() 60 | pod.name = 'mypod' 61 | pod.obj = {'status': {'phase': 'Running'}, 'spec': {'nodeName': 'foo', 'containers': [{'name': 'mycont', 'resources': {'requests': {'cpu': '1m'}}}]}} 62 | nodes = {} 63 | assert calculate_usage_by_asg_zone([pod], nodes) == {} 64 | 65 | # failed pod, should be included in the calculations 66 | pod = MagicMock() 67 | pod.name = 'mypod' 68 | pod.obj = {'status': {'phase': 'Failed'}, 'spec': {'nodeName': 'foo', 'containers': [{'name': 'mycont', 'resources': {'requests': {'cpu': '1m'}}}]}} 69 | assert calculate_usage_by_asg_zone([pod], {}) == {('unknown', 'unknown'): {'cpu': 1/1000, 'memory': 52428800, 'pods': 1}} 70 | 71 | # failed pod that won't be restarted, should not be included in the calculations 72 | pod = MagicMock() 73 | pod.name = 'mypod' 74 | pod.obj = {'status': {'phase': 'Failed'}, 'spec': {'nodeName': 'foo', 'restartPolicy': 'Never', 'containers': [{'name': 'mycont', 'resources': {'requests': {'cpu': '1m'}}}]}} 75 | assert calculate_usage_by_asg_zone([pod], {}) == {} 76 | 77 | 78 | def test_calculate_required_auto_scaling_group_sizes(): 79 | assert calculate_required_auto_scaling_group_sizes({}, {}, {}, {}) == {} 80 | node = {'allocatable': {'cpu': 1, 'memory': 1, 'pods': 1}, 'unschedulable': False, 'master': False} 81 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {}, {}, {}) == {'a1': 0} 82 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {('a1', 'z1'): {'cpu': 1, 'memory': 1, 'pods': 1}}, {}, {}) == {'a1': 1} 83 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {('unknown', 'unknown'): {'cpu': 1, 'memory': 1, 'pods': 1}}, {}, {}) == {'a1': 1} 84 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {}, {}, {}, buffer_spare_nodes=2) == {'a1': 2} 85 | 86 | 87 | def test_calculate_required_auto_scaling_group_sizes_no_scaledown(): 88 | nodes = [{'allocatable': {'cpu': 1, 'memory': 1, 'pods': 1}, 'unschedulable': False, 'master': False}, 89 | {'allocatable': {'cpu': 1, 'memory': 1, 'pods': 1}, 'unschedulable': False, 'master': False}] 90 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): nodes}, {}, {}, {}) == {'a1': 0} 91 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): nodes}, {}, {}, {}, disable_scale_down=True) == {'a1': 2} 92 | 93 | 94 | def test_calculate_required_auto_scaling_group_sizes_cordon(): 95 | node = {'name': 'mynode', 'allocatable': {'cpu': 1, 'memory': 1, 'pods': 1}, 'unschedulable': True, 'master': False, 'asg_lifecycle_state': 'InService'} 96 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {}, {}, {}) == {'a1': 1} 97 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {('a1', 'z1'): {'cpu': 1, 'memory': 1, 'pods': 1}}, {}, {}) == {'a1': 2} 98 | 99 | 100 | def test_calculate_required_auto_scaling_group_sizes_unschedulable_terminating(): 101 | node = {'name': 'mynode', 'allocatable': {'cpu': 1, 'memory': 1, 'pods': 1}, 'unschedulable': True, 'master': False, 'asg_lifecycle_state': 'Terminating'} 102 | # do not compensate if the instance is terminating.. (it will probably be replaced by ASG) 103 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {}, {}, {}) == {'a1': 0} 104 | assert calculate_required_auto_scaling_group_sizes({('a1', 'z1'): [node]}, {('a1', 'z1'): {'cpu': 1, 'memory': 1, 'pods': 1}}, {}, {}) == {'a1': 1} 105 | 106 | 107 | def test_get_nodes_by_asg_zone(): 108 | autoscaling = MagicMock() 109 | autoscaling.describe_auto_scaling_instances.return_value = {'AutoScalingInstances': []} 110 | assert get_nodes_by_asg_zone(autoscaling, {}) == {} 111 | 112 | autoscaling.describe_auto_scaling_instances.return_value = {'AutoScalingInstances': [ 113 | {'InstanceId': 'i-1', 'AutoScalingGroupName': 'myasg', 'AvailabilityZone': 'myaz', 'LifecycleState': 'InService'} 114 | ]} 115 | expected_result = {('myasg', 'myaz'): [{'asg_name': 'myasg', 'instance_id': 'i-1', 'asg_lifecycle_state': 'InService'}]} 116 | assert get_nodes_by_asg_zone(autoscaling, {'foo': {'instance_id': 'i-1'}}) == expected_result 117 | 118 | 119 | def test_get_nodes_by_asg_zone_chunked(): 120 | 121 | def describe_auto_scaling_instances(InstanceIds): 122 | # AWS API only supports chunks of 50 123 | assert len(InstanceIds) <= 50 124 | return {'AutoScalingInstances': list([ 125 | {'InstanceId': instance_id, 'AutoScalingGroupName': 'myasg', 'AvailabilityZone': 'myaz', 'LifecycleState': 'InService'} for instance_id in InstanceIds 126 | ])} 127 | 128 | autoscaling = MagicMock() 129 | autoscaling.describe_auto_scaling_instances = describe_auto_scaling_instances 130 | expected_result = {('myasg', 'myaz'): []} 131 | nodes = {} 132 | for i in range(51): 133 | nodes['node-{:02d}'.format(i)] = {'instance_id': 'i-{:02d}'.format(i)} 134 | expected_result[('myasg', 'myaz')].append({'asg_name': 'myasg', 'instance_id': 'i-{:02d}'.format(i), 'asg_lifecycle_state': 'InService'}) 135 | actual_result = get_nodes_by_asg_zone(autoscaling, nodes) 136 | assert actual_result == expected_result 137 | 138 | 139 | def test_resize_auto_scaling_groups_empty(): 140 | autoscaling = MagicMock() 141 | autoscaling.describe_auto_scaling_groups.return_value = {'AutoScalingGroups': []} 142 | asg_size = {} 143 | resize_auto_scaling_groups(autoscaling, asg_size, {}) 144 | autoscaling.set_desired_capacity.assert_not_called() 145 | 146 | 147 | def test_resize_auto_scaling_groups_downscale(): 148 | autoscaling = MagicMock() 149 | autoscaling.describe_auto_scaling_groups.return_value = { 150 | 'AutoScalingGroups': [{ 151 | 'AutoScalingGroupName': 'asg1', 152 | 'DesiredCapacity': 2, 153 | 'MinSize': 1, 154 | 'MaxSize': 10 155 | }] 156 | } 157 | asg_size = {'asg1': 1} 158 | ready_nodes = {'asg1': 2} 159 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 160 | autoscaling.set_desired_capacity.assert_called_with(AutoScalingGroupName='asg1', DesiredCapacity=1) 161 | 162 | 163 | def test_resize_auto_scaling_groups_nochange(): 164 | autoscaling = MagicMock() 165 | autoscaling.describe_auto_scaling_groups.return_value = { 166 | 'AutoScalingGroups': [{ 167 | 'AutoScalingGroupName': 'asg1', 168 | 'DesiredCapacity': 2, 169 | 'MinSize': 1, 170 | 'MaxSize': 10 171 | }] 172 | } 173 | asg_size = {'asg1': 2} 174 | ready_nodes = {'asg1': 2} 175 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 176 | autoscaling.set_desired_capacity.assert_not_called() 177 | 178 | asg_size = {'asg1': 1} 179 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes, dry_run=True) 180 | autoscaling.set_desired_capacity.assert_not_called() 181 | 182 | 183 | def test_resize_auto_scaling_groups_constraints(): 184 | autoscaling = MagicMock() 185 | autoscaling.describe_auto_scaling_groups.return_value = { 186 | 'AutoScalingGroups': [{ 187 | 'AutoScalingGroupName': 'asg1', 188 | 'DesiredCapacity': 2, 189 | 'MinSize': 2, 190 | 'MaxSize': 2 191 | }] 192 | } 193 | asg_size = {'asg1': 1} 194 | ready_nodes = {'asg1': 2} 195 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 196 | autoscaling.set_desired_capacity.assert_not_called() 197 | 198 | asg_size = {'asg1': 3} 199 | ready_nodes = {'asg1': 2} 200 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 201 | autoscaling.set_desired_capacity.assert_not_called() 202 | 203 | 204 | def test_resize_auto_scaling_groups_to_min_max(): 205 | autoscaling = MagicMock() 206 | autoscaling.describe_auto_scaling_groups.return_value = { 207 | 'AutoScalingGroups': [{ 208 | 'AutoScalingGroupName': 'asg1', 209 | 'DesiredCapacity': 3, 210 | 'MinSize': 2, 211 | 'MaxSize': 10 212 | }] 213 | } 214 | asg_size = {'asg1': 1} 215 | ready_nodes = {'asg1': 3} 216 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 217 | autoscaling.set_desired_capacity.assert_called_with(AutoScalingGroupName='asg1', DesiredCapacity=2) 218 | 219 | asg_size = {'asg1': 18} 220 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 221 | autoscaling.set_desired_capacity.assert_called_with(AutoScalingGroupName='asg1', DesiredCapacity=10) 222 | 223 | 224 | def test_resize_auto_scaling_groups_activity_in_progress(monkeypatch): 225 | monkeypatch.setattr('kube_aws_autoscaler.main.scaling_activity_in_progress', lambda a, b: True) 226 | autoscaling = MagicMock() 227 | autoscaling.describe_auto_scaling_groups.return_value = { 228 | 'AutoScalingGroups': [{ 229 | 'AutoScalingGroupName': 'asg1', 230 | 'DesiredCapacity': 3, 231 | 'MinSize': 2, 232 | 'MaxSize': 10 233 | }] 234 | } 235 | asg_size = {'asg1': 2} 236 | ready_nodes = {'asg1': 3} 237 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 238 | autoscaling.set_desired_capacity.assert_not_called() 239 | 240 | 241 | def test_resize_auto_scaling_groups_nodes_not_ready(monkeypatch): 242 | monkeypatch.setattr('kube_aws_autoscaler.main.scaling_activity_in_progress', lambda a, b: False) 243 | autoscaling = MagicMock() 244 | autoscaling.describe_auto_scaling_groups.return_value = { 245 | 'AutoScalingGroups': [{ 246 | 'AutoScalingGroupName': 'asg1', 247 | 'DesiredCapacity': 3, 248 | 'MinSize': 2, 249 | 'MaxSize': 10 250 | }] 251 | } 252 | asg_size = {'asg1': 2} 253 | ready_nodes = {'asg1': 2} 254 | resize_auto_scaling_groups(autoscaling, asg_size, ready_nodes) 255 | autoscaling.set_desired_capacity.assert_not_called() 256 | 257 | 258 | def test_activity_in_progress(): 259 | autoscaling = MagicMock() 260 | autoscaling.describe_scaling_activities.return_value = { 261 | 'Activities': [] 262 | } 263 | assert not scaling_activity_in_progress(autoscaling, 'my-asg') 264 | autoscaling.describe_scaling_activities.return_value = { 265 | 'Activities': [{ 266 | 'Progress': 100 267 | }] 268 | } 269 | assert not scaling_activity_in_progress(autoscaling, 'my-asg') 270 | autoscaling.describe_scaling_activities.return_value = { 271 | 'Activities': [ 272 | {'Progress': 100}, 273 | {'Progress': 67} 274 | ] 275 | } 276 | assert scaling_activity_in_progress(autoscaling, 'my-asg') 277 | 278 | 279 | def test_get_nodes(monkeypatch): 280 | node = MagicMock() 281 | node.name = 'n1' 282 | node.labels = { 283 | 'failure-domain.beta.kubernetes.io/region': 'eu-north-1', 284 | 'failure-domain.beta.kubernetes.io/zone': 'eu-north-1a', 285 | 'beta.kubernetes.io/instance-type': 'x1.mega' 286 | } 287 | node.obj = { 288 | 'status': {'allocatable': {'cpu': '2', 'memory': '16Gi', 'pods': '10'}}, 289 | 'spec': {'externalID': 'i-123'} 290 | } 291 | 292 | master = MagicMock() 293 | master.name = 'master' 294 | master.labels = { 295 | 'failure-domain.beta.kubernetes.io/region': 'eu-north-1', 296 | 'failure-domain.beta.kubernetes.io/zone': 'eu-north-1a', 297 | 'beta.kubernetes.io/instance-type': 'a1.small', 298 | 'master': 'true' 299 | } 300 | master.obj = { 301 | 'status': {'allocatable': {'cpu': '2', 'memory': '16Gi', 'pods': '10'}}, 302 | 'spec': {'externalID': 'i-456'} 303 | } 304 | 305 | objects = MagicMock() 306 | objects.return_value = [node, master] 307 | monkeypatch.setattr('pykube.Node.objects', objects) 308 | api = MagicMock() 309 | assert get_nodes(api) == {'n1': { 310 | 'name': 'n1', 311 | 'region': 'eu-north-1', 'zone': 'eu-north-1a', 'instance_id': 'i-123', 'instance_type': 'x1.mega', 312 | 'allocatable': {'cpu': 2, 'memory': 16*1024*1024*1024, 'pods': 10}, 313 | 'ready': False, 314 | 'unschedulable': False, 315 | 'master': False}} 316 | 317 | assert get_nodes(api, include_master_nodes=True) == {'n1': { 318 | 'name': 'n1', 319 | 'region': 'eu-north-1', 'zone': 'eu-north-1a', 'instance_id': 'i-123', 'instance_type': 'x1.mega', 320 | 'allocatable': {'cpu': 2, 'memory': 16*1024*1024*1024, 'pods': 10}, 321 | 'ready': False, 322 | 'unschedulable': False, 323 | 'master': False}, 'master': { 324 | 'name': 'master', 325 | 'region': 'eu-north-1', 'zone': 'eu-north-1a', 'instance_id': 'i-456', 'instance_type': 'a1.small', 326 | 'allocatable': {'cpu': 2, 'memory': 16*1024*1024*1024, 'pods': 10}, 327 | 'ready': False, 328 | 'unschedulable': False, 329 | 'master': True 330 | }} 331 | 332 | 333 | def test_get_kube_api(monkeypatch): 334 | kube_config = MagicMock() 335 | kube_config.from_service_account.side_effect = FileNotFoundError 336 | monkeypatch.setattr('pykube.KubeConfig', kube_config) 337 | monkeypatch.setattr('pykube.HTTPClient', MagicMock()) 338 | get_kube_api() 339 | kube_config.from_file.assert_called_once_with(os.path.expanduser('~/.kube/config')) 340 | 341 | 342 | def test_autoscale(monkeypatch): 343 | kube_config = MagicMock() 344 | get_nodes = MagicMock() 345 | get_nodes.return_value = {'n1': { 346 | 'name': 'n1', 347 | 'region': 'eu-north-1', 'zone': 'eu-north-1a', 'instance_id': 'i-123', 'instance_type': 'x1.mega', 348 | 'allocatable': {'cpu': 2, 'memory': 16*1024*1024*1024, 'pods': 10}, 349 | 'ready': True, 350 | 'unschedulable': False, 351 | 'master': False}} 352 | get_pods = MagicMock() 353 | pod = MagicMock() 354 | pod.obj = {'status': {}, 'spec': {'nodeName': 'n1', 'containers': [{'name': 'c1', 'resources': {'requests': {'cpu': '4000m'}}}]}} 355 | get_pods.return_value = [pod] 356 | boto3_client = MagicMock() 357 | boto3_client.return_value.describe_auto_scaling_instances.return_value = {'AutoScalingInstances': [ 358 | {'InstanceId': 'i-123', 'AutoScalingGroupName': 'a1', 'AvailabilityZone': 'eu-north-1a', 'LifecycleState': 'InService'} 359 | ]} 360 | boto3_client.return_value.describe_auto_scaling_groups.return_value = {'AutoScalingGroups': [{'AutoScalingGroupName': 'a1', 'DesiredCapacity': 1, 'MinSize': 1, 'MaxSize': 10}]} 361 | monkeypatch.setattr('pykube.KubeConfig', kube_config) 362 | monkeypatch.setattr('pykube.HTTPClient', MagicMock()) 363 | monkeypatch.setattr('pykube.Pod.objects', get_pods) 364 | monkeypatch.setattr('kube_aws_autoscaler.main.get_nodes', get_nodes) 365 | monkeypatch.setattr('boto3.client', boto3_client) 366 | 367 | buffer_percentage = {} 368 | buffer_fixed = {} 369 | autoscale(buffer_percentage, buffer_fixed, 1, 0.0, False) 370 | boto3_client.return_value.set_desired_capacity.assert_called_with(AutoScalingGroupName='a1', DesiredCapacity=2) 371 | 372 | 373 | def test_autoscale_node_without_asg(monkeypatch): 374 | kube_config = MagicMock() 375 | get_nodes = MagicMock() 376 | get_nodes.return_value = {'n1': { 377 | 'name': 'n1', 378 | 'region': 'eu-north-1', 'zone': 'eu-north-1a', 'instance_id': 'i-123', 'instance_type': 'x1.mega', 379 | 'allocatable': {'cpu': 2, 'memory': 16*1024*1024*1024, 'pods': 10}, 380 | 'ready': True, 381 | 'unschedulable': False, 382 | 'master': False}} 383 | get_pods = MagicMock() 384 | pod = MagicMock() 385 | pod.obj = {'status': {}, 'spec': {'nodeName': 'n1', 'containers': [{'name': 'c1', 'resources': {'requests': {'cpu': '1000m'}}}]}} 386 | get_pods.return_value = [pod] 387 | boto3_client = MagicMock() 388 | boto3_client.return_value.describe_auto_scaling_instances.return_value = {'AutoScalingInstances': []} 389 | boto3_client.return_value.describe_auto_scaling_groups.return_value = {'AutoScalingGroups': [{'AutoScalingGroupName': 'a1', 'DesiredCapacity': 1, 'MinSize': 1, 'MaxSize': 10}]} 390 | monkeypatch.setattr('pykube.KubeConfig', kube_config) 391 | monkeypatch.setattr('pykube.HTTPClient', MagicMock()) 392 | monkeypatch.setattr('pykube.Pod.objects', get_pods) 393 | monkeypatch.setattr('kube_aws_autoscaler.main.get_nodes', get_nodes) 394 | monkeypatch.setattr('boto3.client', boto3_client) 395 | 396 | buffer_percentage = {} 397 | buffer_fixed = {} 398 | autoscale(buffer_percentage, buffer_fixed, 1, 0.0, False) 399 | 400 | 401 | def test_main(monkeypatch): 402 | autoscale = MagicMock() 403 | monkeypatch.setattr('kube_aws_autoscaler.main.autoscale', autoscale) 404 | monkeypatch.setattr('sys.argv', ['foo', '--once', '--dry-run']) 405 | main() 406 | autoscale.assert_called_once_with( 407 | {'memory': 10, 'pods': 10, 'cpu': 10}, 408 | {'memory': 209715200, 'pods': 10, 'cpu': 0.2}, 409 | buffer_spare_nodes=1, include_master_nodes=False, dry_run=True, disable_scale_down=False, 410 | scale_down_step_fixed=1, scale_down_step_percentage=0.0 411 | ) 412 | 413 | autoscale.side_effect = ValueError 414 | 415 | monkeypatch.setattr('sys.argv', ['foo', '--dry-run']) 416 | monkeypatch.setattr('time.sleep', MagicMock(side_effect=Exception)) 417 | with pytest.raises(Exception): 418 | main() 419 | 420 | def test_main_step_down(monkeypatch): 421 | monkeypatch.setattr('sys.argv', ['foo', '--once', '--dry-run', '--scale-down-step-fixed=0']) 422 | with pytest.raises(ValueError) as err: 423 | main() 424 | assert 'Invalid scale-down-step-fixed value: 0' in str(err.value) 425 | 426 | monkeypatch.setattr('sys.argv', ['foo', '--once', '--dry-run', '--scale-down-step-fixed=-1']) 427 | with pytest.raises(ValueError) as err: 428 | main() 429 | assert 'Invalid scale-down-step-fixed value: -1' in str(err.value) 430 | 431 | monkeypatch.setattr('sys.argv', ['foo', '--once', '--dry-run', '--scale-down-step-percentage=-0.0001']) 432 | with pytest.raises(ValueError) as err: 433 | main() 434 | assert 'Invalid scale-down-step-percentage value: -0.0001' in str(err.value) 435 | 436 | monkeypatch.setattr('sys.argv', ['foo', '--once', '--dry-run', '--scale-down-step-percentage=1.0001']) 437 | with pytest.raises(ValueError) as err: 438 | main() 439 | assert 'Invalid scale-down-step-percentage value: 1.0001' in str(err.value) 440 | 441 | 442 | def test_format_resource(): 443 | assert format_resource(1, 'cpu') == '1.0' 444 | assert format_resource(1024*1024, 'memory') == '1Mi' 445 | assert format_resource(1, 'pods') == '1' 446 | assert format_resource(1, 'foo') == '1' 447 | 448 | 449 | def test_slow_down_downscale(): 450 | # assert invalid scale-down-step-fixed value 451 | with pytest.raises(ValueError) as err: 452 | slow_down_downscale({}, {}, 0, 0.0) 453 | assert 'scale-down-step-fixed must be >= 1' in str(err.value) 454 | 455 | # assert invalid scale-down-step-percentage (negative) 456 | with pytest.raises(ValueError) as err: 457 | slow_down_downscale({}, {}, 1, -1) 458 | assert 'scale-down-step-precentage value must be: 0 < value <= 1' in str(err.value) 459 | 460 | # assert invalid scale-down-step-percentage (greater than 100%) 461 | with pytest.raises(ValueError) as err: 462 | slow_down_downscale({}, {}, 1, 1.1) 463 | assert 'scale-down-step-precentage value must be: 0 < value <= 1' in str(err.value) 464 | 465 | # test with 1 step fixed and 0 step percentage 466 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}]}, 1, 0.0) == {'a1': 1} 467 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}]}, 1, 0.0) == {'a1': 1} 468 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}]}, 1, 0.0) == {'a1': 2} 469 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}], ('a1', 'z2'): [{}]}, 1, 0.0) == {'a1': 2} 470 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}], ('a1', 'z2'): [{}, {}]}, 1, 0.0) == {'a1': 3} 471 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}], ('a1', 'z2'): [{}, {}]}, 1, 0.0) == {'a1': 4} 472 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}], ('a1', 'z2'): [{}, {}, {}]}, 1, 0.0) == {'a1': 5} 473 | 474 | # test with 1 step fixed and 1% step percentage (same as above) 475 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}]}, 1, 0.01) == {'a1': 1} 476 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}]}, 1, 0.01) == {'a1': 1} 477 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}]}, 1, 0.01) == {'a1': 2} 478 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}], ('a1', 'z2'): [{}]}, 1, 0.01) == {'a1': 2} 479 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}], ('a1', 'z2'): [{}, {}]}, 1, 0.01) == {'a1': 3} 480 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}], ('a1', 'z2'): [{}, {}]}, 1, 0.0) == {'a1': 4} 481 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}], ('a1', 'z2'): [{}, {}, {}]}, 1, 0.0) == {'a1': 5} 482 | 483 | # test with 1 step fixed and 50% step percentage 484 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}]}, 1, 0.5) == {'a1': 1} 485 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}]}, 1, 0.5) == {'a1': 1} 486 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}]}, 1, 0.5) == {'a1': 2} 487 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}], ('a1', 'z2'): [{}]}, 1, 0.5) == {'a1': 2} 488 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}], ('a1', 'z2'): [{}, {}]}, 1, 0.5) == {'a1': 2} 489 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}], ('a1', 'z2'): [{}, {}]}, 1, 0.5) == {'a1': 3} 490 | assert slow_down_downscale({'a1': 1}, {('a1', 'z1'): [{}, {}, {}], ('a1', 'z2'): [{}, {}, {}]}, 1, 0.5) == {'a1': 3} 491 | 492 | 493 | def test_is_node_ready(): 494 | node = MagicMock() 495 | node.obj = {'status': {}} 496 | assert not is_node_ready(node) 497 | node.obj = {'status': {'conditions': [{'type': 'Ready', 'status': 'False'}]}} 498 | assert not is_node_ready(node) 499 | node.obj = {'status': {'conditions': [{'type': 'Ready', 'status': 'True'}]}} 500 | assert is_node_ready(node) 501 | 502 | 503 | def test_chunks(): 504 | assert list(chunks([], 1)) == [] 505 | assert list(chunks([1], 1)) == [[1]] 506 | assert list(chunks([1, 2], 1)) == [[1], [2]] 507 | assert list(chunks([1, 2, 3], 2)) == [[1, 2], [3]] 508 | 509 | 510 | def test_start_health_endpoint(): 511 | flask = app.test_client() 512 | flask.testing = True 513 | response = flask.get('/healthz') 514 | assert response.status_code == 503 515 | 516 | def test_endpoint_healthy_state(monkeypatch): 517 | kube_aws_autoscaler.main.Healthy = False 518 | autoscale = MagicMock() 519 | monkeypatch.setattr('kube_aws_autoscaler.main.autoscale', autoscale) 520 | monkeypatch.setattr('sys.argv', ['foo', '--once', '--dry-run']) 521 | main() 522 | assert kube_aws_autoscaler.main.Healthy == True 523 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist=py36,flake8 3 | 4 | [tox:travis] 5 | 3.6=py36,flake8 6 | 7 | [testenv] 8 | deps=pytest 9 | commands= 10 | pip install -r requirements.txt 11 | python setup.py test 12 | 13 | [testenv:flake8] 14 | deps=flake8 15 | commands=python setup.py flake8 16 | 17 | [flake8] 18 | max-line-length=160 19 | --------------------------------------------------------------------------------