├── .gitignore ├── CHANGELOG ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── RELEASE ├── VERSION ├── bin └── monit-docker ├── debian ├── changelog ├── compat ├── control ├── copyright ├── dirs ├── docs ├── install ├── logrotate ├── postinst └── rules ├── docker-compose.yml ├── docker-run.sh ├── docs ├── Makefile ├── _static │ └── .gitkeep ├── conf.py ├── index.md └── requirements.txt ├── etc └── monit-docker │ ├── clients.yml.example │ ├── foo_https.vars.yml.example │ └── monit-docker.yml.example ├── requirements.txt ├── setup.cfg ├── setup.py ├── setup.yml └── setup.yml.j2 /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *~ 3 | *.sw* 4 | *.egg/ 5 | *.egg-info 6 | __pycache__ 7 | build/ 8 | dist/ 9 | docs/_build/ 10 | TODO 11 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | monit-docker (0.0.50) unstable; urgency=medium 2 | 3 | * [RELEASE] version: 0.0.50. 4 | * Removed libressl-dev package in Dockerfile. 5 | 6 | -- Adrien DELLE CAVE (Decryptus) Mon, 16 Jan 2023 12:28:30 +0100 7 | 8 | monit-docker (0.0.49) unstable; urgency=medium 9 | 10 | * [RELEASE] version: 0.0.49. 11 | * Fixed #5 12 | 13 | -- Adrien DELLE CAVE (Decryptus) Mon, 16 Jan 2023 04:59:28 +0100 14 | 15 | monit-docker (0.0.48) unstable; urgency=medium 16 | 17 | * [RELEASE] version: 0.0.48. 18 | 19 | -- Adrien DELLE CAVE (Decryptus) Sat, 29 Oct 2022 08:25:38 +0200 20 | 21 | monit-docker (0.0.47) unstable; urgency=medium 22 | 23 | * Fixed #4 24 | 25 | -- Adrien DELLE CAVE (Decryptus) Mon, 26 Sep 2022 12:08:12 +0200 26 | 27 | monit-docker (0.0.46) unstable; urgency=medium 28 | 29 | * Reviewed requirements.txt. 30 | 31 | -- Adrien DELLE CAVE (Decryptus) Fri, 28 Jan 2022 01:43:29 +0100 32 | 33 | monit-docker (0.0.45) unstable; urgency=medium 34 | 35 | * Reviewed requirements.txt. 36 | 37 | -- Adrien DELLE CAVE (Decryptus) Fri, 21 Jan 2022 17:25:21 +0100 38 | 39 | monit-docker (0.0.44) unstable; urgency=medium 40 | 41 | * Reviewed requirements. 42 | 43 | -- Adrien DELLE CAVE (Decryptus) Fri, 21 Jan 2022 17:23:30 +0100 44 | 45 | monit-docker (0.0.43) unstable; urgency=medium 46 | 47 | * Fixed shebang. 48 | 49 | -- Adrien DELLE CAVE (Decryptus) Tue, 27 Jul 2021 18:44:03 +0200 50 | 51 | monit-docker (0.0.42) unstable; urgency=medium 52 | 53 | * Added cargo package in Dockerfile. 54 | 55 | -- Adrien DELLE CAVE (Decryptus) Thu, 22 Jul 2021 02:10:31 +0200 56 | 57 | monit-docker (0.0.41) unstable; urgency=medium 58 | 59 | * Added possibility to monitor pidfile. 60 | 61 | -- Adrien DELLE CAVE (Decryptus) Wed, 23 Jun 2021 12:49:47 +0200 62 | 63 | monit-docker (0.0.40) unstable; urgency=medium 64 | 65 | * Reviewed requirements. 66 | 67 | -- Adrien DELLE CAVE (Decryptus) Sat, 03 Apr 2021 21:08:06 +0200 68 | 69 | monit-docker (0.0.39) unstable; urgency=medium 70 | 71 | * Reviewed requirements. 72 | 73 | -- Adrien DELLE CAVE (Decryptus) Wed, 17 Mar 2021 15:52:00 +0100 74 | 75 | monit-docker (0.0.38) unstable; urgency=medium 76 | 77 | * Reviewed requirements. 78 | 79 | -- Adrien DELLE CAVE (Decryptus) Tue, 08 Dec 2020 22:54:19 +0100 80 | 81 | monit-docker (0.0.37) unstable; urgency=medium 82 | 83 | * Added curl-dev package in Dockerfile. 84 | 85 | -- Adrien DELLE CAVE (Decryptus) Mon, 14 Sep 2020 02:07:36 +0200 86 | 87 | monit-docker (0.0.36) unstable; urgency=medium 88 | 89 | * Added 'my' filter for variables in templates. 90 | 91 | -- Adrien DELLE CAVE (Decryptus) Mon, 14 Sep 2020 01:05:10 +0200 92 | 93 | monit-docker (0.0.35) unstable; urgency=medium 94 | 95 | * Reviewed requirements. 96 | 97 | -- Adrien DELLE CAVE (Decryptus) Mon, 08 Jun 2020 22:38:31 +0200 98 | 99 | monit-docker (0.0.34) unstable; urgency=medium 100 | 101 | * Reviewed requirements. 102 | 103 | -- Adrien DELLE CAVE (Decryptus) Thu, 19 Dec 2019 06:49:05 +0100 104 | 105 | monit-docker (0.0.33) unstable; urgency=medium 106 | 107 | * [RELEASE] version: 0.0.33. 108 | 109 | -- Adrien DELLE CAVE (Decryptus) Tue, 15 Oct 2019 21:40:33 +0200 110 | 111 | monit-docker (0.0.32) unstable; urgency=medium 112 | 113 | * [RELEASE] version: 0.0.32. 114 | 115 | -- Adrien DELLE CAVE (Decryptus) Mon, 16 Sep 2019 11:16:30 +0200 116 | 117 | monit-docker (0.0.31) unstable; urgency=medium 118 | 119 | * [RELEASE] version: 0.0.31. 120 | 121 | -- Adrien DELLE CAVE (Decryptus) Fri, 13 Sep 2019 20:48:13 +0200 122 | 123 | monit-docker (0.0.30) unstable; urgency=medium 124 | 125 | * [RELEASE] version: 0.0.30. 126 | 127 | -- Adrien DELLE CAVE (Decryptus) Sat, 07 Sep 2019 22:58:52 +0200 128 | 129 | monit-docker (0.0.29) unstable; urgency=medium 130 | 131 | * [RELEASE] version: 0.0.29. 132 | 133 | -- Adrien DELLE CAVE (Decryptus) Sat, 07 Sep 2019 22:50:48 +0200 134 | 135 | monit-docker (0.0.28) unstable; urgency=medium 136 | 137 | * [RELEASE] version: 0.0.28. 138 | * Changed license from GPLv2 to GPLv3. 139 | 140 | -- Adrien DELLE CAVE (Decryptus) Sat, 07 Sep 2019 22:41:13 +0200 141 | 142 | monit-docker (0.0.27) unstable; urgency=medium 143 | 144 | * Reviewed documentation. 145 | 146 | -- Adrien DELLE CAVE (Decryptus) Sat, 07 Sep 2019 12:31:31 +0200 147 | 148 | monit-docker (0.0.26) unstable; urgency=medium 149 | 150 | * Added license file. 151 | 152 | -- Adrien DELLE CAVE (Decryptus) Sun, 01 Sep 2019 20:49:57 +0200 153 | 154 | monit-docker (0.0.25) unstable; urgency=medium 155 | 156 | * Fixed python3 compatibility. 157 | 158 | -- Adrien DELLE CAVE (Decryptus) Sun, 01 Sep 2019 20:47:12 +0200 159 | 160 | monit-docker (0.0.24) unstable; urgency=medium 161 | 162 | * Fixed setup.py. 163 | 164 | -- Adrien DELLE CAVE (Decryptus) Sat, 31 Aug 2019 15:10:27 +0200 165 | 166 | monit-docker (0.0.23) unstable; urgency=medium 167 | 168 | * Reviewed README.md and fixed python3 compatibility. 169 | 170 | -- Adrien DELLE CAVE (Decryptus) Sat, 31 Aug 2019 14:52:05 +0200 171 | 172 | monit-docker (0.0.22) unstable; urgency=medium 173 | 174 | * Missing close on StringIO. 175 | 176 | -- Adrien DELLE CAVE (Decryptus) Mon, 26 Aug 2019 20:05:04 +0200 177 | 178 | monit-docker (0.0.21) unstable; urgency=medium 179 | 180 | * Reviewed README.md. 181 | 182 | -- Adrien DELLE CAVE (Decryptus) Mon, 19 Aug 2019 13:22:35 +0200 183 | 184 | monit-docker (0.0.20) unstable; urgency=medium 185 | 186 | * Reviewed exit codes and added status argument. 187 | 188 | -- Adrien DELLE CAVE (Decryptus) Mon, 19 Aug 2019 13:13:30 +0200 189 | 190 | monit-docker (0.0.19) unstable; urgency=medium 191 | 192 | * Reviewed README.md. 193 | 194 | -- Adrien DELLE CAVE (Decryptus) Mon, 12 Aug 2019 09:22:38 +0200 195 | 196 | monit-docker (0.0.18) unstable; urgency=medium 197 | 198 | * Reviewed README.md. 199 | 200 | -- Adrien DELLE CAVE (Decryptus) Sun, 11 Aug 2019 18:48:48 +0200 201 | 202 | monit-docker (0.0.17) unstable; urgency=medium 203 | 204 | * Missing an r prefix. 205 | 206 | -- Adrien DELLE CAVE (Decryptus) Sun, 11 Aug 2019 18:11:53 +0200 207 | 208 | monit-docker (0.0.16) unstable; urgency=medium 209 | 210 | * Allow to execute commands without condition. 211 | 212 | -- Adrien DELLE CAVE (Decryptus) Sun, 11 Aug 2019 18:03:29 +0200 213 | 214 | monit-docker (0.0.15) unstable; urgency=medium 215 | 216 | * Fixed README.md. 217 | 218 | -- Adrien DELLE CAVE (Decryptus) Wed, 07 Aug 2019 11:28:28 +0200 219 | 220 | monit-docker (0.0.14) unstable; urgency=medium 221 | 222 | * Added argument ctn-group. 223 | 224 | -- Adrien DELLE CAVE (Decryptus) Wed, 07 Aug 2019 10:32:51 +0200 225 | 226 | monit-docker (0.0.13) unstable; urgency=medium 227 | 228 | * Removed ansible package from requirements.txt. 229 | 230 | -- Adrien DELLE CAVE (Decryptus) Tue, 30 Jul 2019 17:08:29 +0200 231 | 232 | monit-docker (0.0.12) unstable; urgency=medium 233 | 234 | * Added commands docker remove and kill. 235 | 236 | -- Adrien DELLE CAVE (Decryptus) Sun, 28 Jul 2019 16:25:02 +0200 237 | 238 | monit-docker (0.0.11) unstable; urgency=medium 239 | 240 | * Reviewed Dockerfile. 241 | 242 | -- Adrien DELLE CAVE (Decryptus) Sun, 28 Jul 2019 15:34:14 +0200 243 | 244 | monit-docker (0.0.10) unstable; urgency=medium 245 | 246 | * Fixed cron examples and clean Dockerfile. 247 | 248 | -- Adrien DELLE CAVE (Decryptus) Sun, 28 Jul 2019 14:59:46 +0200 249 | 250 | monit-docker (0.0.9) unstable; urgency=medium 251 | 252 | * Reviewed docker-compose.yml cron examples. 253 | 254 | -- Adrien DELLE CAVE (Decryptus) Sun, 28 Jul 2019 14:48:06 +0200 255 | 256 | monit-docker (0.0.8) unstable; urgency=medium 257 | 258 | * Fixed command result. 259 | 260 | -- Adrien DELLE CAVE (Decryptus) Sun, 28 Jul 2019 14:44:34 +0200 261 | 262 | monit-docker (0.0.7) unstable; urgency=medium 263 | 264 | * Enabled logfile only if log directory exists. 265 | 266 | -- Adrien DELLE CAVE (Decryptus) Sun, 28 Jul 2019 10:59:09 +0200 267 | 268 | monit-docker (0.0.6) unstable; urgency=medium 269 | 270 | * Added units parsing for sub-command monit. 271 | * Fixed statistics for sub-command stats. 272 | 273 | -- Adrien DELLE CAVE (Decryptus) Thu, 18 Jul 2019 15:48:53 +0200 274 | 275 | monit-docker (0.0.5) unstable; urgency=medium 276 | 277 | * Fixed python3 compatibility. 278 | 279 | -- Adrien DELLE CAVE (Decryptus) Wed, 17 Jul 2019 16:46:07 +0200 280 | 281 | monit-docker (0.0.4) unstable; urgency=medium 282 | 283 | * Added aliases in command lines. 284 | 285 | -- Adrien DELLE CAVE (Decryptus) Wed, 17 Jul 2019 16:16:59 +0200 286 | 287 | monit-docker (0.0.3) unstable; urgency=medium 288 | 289 | * Added argumet --id. 290 | 291 | -- Adrien DELLE CAVE (Decryptus) Fri, 12 Jul 2019 13:29:54 +0200 292 | 293 | monit-docker (0.0.2) unstable; urgency=medium 294 | 295 | * Renamed monit argument exec-if in cmd-if. 296 | 297 | -- Adrien DELLE CAVE (Decryptus) Fri, 12 Jul 2019 03:03:11 +0200 298 | 299 | monit-docker (0.0.1) unstable; urgency=medium 300 | 301 | * First version package 302 | 303 | -- Adrien DELLE CAVE (Decryptus) Thu, 11 Jul 2019 17:40:04 +0200 304 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | 3 | LABEL maintainer="docker@doowan.net" 4 | 5 | RUN apk -Uuv add bash \ 6 | cargo \ 7 | curl-dev \ 8 | gcc \ 9 | libffi-dev \ 10 | musl-dev \ 11 | python3 \ 12 | python3-dev \ 13 | py3-pip && \ 14 | find /var/cache/apk/ -type f -delete 15 | 16 | RUN pip3 install monit-docker 17 | 18 | ADD docker-run.sh /run.sh 19 | 20 | CMD ["/run.sh"] 21 | -------------------------------------------------------------------------------- /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 | #!/usr/bin/make -f 2 | # -*- makefile -*- 3 | 4 | CHANGELOG_PATH ?= "$(CURDIR)/CHANGELOG" 5 | DCH_PATH ?= dch 6 | DPKG_PARSECHANGELOG_PATH ?= dpkg-parsechangelog 7 | EDITOR_PATH ?= vim 8 | FIND_PATH ?= find 9 | GIT_PATH ?= git 10 | GREP_PATH ?= grep 11 | J2_PATH ?= j2 12 | MAKE_PATH ?= make 13 | PYTHON2_PATH ?= python2 14 | PYTHON3_PATH ?= python3 15 | RM_PATH ?= rm 16 | SED_PATH ?= sed 17 | TWINE_PATH ?= twine 18 | 19 | export PROJECT_RELEASE=$(shell $(DPKG_PARSECHANGELOG_PATH) -S Version -l $(CHANGELOG_PATH)) 20 | export PROJECT_VERSION=$(shell $(DPKG_PARSECHANGELOG_PATH) -S Version -l $(CHANGELOG_PATH) | $(SED_PATH) -nre 's/^[^0-9]*(([0-9]+\.)*[0-9]+).*/\1/p') 21 | export PROJECT_GIT_RELEASE="$(shell echo -n "$(PROJECT_RELEASE)"| $(SED_PATH) 's/~/-/g')" 22 | export PROJECT_COPYRIGHT_YEAR=$(shell date +'%Y') 23 | 24 | changelog: 25 | EDITOR="$(EDITOR_PATH)" $(DCH_PATH) -i -D unstable --no-auto-nmu -m --changelog "$(CHANGELOG_PATH)" 26 | $(MAKE_PATH) release 27 | $(MAKE_PATH) version 28 | 29 | release: 30 | $(shell echo $(PROJECT_RELEASE) > "$(CURDIR)/RELEASE") 31 | 32 | version: 33 | $(shell echo $(PROJECT_VERSION) > "$(CURDIR)/VERSION") 34 | 35 | setup-config: 36 | $(MAKE_PATH) release 37 | $(MAKE_PATH) version 38 | $(J2_PATH) setup.yml.j2 -o setup.yml 39 | 40 | docs: setup-config 41 | cd docs && $(MAKE_PATH) html 42 | 43 | clean-docs: 44 | cd docs && $(MAKE_PATH) clean 45 | 46 | build-git-commit: 47 | $(DPKG_PARSECHANGELOG_PATH) -S Changes -l "$(CHANGELOG_PATH)"|\ 48 | $(GREP_PATH) '^\s\+\*'|\ 49 | $(SED_PATH) -e 's/^\s\+\*\s\(.\+\)$$/\1/'|\ 50 | $(GIT_PATH) commit -a -F - || true 51 | 52 | build-git-version: 53 | if [ -d "bin" ]; then \ 54 | $(FIND_PATH) bin/ -type f | while read file; \ 55 | do \ 56 | $(SED_PATH) -i -e "s/^\(__version__\s*=\s*\)['\"]\(.*\)['\"]/\1'${PROJECT_VERSION}'/" "$$file"; \ 57 | done \ 58 | fi ; 59 | 60 | push-git-version: 61 | $(GIT_PATH) push 62 | $(GIT_PATH) tag -a "v$(PROJECT_VERSION)" -m "version: $(PROJECT_VERSION)" 63 | $(GIT_PATH) push origin "v$(PROJECT_VERSION)" 64 | 65 | push-git-release: 66 | $(GIT_PATH) push 67 | $(GIT_PATH) tag -a "$(PROJECT_GIT_RELEASE)-release" -m "release: $(PROJECT_GIT_RELEASE)" 68 | $(GIT_PATH) push origin "$(PROJECT_GIT_RELEASE)-release" 69 | 70 | git-push: 71 | $(MAKE_PATH) changelog 72 | $(MAKE_PATH) setup-config 73 | $(MAKE_PATH) build-git-version 74 | $(MAKE_PATH) build-git-commit 75 | 76 | git-version: 77 | $(MAKE_PATH) git-push 78 | $(MAKE_PATH) push-git-version 79 | 80 | git-release: 81 | $(MAKE_PATH) git-push 82 | $(MAKE_PATH) push-git-release 83 | 84 | build-pip2: clean-pip 85 | $(PYTHON2_PATH) setup.py bdist_wheel 86 | 87 | build-pip3: clean-pip 88 | $(PYTHON3_PATH) setup.py bdist_wheel 89 | 90 | push-pip2: 91 | $(TWINE_PATH) upload dist/* 92 | 93 | push-pip3: 94 | $(TWINE_PATH) upload dist/* 95 | 96 | push-pip: 97 | $(MAKE_PATH) build-pip2 98 | $(MAKE_PATH) push-pip2 99 | $(MAKE_PATH) build-pip3 100 | $(MAKE_PATH) push-pip3 101 | 102 | clean-pip: 103 | $(RM_PATH) -rf build/ dist/ 104 | 105 | clean-python: 106 | $(FIND_PATH) -type f -name "*.pyc" -delete 107 | $(FIND_PATH) -type d -name __pycache__ -exec rm -rf '{}' + 108 | 109 | clean: clean-docs clean-pip clean-python 110 | 111 | .PHONY: changelog release version 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # monit-docker project 2 | 3 | [![PyPI pyversions](https://img.shields.io/pypi/pyversions/monit-docker.svg)](https://pypi.org/project/monit-docker/) 4 | [![PyPI version shields.io](https://img.shields.io/pypi/v/monit-docker.svg)](https://pypi.org/project/monit-docker/) 5 | [![Docker Cloud Build Status](https://img.shields.io/docker/cloud/build/decryptus/monit-docker)](https://hub.docker.com/r/decryptus/monit-docker) 6 | [![Documentation Status](https://readthedocs.org/projects/monit-docker/badge/?version=latest)](https://monit-docker.readthedocs.io/) 7 | 8 | monit-docker is a free and open-source, we develop it to monitor container status or resources 9 | and execute some commands inside containers or manage containers with dockerd, for example: 10 | - reload php-fpm if memory usage is too high 11 | - reload php-fpm if no free space in /dev/shm 12 | - restart container if status is not running 13 | - remove all containers 14 | 15 | ## Table of contents 16 | 1. [Quickstart](#quickstart) 17 | 2. [Installation](#installation) 18 | 3. [Environment variables](#environment_variables) 19 | 4. [Sub-command: monit](#sub-command_monit) 20 | 1. [Basic commands](#monit_basic_commands) 21 | 2. [Advanced commands](#monit_advanced_commands) 22 | 3. [Container informations with exit codes](#monit_container_informations) 23 | 4. [monit-docker with M/Monit](#monit_with_mmonit) 24 | 5. [Sub-command: stats](#sub-command_stats) 25 | 1. [Basic commands](#stats_basic_commands) 26 | 2. [Advanced commands](#stats_advanced_commands) 27 | 28 | ## Quickstart 29 | 30 | Using monit-docker in Docker with crond 31 | 32 | `docker-compose up -d` 33 | 34 | See [docker-compose.yml](docker-compose.yml) and MONIT\_DOCKER\_CRONS environment variable to configure commands. 35 | 36 | ## Installation 37 | 38 | `pip install monit-docker` 39 | 40 | ## Environment variables 41 | 42 | | Variable | Description | Default | 43 | |:---------------------------|:----------------------------|:--------| 44 | | `MONIT_DOCKER_CONFIG` | Configuration file contents
(e.g. `export MONIT_DOCKER_CONFIG="$(cat monit-docker.yml)"`) | | 45 | | `MONIT_DOCKER_CONFFILE` | Configuration file path | /etc/monit-docker/monit-docker.yml | 46 | | `MONIT_DOCKER_LOGFILE` | Log file path | /var/log/monit-docker/monit-docker.log | 47 | | `MONIT_DOCKER_RUNTIMEDIR` | Runtime directory path | /run/monit-docker | 48 | 49 | ## Sub-command: monit 50 | 51 | ### Basic commands 52 | 53 | Restart containers with name starts with foo if memory usage percentage > 60% or cpu usage percentage > 90%: 54 | 55 | `monit-docker --name 'foo*' monit --cmd-if 'mem_percent > 60 ? restart' --cmd-if 'cpu_percent > 90 ? restart'` 56 | 57 | Stop containers with name starts with bar or foo and if cpu usage percentage greater than 60% and less than 70%: 58 | 59 | `monit-docker --name 'bar*' --name 'foo*' monit --cmd-if '60 > cpu_percent < 70 ? stop'` 60 | 61 | Kill containers with name starts with bar and status equal to pause or running: 62 | 63 | `monit-docker --name 'bar*' monit --cmd-if 'status in (pause,running) ? kill'` 64 | 65 | You can also use status argument, for example, restart containers with status paused or exited: 66 | 67 | `monit-docker -s paused -s exited monit --cmd 'restart'` 68 | 69 | Generate containers pidfile: 70 | 71 | `monit-docker monit --rsc pid` 72 | 73 | Reload php-fpm in container with image name contains /php-fpm/ if memory usage greater than 100 MiB: 74 | 75 | `monit-docker --image '*/php-fpm/*' monit --cmd-if 'mem_usage > 100 MiB ? (kill -USR2 1)'` 76 | 77 | Reload php-fpm in container with image name contains /php-fpm/ if /dev/shm percentage usage greater than 80%: 78 | 79 | `monit-docker --image '*/php-fpm/*' monit --cmd '(bash -c "[ $(df /dev/shm | sed \"s/\%//;\$!d\" | awk \"{print \$5}\") -gt 80 ] && kill -USR2 1")'` 80 | 81 | ### Advanced commands with configuration file or environment variable MONIT\_DOCKER\_CONFIG 82 | 83 | ##### Run commands with aliases declared in configuration file (e.g.: [monit-docker.yml.example](etc/monit-docker/monit-docker.yml.example)): 84 | 85 | Restart container id 4c01db0b339c if condition alias @status\_not\_running is true: 86 | 87 | `monit-docker --id 4c01db0b339c monit --cmd-if '@status_not_running ? restart'` 88 | 89 | Execute commands alias @start\_pause containers with name starts with foo if condition alias @status\_not\_running is true: 90 | 91 | `monit-docker --name 'foo*' monit --cmd-if '@status_not_running ? @start_pause'` 92 | 93 | Remove force container group php if status is equal to running: 94 | 95 | `monit-docker --ctn-group php monit --cmd-if 'status == running ? @remove_force'` 96 | 97 | Restart containers group nodejs if memory usage percentage > 10% and cpu usage percentage > 60%: 98 | 99 | `monit-docker --ctn-group nodejs monit --cmd-if '@mem_gt_10pct_and_cpu_gt_60pct ? restart'` 100 | 101 | Remove force all containers: 102 | 103 | `monit-docker monit --cmd '@remove_force'` 104 | 105 | ### Container informations with exit codes 106 | 107 | ##### Container status 108 | 109 | Run command below to get status with exit code for container named foo\_php\_fpm: 110 | 111 | `monit-docker --name foo_php_fpm monit --rsc status` 112 | 113 | An error occurred if exit code is greater than 100. 114 | 115 | | Exit code | Description | 116 | |:----------|:------------| 117 | | 0 | Running | 118 | | 10 | Created | 119 | | 20 | Paused | 120 | | 30 | Restarting | 121 | | 40 | Removing | 122 | | 50 | Exited | 123 | | 60 | Dead | 124 | | 114 | Not found | 125 | 126 | ##### Container CPU usage percentage 127 | 128 | Run command below to get CPU usage percentage with exit code for container named foo\_php\_fpm: 129 | 130 | `monit-docker --name foo_php_fpm monit --rsc cpu_percent` 131 | 132 | An error occurred if exit code is greater than 100. 133 | 134 | ##### Container memory usage percentage 135 | 136 | Run command below to get memory usage percentage with exit code for container named foo\_php\_fpm: 137 | 138 | `monit-docker --name foo_php_fpm monit --rsc mem_percent` 139 | 140 | An error occurred if exit code is greater than 100. 141 | 142 | ### monit-docker with M/Monit 143 | 144 | We can also monitoring containers cpu\_percent and mem\_percent resources with [M/Monit](https://mmonit.com). 145 | 146 | ##### Configuration examples 147 | 148 | ``` 149 | check program docker.foo_php_fpm.status with path "/usr/bin/monit-docker --name foo_php_fpm monit --rsc status" 150 | group monit-docker 151 | if status = 114 for 2 cycles then alert # container not found 152 | if status != 0 for 2 cycles then exec "/usr/bin/monit-docker --name foo_php_fpm monit --cmd restart" # container not running 153 | 154 | check program docker.foo_php_fpm.cpu with path "/usr/bin/monit-docker -s running --name foo_php_fpm monit --rsc cpu_percent" 155 | group monit-docker 156 | if status > 100 for 2 cycles then alert 157 | if status > 70 for 2 cycles then alert 158 | if status > 80 for 4 cycles then exec "/usr/bin/monit-docker --name foo_php_fpm monit --cmd reload" 159 | 160 | check program docker.foo_php_fpm.mem with path "/usr/bin/monit-docker -s running --name foo_php_fpm monit --rsc mem_percent" 161 | group monit-docker 162 | if status > 100 for 2 cycles then alert 163 | if status > 70 for 2 cycles then alert 164 | if status > 80 for 4 cycles then exec "/usr/bin/monit-docker --name foo_php_fpm monit --cmd '(kill -USR2 1)'" 165 | 166 | check program docker.foo_php_fpm.pid with pidfile /run/monit-docker/foo_php_fpm.pid 167 | group monit-docker 168 | if changed pid then alert 169 | 170 | ``` 171 | 172 | ## Sub-command: stats 173 | 174 | ### Basic commands 175 | 176 | Get all resources statistics for all containers in json format: 177 | 178 | `monit-docker stats --output json` 179 | 180 | ```json 181 | { 182 | "flamboyant_chaplygin": { 183 | "status": "running", 184 | "mem_percent": 0.03, 185 | "net_tx": "0.0 B", 186 | "cpu_percent": 0, 187 | "mem_usage": "2.52 MiB", 188 | "io_read": "3.5 MB", 189 | "io_write": "0.0 B", 190 | "net_rx": "25.2 kB", 191 | "mem_limit": "7.27 GiB", 192 | "pid": "3943" 193 | } 194 | } 195 | { 196 | "practical_proskuriakova": { 197 | "status": "running", 198 | "mem_percent": 0.04, 199 | "net_tx": "0.0 B", 200 | "cpu_percent": 0, 201 | "mem_usage": "2.61 MiB", 202 | "io_read": "24.6 kB", 203 | "io_write": "0.0 B", 204 | "net_rx": "25.0 kB", 205 | "mem_limit": "7.27 GiB", 206 | "pid": "3990" 207 | } 208 | } 209 | ``` 210 | 211 | Get all resources statistics for all containers in text format: 212 | 213 | `monit-docker stats --output text` 214 | 215 | ``` 216 | flamboyant_chaplygin|mem_usage:2.52 MiB|mem_limit:7.27 GiB|mem_percent:0.03|cpu_percent:0.0|io_read:3.5 MB|io_write:0.0 B|net_tx:0.0 B|net_rx:43.5 kB|status:running 217 | practical_proskuriakova|mem_usage:2.61 MiB|mem_limit:7.27 GiB|mem_percent:0.04|cpu_percent:0.0|io_read:24.6 kB|io_write:0.0 B|net_tx:0.0 B|net_rx:43.3 kB|status:running 218 | ``` 219 | 220 | ### Advanced commands with configuration file or environment variable MONIT\_DOCKER\_CONFIG 221 | 222 | Get status and memory usage for group nodejs: 223 | 224 | `monit-docker --ctn-group nodejs stats --rsc status --rsc mem_usage` 225 | -------------------------------------------------------------------------------- /RELEASE: -------------------------------------------------------------------------------- 1 | 0.0.50 2 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 0.0.50 2 | -------------------------------------------------------------------------------- /bin/monit-docker: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2019-2022 Adrien Delle Cave 4 | # SPDX-License-Identifier: GPL-3.0-or-later 5 | """ 6 | monit-docker 7 | """ 8 | 9 | from __future__ import absolute_import 10 | 11 | __version__ = '0.0.50' 12 | 13 | import argparse 14 | import codecs 15 | import copy 16 | import fnmatch 17 | import itertools 18 | import json 19 | import os 20 | import re 21 | import sys 22 | 23 | from collections import OrderedDict 24 | 25 | import logging 26 | from logging.handlers import WatchedFileHandler 27 | 28 | import six 29 | 30 | try: 31 | from six.moves import cStringIO as StringIO 32 | except ImportError: 33 | from six import StringIO 34 | 35 | import docker 36 | from docker.errors import APIError, DockerException 37 | 38 | import bitmath 39 | 40 | from mako.template import Template 41 | 42 | from sonicprobe import helpers 43 | 44 | import yaml 45 | 46 | try: 47 | from yaml import CSafeLoader as YamlLoader, CSafeDumper as YamlDumper 48 | except ImportError: 49 | from yaml import SafeLoader as YamlLoader, SafeDumper as YamlDumper 50 | 51 | 52 | SYSLOG_NAME = "monit-docker" 53 | LOG = logging.getLogger(SYSLOG_NAME) 54 | 55 | DEFAULT_CONFFILE = "/etc/monit-docker/monit-docker.yml" 56 | DEFAULT_LOGFILE = "/var/log/monit-docker/monit-docker.log" 57 | DEFAULT_RUNTIMEDIR = "/run/monit-docker" 58 | 59 | MONIT_DOCKER_CONFIG = os.environ.get('MONIT_DOCKER_CONFIG') 60 | MONIT_DOCKER_CONFFILE = os.environ.get('MONIT_DOCKER_CONFFILE') or DEFAULT_CONFFILE 61 | MONIT_DOCKER_LOGFILE = os.environ.get('MONIT_DOCKER_LOGFILE') or DEFAULT_LOGFILE 62 | MONIT_DOCKER_RUNTIMEDIR = os.environ.get('MONIT_DOCKER_RUNTIMEDIR') or DEFAULT_RUNTIMEDIR 63 | 64 | _SUBCMDS = {} 65 | _TPL_IMPORTS = ('from os import environ as ENV', 66 | 'from sonicprobe.helpers import to_yaml as my') 67 | 68 | DOCKER_COMMANDS = ('start', 69 | 'stop', 70 | 'remove', 71 | 'reload', 72 | 'restart', 73 | 'kill', 74 | 'pause', 75 | 'unpause') 76 | 77 | RESOURCE_CHOICES = ('mem_usage', 78 | 'mem_limit', 79 | 'mem_percent', 80 | 'cpu_percent', 81 | 'io_read', 82 | 'io_write', 83 | 'net_tx', 84 | 'net_rx', 85 | 'status', 86 | 'pid') 87 | 88 | STATUS_RC = {'running': 0, 89 | 'created': 10, 90 | 'paused': 20, 91 | 'restarting': 30, 92 | 'removing': 40, 93 | 'exited': 50, 94 | 'dead': 60} 95 | 96 | DATATYPES = RESOURCE_CHOICES 97 | DATATYPES_BEFORE_RUN = ('pid', 98 | 'status',) 99 | 100 | PRE_COND_RE = (r'(?:\s*(?P[0-9]+(?:\.[0-9]+)?\s*(?P[a-zA-Z]+)?)\s+' + 101 | r'(?P[\!\<\>=]=|[\<\>])\s+)?\s*') 102 | DATATYPE_RE = r'(?P[a-z_]+)\s*' 103 | OP_RE = r'(?P[\!\<\>=]=|[\<\>]|\s+in\s+|\s+not in\s+)\s*' 104 | VALUE_RE = r'(?P(?:[0-9]+(?:\.[0-9]+)?\s*(?P[a-zA-Z]+)?|[a-z]+|\((?:[a-z]+\,?){1,64}\)))' 105 | CMD_RE = r'(?P[^@].{2,})' 106 | CMD_ALIAS_RE = r'@(?P[a-zA-Z][a-zA-Z0-9_\-\.]{0,64})' 107 | COND_ALIAS_RE = r'@(?P[a-zA-Z][a-zA-Z0-9_\-\.]{0,64})' 108 | 109 | COND_MATCH = re.compile(r'^' + PRE_COND_RE + DATATYPE_RE + OP_RE + VALUE_RE + r'\s*$').match 110 | 111 | CMD_MATCH = re.compile(r'^\s*' + CMD_RE + r'\s*$').match 112 | CTN_GRP_MATCH = re.compile(r'^(?Pid|image|name|label)\s*:\s*(?P.+)\s*$').match 113 | 114 | EXPR_MATCH = re.compile(r'^(?:(?:(?P' + PRE_COND_RE + DATATYPE_RE + OP_RE + VALUE_RE + r')\s*|' + 115 | r'\s*' + COND_ALIAS_RE + r')\s*' + 116 | r'\?)?\s*(?:' + CMD_ALIAS_RE + r'|' + CMD_RE + r')\s*$').match 117 | 118 | 119 | StatusLoopContinue = object() 120 | StatusLoopRunContinue = object() 121 | StatusLoopBreak = object() 122 | StatusFuncReturn = object() 123 | 124 | try: 125 | codecs.lookup_error('surrogateescape') 126 | HAS_SURROGATEESCAPE = True 127 | except LookupError: 128 | HAS_SURROGATEESCAPE = False 129 | 130 | _COMPOSED_ERROR_HANDLERS = frozenset((None, 'surrogate_or_replace', 131 | 'surrogate_or_strict', 132 | 'surrogate_then_replace')) 133 | 134 | 135 | def argv_parse_check(): 136 | """ 137 | Parse (and check a little) command line parameters 138 | """ 139 | parser = argparse.ArgumentParser() 140 | 141 | parser.add_argument("-c", 142 | dest = 'conffile', 143 | default = MONIT_DOCKER_CONFFILE, 144 | help = "Use configuration file instead of %(default)s") 145 | parser.add_argument("--client", 146 | dest = 'client', 147 | default = None, 148 | help = "choose client configuration") 149 | parser.add_argument("--client-from-env", 150 | action = 'store_true', 151 | dest = 'client_from_env', 152 | default = False, 153 | help = "load client configuration from environment variables") 154 | parser.add_argument("--ctn-group", 155 | action = 'append', 156 | dest = 'ctn_grp', 157 | default = [], 158 | help = "select container group from configuration file") 159 | parser.add_argument("--id", 160 | action = 'append', 161 | dest = 'id', 162 | default = [], 163 | help = "match containers by id") 164 | parser.add_argument("--image", 165 | action = 'append', 166 | dest = 'image', 167 | default = [], 168 | help = "match containers by image") 169 | parser.add_argument("--label", 170 | action = 'append', 171 | dest = 'label', 172 | default = [], 173 | help = "match containers by label") 174 | parser.add_argument("-s", 175 | action = 'append', 176 | dest = 'status', 177 | default = [], 178 | choices = list(STATUS_RC), 179 | help = "match containers by status") 180 | parser.add_argument("-l", 181 | dest = 'loglevel', 182 | default = 'info', # warning: see affectation under 183 | choices = ('critical', 'error', 'warning', 'info', 'debug'), 184 | help = ("emit traces with LOGLEVEL details, must be one")) 185 | parser.add_argument("--logfile", 186 | dest = 'logfile', 187 | default = MONIT_DOCKER_LOGFILE, 188 | help = "Use log file instead of %(default)s") 189 | parser.add_argument("--runtimedir", 190 | dest = 'runtimedir', 191 | default = MONIT_DOCKER_RUNTIMEDIR, 192 | help = "Use runtime directory instead of %(default)s") 193 | parser.add_argument("--name", 194 | action = 'append', 195 | dest = 'name', 196 | default = [], 197 | help = "match containers by name") 198 | 199 | subparsers = parser.add_subparsers(dest = 'subcommand', 200 | help = "choice sub-command") 201 | 202 | for subcmd in six.itervalues(_SUBCMDS): 203 | subcmd.load_subcmd_parser(subparsers) 204 | 205 | options, args = parser.parse_known_args() 206 | 207 | if args: 208 | parser.error("no argument is allowed - use option --help to get an help screen") 209 | 210 | options.loglevel = getattr(logging, options.loglevel.upper(), logging.INFO) 211 | 212 | if getattr(options, 'subcommand') \ 213 | and options.subcommand in _SUBCMDS: 214 | _SUBCMDS[options.subcommand].valid_subcmd_parser(parser, options) 215 | else: 216 | parser.error("too few arguments - use option --help to get an help screen") 217 | 218 | return options 219 | 220 | 221 | class MonitDockerExit(SystemExit): 222 | pass 223 | 224 | 225 | class MonitDockerDataTypeError(TypeError): 226 | pass 227 | 228 | 229 | class MonitDockerExprParserError(SyntaxError): 230 | pass 231 | 232 | 233 | class MonitDockerSubCmdAbstract(object): #pylint: disable=useless-object-inheritance 234 | _CTN_GRPS = {} 235 | 236 | def __init__(self, options): 237 | self.options = options 238 | self.config = {} 239 | self.client = None 240 | self._common_conf = {} 241 | self._config_dir = "" 242 | self._containers = {} 243 | self._subsets = {} 244 | 245 | self._reset_subsets() 246 | self.load_conf() 247 | self.load_client() 248 | self.has_subsets = self._load_subsets() 249 | 250 | @classmethod 251 | def load_subcmd_parser(cls, subparsers): #pylint: disable=unused-argument 252 | return 253 | 254 | @classmethod 255 | def valid_subcmd_parser(cls, parser, options): #pylint: disable=unused-argument 256 | return 257 | 258 | @staticmethod 259 | def _subset_pattern(pattern_str): 260 | if not pattern_str.startswith('~'): 261 | return re.compile(fnmatch.translate(pattern_str)).match 262 | 263 | return re.compile(pattern_str[1:]).match 264 | 265 | @staticmethod 266 | def _load_yaml(stream, loader = YamlLoader): 267 | return yaml.load(stream, Loader = loader) 268 | 269 | @staticmethod 270 | def _dump_yaml(stream, dumper = YamlDumper, default_flow_style = True): 271 | return yaml.dump(stream, Dumper = dumper, default_flow_style = default_flow_style) 272 | 273 | @staticmethod 274 | def _load_clients_conf_finalize(name, conf): #pylint: disable=unused-argument 275 | if conf.get('tls') \ 276 | and isinstance(conf['tls'], dict): 277 | conf['tls'] = docker.tls.TLSConfig(**conf['tls']) 278 | 279 | @staticmethod 280 | def _get_status_rc(status): 281 | status = status.lower() 282 | if status not in STATUS_RC: 283 | raise ValueError("unknown status: %r" % status) 284 | 285 | return STATUS_RC[status] 286 | 287 | def _write_pidfile(self, pid, container_name): 288 | if not self.options.runtimedir: 289 | LOG.warning("runtime directory not configured or doesn't exist") 290 | return 291 | 292 | helpers.file_w_tmp((str(pid) + '\n',), 293 | os.path.join(self.options.runtimedir, "%s.pid" % container_name)) 294 | 295 | def _reset_subsets(self): 296 | self._subsets = {'id': [], 297 | 'image': [], 298 | 'name': [], 299 | 'label': []} 300 | 301 | def _load_ctn_grp_conf_finalize(self, name, matches): 302 | r = {} 303 | 304 | for match in matches: 305 | m = CTN_GRP_MATCH(match) 306 | if not m: 307 | raise MonitDockerExprParserError("unable to parse container group match: %r" % match) 308 | 309 | subset = m.group('subset') 310 | pattern = m.group('pattern') 311 | 312 | if subset not in r: 313 | r[subset] = [] 314 | 315 | if subset == 'id' \ 316 | and len(pattern) == 12 \ 317 | and pattern.isalnum(): 318 | pattern += '*' 319 | 320 | r[subset].append(self._subset_pattern(pattern)) 321 | 322 | self._CTN_GRPS[name] = r 323 | 324 | def load_client(self): 325 | if self.options.client_from_env \ 326 | or not self.config \ 327 | or not self.config.get('clients'): 328 | if not os.environ.get('DOCKER_HOST'): 329 | os.environ['DOCKER_HOST'] = "unix:///var/run/docker.sock" 330 | self.client = docker.from_env() 331 | return 332 | 333 | if self.options.client: 334 | if self.options.client in self.config['clients']: 335 | client = self.config['clients'][self.options.client] 336 | else: 337 | LOG.error("unknown client: %r", self.options.client) 338 | raise MonitDockerExit(110) 339 | else: 340 | client = self.config['clients'][list(self.config['clients'])[0]] 341 | 342 | self.client = docker.DockerClient(**client['config']) 343 | 344 | def _import_conf_file(self, filepath, config_dir = None, xvars = None): 345 | if not xvars: 346 | xvars = {} 347 | 348 | if config_dir and not filepath.startswith(os.path.sep): 349 | filepath = os.path.join(config_dir, filepath) 350 | 351 | with open(filepath, 'r') as f: 352 | return self._load_yaml( 353 | Template(f.read(), 354 | imports = _TPL_IMPORTS).render(**xvars)) 355 | 356 | def _parse_import_file(self, conf, name, config_dir, xvars = None): 357 | r = OrderedDict() 358 | 359 | import_key = "@import_%s" % name 360 | 361 | if not conf.get(import_key): 362 | return r 363 | 364 | if isinstance(conf[import_key], six.string_types): 365 | c = [conf[import_key]] 366 | else: 367 | c = conf[import_key] 368 | 369 | for import_file in c: 370 | r.update( 371 | self._import_conf_file( 372 | import_file, 373 | config_dir, 374 | xvars)) 375 | 376 | return r 377 | 378 | def _render_conf_object(self, conf, xvars = None): 379 | if not xvars: 380 | xvars = {} 381 | 382 | return self._load_yaml( 383 | Template(self._dump_yaml(conf, default_flow_style = False), 384 | imports = _TPL_IMPORTS).render(**xvars)) 385 | 386 | def _load_conf_section(self, xtype, section, conf, finalizer = None, config_dir = None): 387 | r = OrderedDict() 388 | 389 | if not config_dir: 390 | config_dir = self._config_dir 391 | 392 | xvars = copy.deepcopy(self._common_conf) 393 | xvars.update(self._parse_import_file(conf, 'vars', config_dir, xvars)) 394 | 395 | r = self._parse_import_file(conf, xtype, config_dir, xvars) 396 | r.update(conf) 397 | 398 | for name, value in six.iteritems(copy.copy(r)): 399 | if name.startswith('@'): 400 | del r[name] 401 | continue 402 | 403 | c = copy.deepcopy(self._common_conf) 404 | c.update(copy.deepcopy(xvars)) 405 | c["%s_name" % xtype] = name 406 | c['vars'].update(copy.deepcopy(xvars['vars'])) 407 | c['vars'].update(self._parse_import_file(value, 'vars', config_dir, c)) 408 | 409 | if 'vars' in value: 410 | c['vars'].update(copy.deepcopy(value['vars'])) 411 | 412 | if name not in r: 413 | r[name] = {section: {}} 414 | 415 | if section in value: 416 | r[name][section] = self._render_conf_object(value[section], c) 417 | else: 418 | LOG.error("missing %s in %s: %r", section, xtype, name) 419 | raise MonitDockerExit(110) 420 | 421 | if finalizer: 422 | finalizer(name, r[name][section]) 423 | 424 | for x in ('vars', '@import_vars'): 425 | if x in r[name]: 426 | del r[name][x] 427 | 428 | return r 429 | 430 | def load_conf(self): 431 | if os.path.exists(self.options.conffile): 432 | self._config_dir = os.path.dirname(os.path.abspath(self.options.conffile)) 433 | 434 | with open(self.options.conffile, 'r') as f: 435 | conf = self._load_yaml(f) 436 | elif MONIT_DOCKER_CONFIG: 437 | c = StringIO(MONIT_DOCKER_CONFIG) 438 | conf = self._load_yaml(c.getvalue()) 439 | c.close() 440 | else: 441 | return {} 442 | 443 | self._common_conf = {'general': {}, 444 | 'vars': {}} 445 | 446 | if conf.get('general'): 447 | self._common_conf['general'] = dict(conf['general']) 448 | 449 | if conf.get('vars'): 450 | self._common_conf['vars'] = dict(conf['vars']) 451 | 452 | if conf.get('clients'): 453 | self.config['clients'] = self._load_conf_section('client', 454 | 'config', 455 | conf['clients'], 456 | finalizer = self._load_clients_conf_finalize) 457 | 458 | if conf.get('ctn-groups'): 459 | self.config['ctn-groups'] = self._load_conf_section('ctn-group', 460 | 'match', 461 | conf['ctn-groups'], 462 | finalizer = self._load_ctn_grp_conf_finalize) 463 | 464 | return conf 465 | 466 | def _load_subsets(self): 467 | r = False 468 | for subset_type, subset_patterns in six.iteritems(self._subsets): 469 | subset_opt = getattr(self.options, subset_type) 470 | if not subset_opt: 471 | continue 472 | 473 | r = True 474 | 475 | for search_pattern in self._split_search_pattern(subset_opt): 476 | if subset_type == 'id' \ 477 | and len(search_pattern) == 12 \ 478 | and search_pattern.isalnum(): 479 | search_pattern += '*' 480 | subset_patterns.append(self._subset_pattern(search_pattern)) 481 | 482 | return r 483 | 484 | def _match_containers(self, xall = False): 485 | r = OrderedDict() 486 | 487 | containers = self.client.containers.list(**{'all': xall}) 488 | 489 | if not containers: 490 | LOG.warning("no container found") 491 | return r 492 | 493 | for container in containers: 494 | if self.options.status \ 495 | and container.status not in self.options.status: 496 | continue 497 | 498 | if not self.has_subsets: 499 | r[container.id] = container 500 | continue 501 | 502 | matched = False 503 | for subset_type, patterns in six.iteritems(self._subsets): 504 | if not patterns: 505 | continue 506 | 507 | for pattern in patterns: 508 | if subset_type in ('id', 'name'): 509 | if pattern(getattr(container, subset_type)): 510 | matched = True 511 | r[container.id] = container 512 | break 513 | elif subset_type == 'label': 514 | for label in six.itervalues(container.labels): 515 | if pattern(label): 516 | matched = True 517 | r[container.id] = container 518 | break 519 | elif subset_type == 'image': 520 | for tag in container.image.tags: 521 | if pattern(tag): 522 | matched = True 523 | r[container.id] = container 524 | break 525 | if matched: 526 | break 527 | if matched: 528 | break 529 | 530 | return r 531 | 532 | def to_text(self, obj, encoding='utf-8', errors=None, nonstring='simplerepr'): 533 | """ function from project ansible: ansible/module_utils/_text.py """ 534 | 535 | if isinstance(obj, six.text_type): 536 | return obj 537 | 538 | if errors in _COMPOSED_ERROR_HANDLERS: 539 | if HAS_SURROGATEESCAPE: 540 | errors = 'surrogateescape' 541 | elif errors == 'surrogate_or_strict': 542 | errors = 'strict' 543 | else: 544 | errors = 'replace' 545 | 546 | if isinstance(obj, six.binary_type): 547 | # Note: We don't need special handling for surrogate_then_replace 548 | # because all bytes will either be made into surrogates or are valid 549 | # to decode. 550 | return obj.decode(encoding, errors) 551 | 552 | # Note: We do these last even though we have to call to_text again on the 553 | # value because we're optimizing the common case 554 | if nonstring == 'simplerepr': 555 | try: 556 | value = str(obj) 557 | except UnicodeError: 558 | try: 559 | value = repr(obj) 560 | except UnicodeError: 561 | # Giving up 562 | return u'' 563 | elif nonstring == 'passthru': 564 | return obj 565 | elif nonstring == 'empty': 566 | return u'' 567 | elif nonstring == 'strict': 568 | raise TypeError('obj must be a string type') 569 | else: 570 | raise TypeError('Invalid value %s for to_text\'s nonstring parameter' % nonstring) 571 | 572 | return self.to_text(value, encoding, errors) 573 | 574 | def _split_search_pattern(self, pattern): 575 | if isinstance(pattern, list): 576 | return list(itertools.chain(*map(self._split_search_pattern, pattern))) 577 | if not isinstance(pattern, six.string_types): 578 | pattern = self.to_text(pattern, errors='surrogate_or_strict') 579 | 580 | if u',' in pattern: 581 | patterns = pattern.split(u',') 582 | else: 583 | patterns = [pattern] 584 | 585 | return [p.strip() for p in patterns] 586 | 587 | def terminate(self): 588 | if self.client: 589 | self.client.api.close() 590 | 591 | 592 | class MonitDockerSubCmdStats(MonitDockerSubCmdAbstract): 593 | CMD_NAME = 'stats' 594 | CMD_HELP = "display stats information" 595 | 596 | @classmethod 597 | def load_subcmd_parser(cls, subparsers): 598 | parser = subparsers.add_parser(cls.CMD_NAME, 599 | help = cls.CMD_HELP) 600 | parser.add_argument("--output", 601 | dest = 'output', 602 | default = 'json', 603 | choices = ('text', 'json'), 604 | help = "formatting style for command output") 605 | parser.add_argument("--rsc", 606 | action = 'append', 607 | dest = 'resource', 608 | default = [], 609 | choices = RESOURCE_CHOICES, 610 | help = "resource information") 611 | 612 | @classmethod 613 | def valid_subcmd_parser(cls, parser, options): 614 | if not options.resource: 615 | options.resource = RESOURCE_CHOICES 616 | 617 | @staticmethod 618 | def _calc_cpu_percent(cur_stats, pre_stats): 619 | r = 0.0 620 | 621 | if not cur_stats.get('system_cpu_usage'): 622 | return r 623 | 624 | if not pre_stats or not pre_stats.get('system_cpu_usage'): 625 | return r 626 | 627 | if pre_stats: 628 | cpu_delta = float(cur_stats['cpu_usage']['total_usage']) - float(pre_stats['cpu_usage']['total_usage']) 629 | sys_delta = float(cur_stats['system_cpu_usage']) - float(pre_stats['system_cpu_usage']) 630 | else: 631 | cpu_delta = 0.0 632 | sys_delta = 0.0 633 | 634 | if cur_stats.get('online_cpus'): 635 | online_cpus = cur_stats['online_cpus'] 636 | elif cur_stats['cpu_usage'].get('percpu_usage'): 637 | online_cpus = len(cur_stats['cpu_usage']['percpu_usage']) 638 | else: 639 | LOG.warning("unable to get online cpus information") 640 | return r 641 | 642 | if cpu_delta > 0.0 and sys_delta > 0.0: 643 | r = (cpu_delta / sys_delta) * online_cpus * 100.0 644 | 645 | return round(r, 2) 646 | 647 | def _calc_mem_usage(self, data): 648 | usage = data.get('usage', 0) 649 | 650 | if data.get('stats') and 'total_cache' in data['stats']: 651 | usage -= data['stats']['total_cache'] 652 | 653 | if self.CMD_NAME == 'monit': 654 | return usage 655 | 656 | if usage < 1: 657 | usage = bitmath.Byte(usage) 658 | else: 659 | usage = bitmath.Byte(usage).best_prefix() 660 | 661 | return usage.format('{value:.2f} {unit}').replace('Byte', 'B') 662 | 663 | def _calc_mem_limit(self, data): 664 | limit = data.get('limit', 0) 665 | 666 | if self.CMD_NAME == 'monit': 667 | return limit 668 | 669 | if limit < 1: 670 | limit = bitmath.Byte(limit) 671 | else: 672 | limit = bitmath.Byte(limit).best_prefix() 673 | 674 | return limit.format('{value:.2f} {unit}').replace('Byte', 'B') 675 | 676 | @staticmethod 677 | def _calc_mem_percent(data): 678 | if not data.get('limit'): 679 | return 0.0 680 | 681 | usage = data.get('usage', 0) 682 | 683 | if data.get('stats') and 'total_cache' in data['stats']: 684 | usage -= data['stats']['total_cache'] 685 | 686 | return round(float(usage) / float(data['limit']) * 100.0, 2) 687 | 688 | def _calc_network(self, data): 689 | rx = 0 690 | tx = 0 691 | 692 | if data: 693 | for v in six.itervalues(data): 694 | rx += v['rx_bytes'] 695 | tx += v['tx_bytes'] 696 | 697 | if self.CMD_NAME == 'monit': 698 | return (rx, tx) 699 | 700 | if rx < 1: 701 | rx = bitmath.Byte(rx) 702 | else: 703 | rx = bitmath.Byte(rx).to_kB().best_prefix() 704 | 705 | if tx < 1: 706 | tx = bitmath.Byte(tx) 707 | else: 708 | tx = bitmath.Byte(tx).to_kB().best_prefix() 709 | 710 | return (rx.format('{value:.1f} {unit}').replace('Byte', 'B'), 711 | tx.format('{value:.1f} {unit}').replace('Byte', 'B')) 712 | 713 | def _calc_blockio(self, data): 714 | read = 0 715 | write = 0 716 | 717 | if data and data.get('io_service_bytes_recursive'): 718 | for x in data['io_service_bytes_recursive']: 719 | if x['op'] == 'Read': 720 | read += x['value'] 721 | elif x['op'] == 'Write': 722 | write += x['value'] 723 | 724 | if self.CMD_NAME == 'monit': 725 | return (read, write) 726 | 727 | if read < 1: 728 | read = bitmath.Byte(read) 729 | else: 730 | read = bitmath.Byte(read).to_kB().best_prefix() 731 | 732 | if write < 1: 733 | write = bitmath.Byte(write) 734 | else: 735 | write = bitmath.Byte(write).to_kB().best_prefix() 736 | 737 | return (read.format('{value:.1f} {unit}').replace('Byte', 'B'), 738 | write.format('{value:.1f} {unit}').replace('Byte', 'B')) 739 | 740 | def _get_resource_info(self, rsc, current, previous): 741 | if rsc == 'mem_usage': 742 | return self._calc_mem_usage(current['memory_stats']) 743 | if rsc == 'mem_limit': 744 | return self._calc_mem_limit(current['memory_stats']) 745 | if rsc == 'mem_percent': 746 | return self._calc_mem_percent(current['memory_stats']) 747 | if rsc == 'cpu_percent': 748 | return self._calc_cpu_percent(current['cpu_stats'], 749 | previous.get('cpu_stats')) 750 | if rsc == 'io_read': 751 | return self._calc_blockio(current.get('blkio_stats'))[0] 752 | if rsc == 'io_write': 753 | return self._calc_blockio(current.get('blkio_stats'))[1] 754 | if rsc == 'net_rx': 755 | return self._calc_network(current.get('networks'))[0] 756 | if rsc == 'net_tx': 757 | return self._calc_network(current.get('networks'))[1] 758 | 759 | LOG.error("resource unknown: %r", rsc) 760 | raise MonitDockerExit(112) 761 | 762 | def before_run(self, container): #pylint: disable=no-self-use 763 | if container['obj'].status not in ('paused', 'running'): 764 | return StatusLoopRunContinue 765 | 766 | return None 767 | 768 | def _output_text(self, container, data): 769 | r = ["%s" % container['name']] 770 | 771 | for rsc in self.options.resource: 772 | if rsc == 'pid': 773 | r.append("%s:%s" % (rsc, container['obj'].attrs['State'].get('Pid') or 'null')) 774 | elif rsc == 'status': 775 | r.append("%s:%s" % (rsc, container['obj'].status)) 776 | elif data: 777 | r.append("%s:%s" % (rsc, self._get_resource_info(rsc, data, container['stats']))) 778 | else: 779 | r.append("%s:%s" % (rsc, 'null')) 780 | 781 | sys.stdout.write('|'.join(r) + "\n") 782 | 783 | def _output_json(self, container, data): 784 | r = {container['name']: {}} 785 | 786 | for rsc in self.options.resource: 787 | if rsc == 'pid': 788 | r[container['name']][rsc] = container['obj'].attrs['State'].get('Pid') 789 | elif rsc == 'status': 790 | r[container['name']][rsc] = container['obj'].status 791 | elif data: 792 | r[container['name']][rsc] = self._get_resource_info(rsc, data, container['stats']) 793 | else: 794 | r[container['name']][rsc] = None 795 | 796 | sys.stdout.write(json.dumps(r) + "\n") 797 | 798 | def run(self, container, data): 799 | getattr(self, "_output_%s" % getattr(self.options, 'output', 'json'))(container, data) 800 | 801 | return StatusLoopBreak 802 | 803 | def __call__(self): 804 | if self.options.ctn_grp and self._CTN_GRPS: 805 | self._reset_subsets() 806 | 807 | for name in self.options.ctn_grp: 808 | if name not in self._CTN_GRPS: 809 | LOG.error("unable to find container group: %r", name) 810 | raise MonitDockerExit(110) 811 | 812 | for subset_type, patterns in six.iteritems(self._CTN_GRPS[name]): 813 | self.has_subsets = True 814 | self._subsets[subset_type].extend(patterns) 815 | 816 | containers = self._match_containers(xall = True) 817 | if not containers: 818 | LOG.warning("no container found") 819 | raise MonitDockerExit(114) 820 | 821 | for xid, obj in six.iteritems(containers): 822 | if xid not in self._containers: 823 | self._containers[xid] = {'obj': obj, 824 | 'id': xid, 825 | 'name': obj.name, 826 | 'stats': None} 827 | 828 | container = self._containers[xid] 829 | 830 | r = self.before_run(container) 831 | if r in (StatusLoopContinue, StatusLoopRunContinue): 832 | if r is StatusLoopRunContinue: 833 | self.run(container, {}) 834 | continue 835 | 836 | for line in container['obj'].stats(stream = True): 837 | data = json.loads(line) 838 | 839 | if not container['stats']: 840 | container['stats'] = data 841 | continue 842 | if data['read'] == container['stats']['read']: 843 | continue 844 | 845 | r = self.run(container, data) 846 | if r is StatusLoopBreak: 847 | break 848 | 849 | 850 | class MonitDockerSubCmdMonit(MonitDockerSubCmdStats): 851 | CMD_NAME = 'monit' 852 | CMD_HELP = "return stats information with return code" 853 | _COMMANDS = {} 854 | _CONDITIONS = {} 855 | _EXPRS = {} 856 | 857 | @classmethod 858 | def load_subcmd_parser(cls, subparsers): 859 | parser = subparsers.add_parser(cls.CMD_NAME, 860 | help = cls.CMD_HELP) 861 | parser.add_argument("--rsc", 862 | action = 'append', 863 | dest = 'resource', 864 | default = [], 865 | choices = RESOURCE_CHOICES, 866 | help = "resource information") 867 | parser.add_argument("--cmd", 868 | "--cmd-if", 869 | action = 'append', 870 | dest = 'cmd', 871 | default = [], 872 | help = "run docker command or execute command inside containers") 873 | 874 | @classmethod 875 | def valid_subcmd_parser(cls, parser, options): 876 | if options.resource and options.cmd: 877 | parser.error("rsc and cmd options can't be in the same command") 878 | 879 | setattr(options, 'output', 'text') 880 | 881 | def _load_conditions_conf_finalize(self, name, exprs): 882 | r = [] 883 | 884 | for expr in exprs: 885 | m = COND_MATCH(expr) 886 | if not m: 887 | raise MonitDockerExprParserError("unable to parse conditional expression: %r" % expr) 888 | 889 | m = m.groupdict() 890 | 891 | if m.get('pre_value_unit'): 892 | m['pre_value'] = bitmath.parse_string(m['pre_value']).bytes 893 | 894 | if m.get('value_unit'): 895 | m['value'] = bitmath.parse_string(m['value']).bytes 896 | 897 | r.append({'real': expr, 898 | 'parsed': m}) 899 | 900 | self._CONDITIONS[name] = r 901 | 902 | def _load_commands_conf_finalize(self, name, cmds): 903 | r = [] 904 | 905 | for cmd in cmds: 906 | xdict = {'args': [], 907 | 'kwargs': {}} 908 | if not isinstance(cmd, dict): 909 | c = cmd 910 | else: 911 | c = list(cmd)[0] 912 | if 'args' in cmd[c]: 913 | xdict['args'] = cmd[c]['args'] 914 | if 'kwargs' in cmd[c]: 915 | xdict['kwargs'] = cmd[c]['kwargs'] 916 | 917 | m = CMD_MATCH(c) 918 | if not m: 919 | raise MonitDockerExprParserError("unable to parse command expression: %r" % cmd) 920 | xdict['cmd'] = m.group('cmd') 921 | r.append(xdict) 922 | 923 | self._COMMANDS[name] = r 924 | 925 | def load_conf(self): 926 | conf = super(MonitDockerSubCmdMonit, self).load_conf() 927 | 928 | if conf.get('conditions'): 929 | self.config['conditions'] = self._load_conf_section('condition', 930 | 'expr', 931 | conf['conditions'], 932 | finalizer = self._load_conditions_conf_finalize) 933 | 934 | if conf.get('commands'): 935 | self.config['commands'] = self._load_conf_section('command', 936 | 'exec', 937 | conf['commands'], 938 | finalizer = self._load_commands_conf_finalize) 939 | 940 | def _parse_exprs(self, expr, datatypes): 941 | r = {'conditions': [], 942 | 'commands': []} 943 | 944 | if expr not in self._EXPRS: 945 | m = EXPR_MATCH(expr) 946 | if not m: 947 | raise MonitDockerExprParserError("unable to parse expression: %r" % expr) 948 | 949 | m = m.groupdict() 950 | 951 | if m.get('pre_value_unit'): 952 | m['pre_value'] = bitmath.parse_string(m['pre_value']).bytes 953 | 954 | if m.get('value_unit'): 955 | m['value'] = bitmath.parse_string(m['value']).bytes 956 | 957 | if m['cond_alias']: 958 | cond_alias = m['cond_alias'] 959 | if cond_alias not in self._CONDITIONS: 960 | LOG.error("unknown conditional expression alias: %r", cond_alias) 961 | raise MonitDockerExit(110) 962 | 963 | r['conditions'] = self._CONDITIONS[cond_alias] 964 | elif m['cond']: 965 | cond = dict(m) 966 | del cond['cmd'] 967 | r['conditions'] = [{'real': cond['cond'], 968 | 'parsed': cond}] 969 | 970 | if m['cmd_alias']: 971 | cmd_alias = m['cmd_alias'] 972 | if cmd_alias not in self._COMMANDS: 973 | LOG.error("unknown command alias: %r", cmd_alias) 974 | raise MonitDockerExit(110) 975 | 976 | r['commands'] = self._COMMANDS[cmd_alias] 977 | else: 978 | r['commands'] = [{'cmd': m['cmd'], 979 | 'args': [], 980 | 'kwargs': {}}] 981 | 982 | self._EXPRS[expr] = r 983 | else: 984 | r = self._EXPRS[expr] 985 | 986 | for cond in r['conditions']: 987 | if cond['parsed']['datatype'] not in datatypes: 988 | raise MonitDockerDataTypeError("invalid specified datatype: %r" % cond['parsed']['datatype']) 989 | 990 | return r 991 | 992 | @staticmethod 993 | def _run_exec(cmd, container, args = None, kwargs = None): 994 | if not args: 995 | args = [] 996 | 997 | if not kwargs: 998 | kwargs = {} 999 | 1000 | LOG.info("execute %r in %s", cmd, container['name']) 1001 | r = container['obj'].exec_run(cmd) 1002 | LOG.info("%r executed in %s: %r", cmd, container['name'], r) 1003 | 1004 | return True 1005 | 1006 | @staticmethod 1007 | def _run_docker_cmd(cmd, container, args = None, kwargs = None): 1008 | if not args: 1009 | args = [] 1010 | 1011 | if not kwargs: 1012 | kwargs = {} 1013 | 1014 | try: 1015 | LOG.info("execute %s on %s", cmd, container['name']) 1016 | getattr(container['obj'], cmd)(*args, **kwargs) 1017 | LOG.info("%s executed on %s", cmd, container['name']) 1018 | return True 1019 | except APIError as e: 1020 | LOG.error("unable to execute %s on %s. (error: %r)", cmd, container['name'], e) 1021 | 1022 | return False 1023 | 1024 | @staticmethod 1025 | def _condition_result(op, ret, val, enable_in = False): 1026 | if op == '==': 1027 | rs = ret == val 1028 | elif op == '!=': 1029 | rs = ret != val 1030 | elif op == '>=': 1031 | rs = ret >= val 1032 | elif op == '<=': 1033 | rs = ret <= val 1034 | elif op == '>': 1035 | rs = ret > val 1036 | elif op == '<': 1037 | rs = ret < val 1038 | elif op == 'in' and enable_in: 1039 | rs = ret in val 1040 | elif op == 'not in' and enable_in: 1041 | rs = ret not in val 1042 | else: 1043 | raise MonitDockerExprParserError("conditional operator unknown: %r" % op) 1044 | 1045 | return rs 1046 | 1047 | def _get_datatype_info(self, datatype, container, data): 1048 | if datatype == 'pid': 1049 | return container['obj'].attrs['State'].get('Pid') or '' 1050 | 1051 | if datatype == 'status': 1052 | return container['obj'].status 1053 | 1054 | return self._get_resource_info(datatype, data, container['stats']) 1055 | 1056 | def _eval_if(self, condition, container, data = None): 1057 | real_cond = condition['real'] 1058 | expr = condition['parsed'] 1059 | 1060 | datatype = expr['datatype'] 1061 | op = expr['op'].strip() 1062 | ret = self._get_datatype_info(datatype, container, data) 1063 | 1064 | pre_op = expr['pre_op'] 1065 | pre_val = expr['pre_value'] 1066 | 1067 | if op in ('in', 'not in'): 1068 | val = expr['value'] 1069 | if val.startswith('(') and val.endswith(')'): 1070 | val = val[1:-1].split(',') 1071 | else: 1072 | raise MonitDockerExprParserError("invalid value with %r for expression if: %r" % (op, real_cond)) 1073 | else: 1074 | try: 1075 | val = type(ret)(expr['value']) 1076 | except TypeError: 1077 | LOG.error("invalid value for expression if: %r", real_cond) 1078 | raise MonitDockerExit(110) 1079 | 1080 | if pre_val is not None: 1081 | try: 1082 | pre_val = type(ret)(pre_val) 1083 | except TypeError: 1084 | LOG.error("invalid pre value for expression if: %r", real_cond) 1085 | raise MonitDockerExit(110) 1086 | 1087 | if None not in (pre_op, pre_val): 1088 | return self._condition_result(pre_op, ret, pre_val) \ 1089 | and self._condition_result(op, ret, val) 1090 | 1091 | return self._condition_result(op, ret, val, enable_in = True) 1092 | 1093 | def _parse_cmd(self, condition, command): 1094 | cmd = command['cmd'].strip() 1095 | 1096 | if cmd.startswith('(') and cmd.endswith(')'): 1097 | cmd = cmd[1:-1] 1098 | if not cmd.strip(): 1099 | LOG.error("missing command to execute in expression: %r", condition) 1100 | raise MonitDockerExit(110) 1101 | return {'func': self._run_exec, 1102 | 'cmd': cmd, 1103 | 'args': [], 1104 | 'kwargs': {}} 1105 | if cmd in DOCKER_COMMANDS: 1106 | return {'func': self._run_docker_cmd, 1107 | 'cmd': cmd, 1108 | 'args': command['args'], 1109 | 'kwargs': command['kwargs']} 1110 | 1111 | LOG.error("invalid docker command: %r. (condition: %r)", cmd, condition) 1112 | raise MonitDockerExit(110) 1113 | 1114 | def _run_cmd(self, expr, container, datatypes, data = None): 1115 | exprs = self._parse_exprs(expr, datatypes) 1116 | cmds = [] 1117 | rs = True 1118 | r = [] 1119 | 1120 | for command in exprs['commands']: 1121 | cmds.append(self._parse_cmd(expr, command)) 1122 | 1123 | for cond in exprs['conditions']: 1124 | if not self._eval_if(cond, container, data): 1125 | rs = False 1126 | break 1127 | 1128 | LOG.debug("commands: %r, conditions: %r, result: %r", 1129 | exprs['commands'], 1130 | exprs['conditions'], 1131 | rs) 1132 | 1133 | if not rs: 1134 | return False 1135 | 1136 | for cmd in cmds: 1137 | r.append(cmd['func'](cmd = cmd['cmd'], 1138 | container = container, 1139 | args = cmd['args'], 1140 | kwargs = cmd['kwargs'])) 1141 | 1142 | return r 1143 | 1144 | def before_run(self, container): 1145 | if self.options.resource: 1146 | if len(self.options.resource) == 1: 1147 | if self.options.resource[0] == 'pid': 1148 | self._write_pidfile(container['obj'].attrs['State'].get('Pid') or '', 1149 | container['name']) 1150 | return StatusLoopRunContinue 1151 | if self.options.resource[0] == 'status': 1152 | raise MonitDockerExit(int(self._get_status_rc(container['obj'].status))) 1153 | 1154 | if container['obj'].status not in ('paused', 'running'): 1155 | return StatusLoopRunContinue 1156 | 1157 | return None 1158 | 1159 | cmds = list(self.options.cmd) 1160 | if cmds: 1161 | to_pop = [] 1162 | for i, expr in enumerate(cmds): 1163 | try: 1164 | self._run_cmd(expr, container, DATATYPES_BEFORE_RUN) 1165 | except MonitDockerExprParserError: 1166 | raise 1167 | except MonitDockerDataTypeError: 1168 | continue 1169 | except Exception as e: 1170 | LOG.debug(e) 1171 | 1172 | to_pop.append(i) 1173 | 1174 | for i in reversed(to_pop): 1175 | cmds.pop(i) 1176 | 1177 | if not cmds: 1178 | return StatusLoopContinue 1179 | 1180 | if container['obj'].status not in ('paused', 'running'): 1181 | return StatusLoopContinue 1182 | 1183 | return None 1184 | 1185 | def run(self, container, data): 1186 | if self.options.resource: 1187 | if len(self.options.resource) > 1 or not self.options.resource[0].endswith('_percent'): 1188 | return super(MonitDockerSubCmdMonit, self).run(container, data) 1189 | 1190 | rsc = self.options.resource[0] 1191 | 1192 | if data: 1193 | raise MonitDockerExit(int(self._get_resource_info(rsc, data, container['stats']))) 1194 | 1195 | LOG.error("no statistic for the container: %s", container['name']) 1196 | raise MonitDockerExit(115) 1197 | 1198 | if self.options.cmd: 1199 | for expr in self.options.cmd: 1200 | self._run_cmd(expr, container, DATATYPES, data) 1201 | 1202 | return StatusLoopBreak 1203 | 1204 | return super(MonitDockerSubCmdMonit, self).run(container, data) 1205 | 1206 | 1207 | _SUBCMDS['monit'] = MonitDockerSubCmdMonit 1208 | _SUBCMDS['stats'] = MonitDockerSubCmdStats 1209 | 1210 | 1211 | def main(options): 1212 | """ 1213 | Main function 1214 | """ 1215 | xformat = "%(levelname)s:%(asctime)-15s: %(message)s" 1216 | datefmt = '%Y-%m-%d %H:%M:%S' 1217 | logging.basicConfig(level = options.loglevel, 1218 | format = xformat, 1219 | datefmt = datefmt) 1220 | 1221 | if os.path.isdir(os.path.dirname(options.logfile)): 1222 | filehandler = WatchedFileHandler(options.logfile) 1223 | filehandler.setFormatter(logging.Formatter(xformat, 1224 | datefmt = datefmt)) 1225 | root_logger = logging.getLogger('') 1226 | root_logger.addHandler(filehandler) 1227 | 1228 | if options.runtimedir and not os.path.isdir(options.runtimedir): 1229 | try: 1230 | helpers.make_dirs(options.runtimedir) 1231 | except Exception: 1232 | LOG.warning("unable to create runtime directory: %r", options.runtimedir) 1233 | setattr(options, 'runtimedir', None) 1234 | 1235 | rc = 0 1236 | monit_docker = None 1237 | 1238 | try: 1239 | monit_docker = _SUBCMDS[options.subcommand](options) 1240 | monit_docker() 1241 | except APIError as e: 1242 | rc = 180 1243 | LOG.error(e.explanation) 1244 | except DockerException as e: 1245 | rc = 170 1246 | LOG.error(e) 1247 | except MonitDockerExit as e: 1248 | rc = e.code 1249 | except (SystemExit, KeyboardInterrupt): 1250 | rc = 255 1251 | except SyntaxError as e: 1252 | rc = 140 1253 | LOG.error(e) 1254 | except Exception as e: 1255 | rc = 150 1256 | LOG.exception(e) 1257 | finally: 1258 | if monit_docker: 1259 | monit_docker.terminate() 1260 | 1261 | return rc 1262 | 1263 | 1264 | if __name__ == '__main__': 1265 | sys.exit(main(argv_parse_check())) 1266 | -------------------------------------------------------------------------------- /debian/changelog: -------------------------------------------------------------------------------- 1 | ../CHANGELOG -------------------------------------------------------------------------------- /debian/compat: -------------------------------------------------------------------------------- 1 | 9 2 | -------------------------------------------------------------------------------- /debian/control: -------------------------------------------------------------------------------- 1 | Source: monit-docker 2 | Section: net 3 | Priority: optional 4 | Maintainer: DevOps Team Fjord Technologies 5 | Uploaders: DevOps Team Fjord Technologies 6 | Build-Depends: debhelper (>= 7), dh-python, lsb-release, python (>= 2.7~) | python2 (>= 2.7~) | python3 (>= 3.9~), python-setuptools (<< 44.1~) | python3-setuptools (>= 44.1~), python-yaml | python3-yaml, sed 7 | Standards-Version: 3.9.5 8 | X-Python-Version: >= 2.7 9 | X-Python3-Version: >= 3.9 10 | XS-Python-Version: >= 2.7 11 | XS-Python3-Version: >= 3.9 12 | Homepage: https://www.commandersact.com 13 | 14 | Package: monit-docker 15 | Architecture: all 16 | Homepage: https://www.commandersact.com 17 | Depends: ${misc:Depends}, python (>= 2.7~) | python2 (>= 2.7~) | python3 (>= 3.9~) 18 | Pre-Depends: python-dev (>= 2.7~) | python2-dev (>= 2.7~) | python3-dev (>= 3.9~), python-pip (<< 20.3~) | python3-pip (>= 20.3~), python-setuptools (<< 44.1~) | python3-setuptools (>= 44.1~) 19 | Description: Fjord Technologies monit-docker package 20 | -------------------------------------------------------------------------------- /debian/copyright: -------------------------------------------------------------------------------- 1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: monit-docker 3 | Upstream-Contact: Adrien Delle Cave 4 | 5 | Files: * 6 | Copyright: 2019-2022 Adrien Delle Cave 7 | License: GPL-3 8 | 9 | Files: debian/* 10 | Copyright: 2019-2022 Adrien Delle Cave 11 | License: GPL-3 12 | 13 | License: GPL-3 14 | This program is free software: you can redistribute it and/or modify 15 | it under the terms of the GNU General Public License as published by 16 | the Free Software Foundation, either version 3 of the License, or 17 | (at your option) any later version. 18 | . 19 | This program is distributed in the hope that it will be useful, 20 | but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 | GNU General Public License for more details. 23 | . 24 | You should have received a copy of the GNU General Public License 25 | along with this program. If not, see . 26 | . 27 | On Debian systems, the complete text of the GNU General 28 | Public License can be found in `/usr/share/common-licenses/GPL-3'. 29 | -------------------------------------------------------------------------------- /debian/dirs: -------------------------------------------------------------------------------- 1 | usr/share/monit-docker 2 | var/log/monit-docker 3 | -------------------------------------------------------------------------------- /debian/docs: -------------------------------------------------------------------------------- 1 | README.md 2 | -------------------------------------------------------------------------------- /debian/install: -------------------------------------------------------------------------------- 1 | bin/ usr/ 2 | etc/* etc/ 3 | requirements.txt usr/share/monit-docker 4 | setup.py usr/share/monit-docker 5 | VERSION usr/share/monit-docker 6 | -------------------------------------------------------------------------------- /debian/logrotate: -------------------------------------------------------------------------------- 1 | /var/log/monit-docker/*.log { 2 | daily 3 | missingok 4 | rotate 7 5 | compress 6 | delaycompress 7 | notifempty 8 | copytruncate 9 | create 640 root adm 10 | } 11 | -------------------------------------------------------------------------------- /debian/postinst: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e 4 | 5 | case "$1" in 6 | configure|reconfigure) 7 | case "`lsb_release -cs`" in 8 | wheezy) 9 | pip install -q -U -i https://pypi.python.org/simple/ pip==9.0.3 2>/dev/null 10 | hash -r 11 | pip install -q -i https://pypi.python.org/simple/ -r /usr/share/monit-docker/requirements.txt 2>/dev/null 12 | ;; 13 | jessie) 14 | pip install -q -U pip 15 | hash -r 16 | pip install -q -r /usr/share/monit-docker/requirements.txt 17 | ;; 18 | *) 19 | pip install -q -r /usr/share/monit-docker/requirements.txt 20 | ;; 21 | esac 22 | ;; 23 | 24 | abort-upgrade|abort-remove|abort-deconfigure) 25 | ;; 26 | 27 | *) 28 | echo "postinst called with unknown argument \`$1'" >&2 29 | exit 1 30 | ;; 31 | esac 32 | -------------------------------------------------------------------------------- /debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | # -*- makefile -*- 3 | 4 | include /usr/share/dpkg/pkg-info.mk 5 | 6 | # Uncomment this to turn on verbose mode. 7 | export DH_VERBOSE=1 8 | export DH_OPTIONS=-v 9 | export PYBUILD_VERBOSE=1 10 | 11 | export PYBUILD_NAME=monit-docker 12 | 13 | DISTRIB_VERSION=$(shell lsb_release -s -r | sed -nre 's/^[^0-9]*([0-9]+).*/\1/p') 14 | 15 | ifeq ($(shell test $(DISTRIB_VERSION) -lt 11; echo $$?),0) 16 | DH_WITH_PYTHON=python2 17 | export PYBUILD_DISABLE_python3=1 18 | else 19 | DH_WITH_PYTHON=python3 20 | export PYBUILD_DISABLE_python2=1 21 | endif 22 | 23 | %: 24 | dh $@ --with $(DH_WITH_PYTHON) --buildsystem=pybuild 25 | 26 | override_dh_auto_install: 27 | dh_auto_install 28 | $(shell echo "$(DEB_VERSION_UPSTREAM)" > $(CURDIR)/VERSION) 29 | 30 | override_dh_auto_clean: 31 | dh_auto_clean 32 | rm -f "$(CURDIR)/VERSION" 33 | find . -type d -name '*.egg-info' | xargs rm -rf 34 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.2' 2 | services: 3 | monit-docker: 4 | image: decryptus/monit-docker:latest 5 | container_name: monit-docker 6 | environment: 7 | MONIT_DOCKER_CRONS: | 8 | */2 * * * * monit-docker monit --cmd-if 'mem_usage > 200 MiB ? (kill -USR2 1)' 9 | */2 * * * * monit-docker monit --cmd-if 'status not in (pause,running) ? restart' 10 | */2 * * * * monit-docker monit --rsc pid 11 | volumes: 12 | - /var/run:/var/run:rw 13 | -------------------------------------------------------------------------------- /docker-run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CRONTABS_PATH="/var/spool/cron/crontabs" 4 | MONIT_DOCKER_ROOT="${MONIT_DOCKER_ROOT:-"/opt/monit-docker"}" 5 | MONIT_DOCKER_CONFFILE="${MONIT_DOCKER_CONFFILE:-"${MONIT_DOCKER_ROOT}/monit-docker.yml"}" 6 | 7 | mkdir -p "${MONIT_DOCKER_ROOT}" 8 | 9 | cd "${MONIT_DOCKER_ROOT}" 10 | 11 | if [[ ! -f "${MONIT_DOCKER_CONFFILE}" ]] && [[ ! -z "${MONIT_DOCKER_CONFIG}" ]]; 12 | then 13 | echo -e "${MONIT_DOCKER_CONFIG}" > "${MONIT_DOCKER_CONFFILE}" 14 | fi 15 | 16 | if [[ -f "${CRONTABS_PATH}/root" ]]; 17 | then 18 | if [[ ! -f "${MONIT_DOCKER_ROOT}/root-crontabs" ]]; 19 | then 20 | cp -a "${CRONTABS_PATH}/root" "${MONIT_DOCKER_ROOT}/root-crontabs" 21 | fi 22 | rm -f "${CRONTABS_PATH}/root" 23 | fi 24 | 25 | if [[ -f "${MONIT_DOCKER_ROOT}/root-crontabs" ]]; 26 | then 27 | cp -a "${MONIT_DOCKER_ROOT}/root-crontabs" "${CRONTABS_PATH}/root" 28 | fi 29 | 30 | [[ ! -z "${MONIT_DOCKER_CRONS}" ]] && echo -e "${MONIT_DOCKER_CRONS}\n" >> "${CRONTABS_PATH}/root" 31 | 32 | exec /usr/sbin/crond -f -L /dev/stdout -d 0 33 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SOURCEDIR = . 8 | BUILDDIR = _build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/_static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/decryptus/monit-docker/2800c54d5e7647b836c4e42e64e0be9f7813afc3/docs/_static/.gitkeep -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | # import os 16 | # import sys 17 | # sys.path.insert(0, os.path.abspath('.')) 18 | import os 19 | import yaml 20 | 21 | root_dir = os.path.abspath('..') 22 | setup_config = os.path.join(root_dir, 'setup.yml') 23 | setup_cfg = yaml.safe_load(open(setup_config, 'r').read()) 24 | 25 | # -- Project information ----------------------------------------------------- 26 | 27 | project = setup_cfg['name'] 28 | copyright = setup_cfg['copyright'] 29 | author = setup_cfg['author'] 30 | 31 | # The short X.Y version 32 | version = setup_cfg['version'] 33 | # The full version, including alpha/beta/rc tags 34 | release = setup_cfg['release'] 35 | 36 | 37 | # -- General configuration --------------------------------------------------- 38 | 39 | # If your documentation needs a minimal Sphinx version, state it here. 40 | # 41 | # needs_sphinx = '1.0' 42 | 43 | # Add any Sphinx extension module names here, as strings. They can be 44 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 45 | # ones. 46 | extensions = [ 47 | 'm2r2', 48 | 'sphinx.ext.autodoc', 49 | #'sphinx.ext.napoleon', 50 | ] 51 | 52 | # Add any paths that contain templates here, relative to this directory. 53 | templates_path = ['_templates'] 54 | 55 | # The suffix(es) of source filenames. 56 | # You can specify multiple suffix as a list of string: 57 | # 58 | source_suffix = ['.rst', '.md'] 59 | #source_suffix = '.md' 60 | 61 | # The master toctree document. 62 | master_doc = 'index' 63 | 64 | # The language for content autogenerated by Sphinx. Refer to documentation 65 | # for a list of supported languages. 66 | # 67 | # This is also used if you do content translation via gettext catalogs. 68 | # Usually you set "language" from the command line for these cases. 69 | language = None 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | # This pattern also affects html_static_path and html_extra_path. 74 | exclude_patterns = [u'_build', 'Thumbs.db', '.DS_Store'] 75 | 76 | # The name of the Pygments (syntax highlighting) style to use. 77 | pygments_style = None 78 | 79 | 80 | # -- Options for HTML output ------------------------------------------------- 81 | 82 | # The theme to use for HTML and HTML Help pages. See the documentation for 83 | # a list of builtin themes. 84 | # 85 | html_theme = 'alabaster' 86 | 87 | # Theme options are theme-specific and customize the look and feel of a theme 88 | # further. For a list of options available for each theme, see the 89 | # documentation. 90 | # 91 | # html_theme_options = {} 92 | 93 | # Add any paths that contain custom static files (such as style sheets) here, 94 | # relative to this directory. They are copied after the builtin static files, 95 | # so a file named "default.css" will overwrite the builtin "default.css". 96 | html_static_path = ['_static'] 97 | 98 | # Custom sidebar templates, must be a dictionary that maps document names 99 | # to template names. 100 | # 101 | # The default sidebars (for documents that don't match any pattern) are 102 | # defined by theme itself. Builtin themes are using these templates by 103 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 104 | # 'searchbox.html']``. 105 | # 106 | # html_sidebars = {} 107 | 108 | 109 | # -- Options for HTMLHelp output --------------------------------------------- 110 | 111 | # Output file base name for HTML help builder. 112 | htmlhelp_basename = 'monit-dockerdoc' 113 | 114 | 115 | # -- Options for LaTeX output ------------------------------------------------ 116 | 117 | latex_elements = { 118 | # The paper size ('letterpaper' or 'a4paper'). 119 | # 120 | # 'papersize': 'letterpaper', 121 | 122 | # The font size ('10pt', '11pt' or '12pt'). 123 | # 124 | # 'pointsize': '10pt', 125 | 126 | # Additional stuff for the LaTeX preamble. 127 | # 128 | # 'preamble': '', 129 | 130 | # Latex figure (float) alignment 131 | # 132 | # 'figure_align': 'htbp', 133 | } 134 | 135 | # Grouping the document tree into LaTeX files. List of tuples 136 | # (source start file, target name, title, 137 | # author, documentclass [howto, manual, or own class]). 138 | latex_documents = [ 139 | (master_doc, 'monit-docker.tex', u'monit-docker Documentation', 140 | u'Adrien Delle Cave', 'manual'), 141 | ] 142 | 143 | 144 | # -- Options for manual page output ------------------------------------------ 145 | 146 | # One entry per manual page. List of tuples 147 | # (source start file, name, description, authors, manual section). 148 | man_pages = [ 149 | (master_doc, 'monit-docker', u'monit-docker Documentation', 150 | [author], 1) 151 | ] 152 | 153 | 154 | # -- Options for Texinfo output ---------------------------------------------- 155 | 156 | # Grouping the document tree into Texinfo files. List of tuples 157 | # (source start file, target name, title, author, 158 | # dir menu entry, description, category) 159 | texinfo_documents = [ 160 | (master_doc, 'monit-docker', u'monit-docker Documentation', 161 | author, 'monit-docker', 'One line description of project.', 162 | 'Miscellaneous'), 163 | ] 164 | 165 | 166 | # -- Options for Epub output ------------------------------------------------- 167 | 168 | # Bibliographic Dublin Core info. 169 | epub_title = project 170 | 171 | # The unique identifier of the text. This can be a ISBN number 172 | # or the project homepage. 173 | # 174 | # epub_identifier = '' 175 | 176 | # A unique identification for the text. 177 | # 178 | # epub_uid = '' 179 | 180 | # A list of files that should not be packed into the epub file. 181 | epub_exclude_files = ['search.html'] 182 | 183 | # Napoleon settings 184 | #napoleon_google_docstring = True 185 | #napoleon_numpy_docstring = False 186 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | .. mdinclude:: ../README.md 2 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | m2r2 2 | PyYAML>=3.10 3 | -------------------------------------------------------------------------------- /etc/monit-docker/clients.yml.example: -------------------------------------------------------------------------------- 1 | local_unix: 2 | config: 3 | base_url: ${vars['base_url_unix'] | n,my} 4 | -------------------------------------------------------------------------------- /etc/monit-docker/foo_https.vars.yml.example: -------------------------------------------------------------------------------- 1 | tls_verify: false 2 | -------------------------------------------------------------------------------- /etc/monit-docker/monit-docker.yml.example: -------------------------------------------------------------------------------- 1 | vars: 2 | base_url_unix: unix:///var/run/docker.sock 3 | base_url_https: https://127.0.0.1:2376/ 4 | tls_verify: true 5 | clients: 6 | '@import_client': 7 | - clients.yml.example 8 | local_https: 9 | config: 10 | base_url: ${vars['base_url_https'] | n,my} 11 | tls: 12 | verify: ${vars.get('tls_verify', False) | n,my} 13 | foo_https: 14 | '@import_vars': foo_https.vars.yml.example 15 | config: 16 | base_url: ${vars['base_url_https'] | n,my} 17 | ctn-groups: 18 | php: 19 | match: 20 | - 'name:foo-php*' 21 | - 'image:*/php-fpm/*' 22 | - 'label:*php-fpm*' 23 | nodejs: 24 | match: 25 | - 'id:4c01db0b339c' 26 | - 'name:node*' 27 | conditions: 28 | mem_gt_10pct_and_cpu_gt_60pct: 29 | expr: 30 | - mem_percent > 10 31 | - cpu_percent > 60 32 | mem_usage_100MiB: 33 | expr: 34 | - mem_usage > 100 MiB 35 | status_not_running: 36 | expr: 37 | - status not in (pause,running) 38 | commands: 39 | start_pause: 40 | exec: 41 | - start 42 | - (echo 'foo' > /tmp/bar) 43 | - pause 44 | pause_restart: 45 | exec: 46 | - pause 47 | - restart 48 | remove_force: 49 | exec: 50 | - remove: 51 | kwargs: 52 | force: true 53 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cryptography>=3.2.1 2 | bitmath>=1.3.3.1 3 | docker>=2.7.0 4 | Mako 5 | pyOpenSSL>=20.0.0 6 | PyYAML>=3.10 7 | six>=1.13.0 8 | sonicprobe>=0.3.51 9 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | 4 | import os 5 | import yaml 6 | from setuptools import find_packages, setup 7 | 8 | current_dir = os.path.abspath(os.path.dirname(__file__)) 9 | requirements = [line.strip() for line in open(os.path.join(current_dir, 'requirements.txt'), 'r').readlines()] 10 | setup_config = os.path.join(current_dir, 'setup.yml') 11 | readme_file = os.path.join(current_dir, 'README.md') 12 | long_desc = None 13 | long_desc_content_type = None 14 | 15 | if os.path.isfile(setup_config): 16 | setup_cfg = yaml.safe_load(open(setup_config, 'r').read()) 17 | 18 | if os.path.isfile(readme_file): 19 | long_desc = open(readme_file, 'r').read() 20 | long_desc_content_type = 'text/markdown' 21 | 22 | setup( 23 | name = setup_cfg['name'], 24 | version = setup_cfg['version'], 25 | description = setup_cfg['description'], 26 | author = setup_cfg['author'], 27 | author_email = setup_cfg['author_email'], 28 | license = setup_cfg['license'], 29 | url = setup_cfg['url'], 30 | scripts = ['bin/monit-docker'], 31 | install_requires = requirements, 32 | python_requires = ', '.join(setup_cfg['python_requires']), 33 | classifiers = setup_cfg['classifiers'], 34 | long_description = long_desc, 35 | long_description_content_type = long_desc_content_type 36 | ) 37 | -------------------------------------------------------------------------------- /setup.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: monit-docker 3 | description: monit-docker 4 | author: Adrien Delle Cave 5 | author_email: pypi@doowan.net 6 | copyright: '2019-2023 Adrien Delle Cave' 7 | release: '0.0.50' 8 | version: '0.0.50' 9 | license: License GPL-3 10 | url: https://github.com/decryptus/monit-docker 11 | python_requires: 12 | - '>=2.7' 13 | - '!=3.0.*' 14 | - '!=3.1.*' 15 | - '!=3.2.*' 16 | - '!=3.3.*' 17 | - '!=3.4.*' 18 | classifiers: 19 | - 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)' 20 | - 'Natural Language :: English' 21 | - 'Operating System :: Unix' 22 | - 'Programming Language :: Python' 23 | - 'Programming Language :: Python :: 2' 24 | - 'Programming Language :: Python :: 2.7' 25 | - 'Programming Language :: Python :: 3' 26 | - 'Programming Language :: Python :: 3.5' 27 | - 'Programming Language :: Python :: 3.6' 28 | - 'Programming Language :: Python :: 3.7' 29 | - 'Topic :: System :: Monitoring' 30 | - 'Topic :: Terminals' 31 | - 'Topic :: Utilities' 32 | -------------------------------------------------------------------------------- /setup.yml.j2: -------------------------------------------------------------------------------- 1 | --- 2 | name: monit-docker 3 | description: monit-docker 4 | author: Adrien Delle Cave 5 | author_email: pypi@doowan.net 6 | copyright: '2019-{{ env('PROJECT_COPYRIGHT_YEAR') }} Adrien Delle Cave' 7 | release: '{{ env('PROJECT_RELEASE') }}' 8 | version: '{{ env('PROJECT_VERSION') }}' 9 | license: License GPL-3 10 | url: https://github.com/decryptus/monit-docker 11 | python_requires: 12 | - '>=2.7' 13 | - '!=3.0.*' 14 | - '!=3.1.*' 15 | - '!=3.2.*' 16 | - '!=3.3.*' 17 | - '!=3.4.*' 18 | classifiers: 19 | - 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)' 20 | - 'Natural Language :: English' 21 | - 'Operating System :: Unix' 22 | - 'Programming Language :: Python' 23 | - 'Programming Language :: Python :: 2' 24 | - 'Programming Language :: Python :: 2.7' 25 | - 'Programming Language :: Python :: 3' 26 | - 'Programming Language :: Python :: 3.5' 27 | - 'Programming Language :: Python :: 3.6' 28 | - 'Programming Language :: Python :: 3.7' 29 | - 'Topic :: System :: Monitoring' 30 | - 'Topic :: Terminals' 31 | - 'Topic :: Utilities' 32 | --------------------------------------------------------------------------------