├── .gitignore
├── .uptimerobot.yml
├── LICENSE
├── MANIFEST.in
├── README.rst
├── build.py
├── conf.py
├── index.rst
├── requirements.txt
├── setup.py
├── tests
├── data
│ ├── alert_contact.json
│ ├── delete_alert_contact.json
│ ├── delete_monitor.json
│ ├── edit_monitor.json
│ ├── get_alert_contacts.json
│ ├── get_monitors.json
│ ├── log.json
│ ├── monitor.json
│ ├── new_alert_contact.json
│ └── new_monitor.json
├── test_alert_contact.py
├── test_cli.py
├── test_client.py
├── test_log.py
└── test_monitor.py
├── uptimerobot.py
└── uptimerobot
├── .uptimerobot.yml
├── __init__.py
├── alert_contact.py
├── cli.py
├── client.py
├── log.py
└── monitor.py
/.gitignore:
--------------------------------------------------------------------------------
1 | dist/
2 | build/
3 | *.pyc
4 | __pycache__
5 | uptimerobot.egg-info
6 | doc/
--------------------------------------------------------------------------------
/.uptimerobot.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | # Default values to use on the command-line.
4 |
5 | api_key: u83441-30844a47d712331872e6ee18
6 |
7 | # get_monitors:
8 | # monitors: null # e.g ['012', 'my monitor', '1451']
9 | # show_alerts: False
10 | # show_log: False
11 | # log_alerts: False
12 | # log_timezone: False
13 | # uptime: null # e.g [1, 5, 10]
14 |
15 | # new_monitor:
16 | # type: 1 # http(s)
17 | # subtype: null
18 | # port: null
19 | # keyword_type: null
20 | # keyword: null
21 | # username: null
22 | # password: null
23 | # alerts: null # e.g. ['12315', 'my alert']
24 |
25 | # edit_monitor:
26 | # # Probably not a good idea to default any of these.
27 | # name: null
28 | # status: null
29 | # url: null
30 | # type: null
31 | # subtype: null
32 | # port: null
33 | # keyword_type: null
34 | # keyword: null
35 | # username: null
36 | # password: null
37 | # alerts: null # e.g. ['12315', 'my alert']
38 |
39 | # get_alerts:
40 | # alerts: null # e.g. ['12315', 'my alert']
41 |
42 | # new_alert:
43 | # type: 2 # Default to email
44 |
45 |
46 |
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include LICENSE
2 | include README.rst
3 | include uptimerobot/*.yml
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | UptimeRobot client
2 | ==================
3 |
4 | A module (with command line application) to access uptimetobot.com API.
5 |
6 | Author: Bil Bas (bil.bas.dev@gmail.com)
7 |
8 | License: GPLv3
9 |
10 | Tested on Python 2.7 and 3.3.
11 |
12 |
13 | Installation
14 | ------------
15 |
16 | $ pip install uptimerobot
17 |
18 |
19 | Usage
20 | -----
21 |
22 | The command line application
23 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24 |
25 | The CLI application will take default values from ./.uptimerobot.yml and/or ~/.uptimerobot.yml (at the least, the api_key needs to be defined in one of these)::
26 |
27 | $ uptimerobot -h
28 |
29 | usage: uptimerobot [-h] SUBCOMMAND [OPTION, ...]
30 |
31 | Manage monitors and alert contacts at UptimeRobot.com
32 |
33 | If files exist, application will take defaults from:
34 | ./.uptimerobot.yml
35 | ~/.uptimerobot.yml
36 |
37 | optional arguments:
38 | -h, --help show this help message and exit
39 |
40 | Subcommands:
41 | get-monitors Get information about some or all monitors
42 | new-monitor Create a new monitor
43 | edit-monitor Edit an existing monitor
44 | delete-monitor Delete a monitor
45 | get-alerts Get information about some or all alert contacts
46 | new-alert Create a new alert contact
47 | delete-alert Delete an alert contact
48 |
49 |
50 | The Python module
51 | ~~~~~~~~~~~~~~~~~
52 |
53 | Users can use the API directly, via the uptimerobot Client class::
54 |
55 | from uptimerobot import Client
56 |
57 | client = Client("my_api_key")
58 |
59 | monitors = client.get_monitors(ids=[123123, 775643],
60 | show_logs=True,
61 | show_alert_contacts=True)
62 |
63 | for monitor in monitors:
64 | print(monitor.name)
65 | print(monitor.status_str)
66 |
67 | for alert_contact in monitor.alert_contacts:
68 | print(alert_contact.type_str)
69 | print(alert_contact.value)
70 |
71 | for log in monitor.logs:
72 | print(log.datetime)
--------------------------------------------------------------------------------
/build.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from __future__ import absolute_import, division, print_function, unicode_literals
4 |
5 | from os import system
6 | from sys import stderr
7 |
8 | from argparse import ArgumentParser
9 |
10 | USAGE = "build.py [-h] ACTION"
11 |
12 | parser = ArgumentParser(description="Manage building docs and release package",
13 | usage=USAGE)
14 |
15 | parser.add_argument('command', metavar='ACTION', type=str,
16 | help='Build either "docs" or "release"')
17 |
18 | opts = parser.parse_args()
19 |
20 | if opts.command == "docs":
21 | # Generate documentation.
22 | system("sphinx-apidoc -o doc uptimerobot")
23 | system("python setup.py build_sphinx")
24 | print()
25 | print("HTML documentation generated: build/sphinx/html/index.html")
26 | elif opts.command == "release":
27 | # Create source distribution.
28 | result = system("python setup.py sdist")
29 |
30 | if result == 0:
31 | print()
32 | print("Distribution package created in dist/")
33 | else:
34 | print('Invalid action (must be "docs" or "release")', file=stderr)
35 | print("usage: %s" % USAGE, file=stderr)
36 | exit(1)
37 |
38 |
--------------------------------------------------------------------------------
/conf.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # X937 documentation build configuration file, created by
5 | # sphinx-quickstart on Sun Apr 28 08:18:41 2013.
6 | #
7 | # This file is execfile()d with the current directory set to its containing dir.
8 | #
9 | # Note that not all possible configuration values are present in this
10 | # autogenerated file.
11 | #
12 | # All configuration values have a default; values that are commented out
13 | # serve to show the default.
14 |
15 | from __future__ import absolute_import, division, print_function, unicode_literals
16 |
17 | import sys, os
18 |
19 | # If extensions (or modules to document with autodoc) are in another directory,
20 | # add these directories to sys.path here. If the directory is relative to the
21 | # documentation root, use os.path.abspath to make it absolute, like shown here.
22 | sys.path.insert(0, os.path.abspath('.'))
23 |
24 | # -- General configuration -----------------------------------------------------
25 |
26 | # If your documentation needs a minimal Sphinx version, state it here.
27 | #needs_sphinx = '1.0'
28 |
29 | # Add any Sphinx extension module names here, as strings. They can be extensions
30 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
31 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
32 |
33 | # Add any paths that contain templates here, relative to this directory.
34 | #templates_path = ['_templates']
35 |
36 | # The suffix of source filenames.
37 | source_suffix = '.rst'
38 |
39 | # The encoding of source files.
40 | #source_encoding = 'utf-8-sig'
41 |
42 | # The master toctree document.
43 | master_doc = 'index'
44 |
45 | # General information about the project.
46 | project = 'uptimerobot'
47 | copyright = '2013, Bil Bas'
48 |
49 | # The version info for the project you're documenting, acts as replacement for
50 | # |version| and |release|, also used in various other places throughout the
51 | # built documents.
52 | #
53 | # The short X.Y version.
54 | version = '1.0.1'
55 | # The full version, including alpha/beta/rc tags.
56 | release = '1.0.1'
57 |
58 | # The language for content autogenerated by Sphinx. Refer to documentation
59 | # for a list of supported languages.
60 | #language = None
61 |
62 | # There are two options for replacing |today|: either, you set today to some
63 | # non-false value, then it is used:
64 | #today = ''
65 | # Else, today_fmt is used as the format for a strftime call.
66 | #today_fmt = '%B %d, %Y'
67 |
68 | # List of patterns, relative to source directory, that match files and
69 | # directories to ignore when looking for source files.
70 | exclude_patterns = ['_build', 'README.rst']
71 |
72 | # The reST default role (used for this markup: `text`) to use for all documents.
73 | #default_role = None
74 |
75 | # If true, '()' will be appended to :func: etc. cross-reference text.
76 | #add_function_parentheses = True
77 |
78 | # If true, the current module name will be prepended to all description
79 | # unit titles (such as .. function::).
80 | add_module_names = True
81 |
82 | # If true, sectionauthor and moduleauthor directives will be shown in the
83 | # output. They are ignored by default.
84 | #show_authors = False
85 |
86 | # The name of the Pygments (syntax highlighting) style to use.
87 | pygments_style = 'sphinx'
88 |
89 | # A list of ignored prefixes for module index sorting.
90 | #modindex_common_prefix = []
91 |
92 | # If true, keep warnings as "system message" paragraphs in the built documents.
93 | #keep_warnings = False
94 |
95 |
96 | # -- Options for HTML output ---------------------------------------------------
97 |
98 | # The theme to use for HTML and HTML Help pages. See the documentation for
99 | # a list of builtin themes.
100 | html_theme = 'default'
101 |
102 | # Theme options are theme-specific and customize the look and feel of a theme
103 | # further. For a list of options available for each theme, see the
104 | # documentation.
105 | #html_theme_options = {}
106 |
107 | # Add any paths that contain custom themes here, relative to this directory.
108 | #html_theme_path = []
109 |
110 | # The name for this set of Sphinx documents. If None, it defaults to
111 | # " v documentation".
112 | #html_title = None
113 |
114 | # A shorter title for the navigation bar. Default is the same as html_title.
115 | #html_short_title = None
116 |
117 | # The name of an image file (relative to this directory) to place at the top
118 | # of the sidebar.
119 | #html_logo = None
120 |
121 | # The name of an image file (within the static path) to use as favicon of the
122 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
123 | # pixels large.
124 | #html_favicon = None
125 |
126 | # Add any paths that contain custom static files (such as style sheets) here,
127 | # relative to this directory. They are copied after the builtin static files,
128 | # so a file named "default.css" will overwrite the builtin "default.css".
129 | #html_static_path = ['_static']
130 |
131 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
132 | # using the given strftime format.
133 | #html_last_updated_fmt = '%b %d, %Y'
134 |
135 | # If true, SmartyPants will be used to convert quotes and dashes to
136 | # typographically correct entities.
137 | #html_use_smartypants = True
138 |
139 | # Custom sidebar templates, maps document names to template names.
140 | #html_sidebars = {}
141 |
142 | # Additional templates that should be rendered to pages, maps page names to
143 | # template names.
144 | #html_additional_pages = {}
145 |
146 | # If false, no module index is generated.
147 | #html_domain_indices = True
148 |
149 | # If false, no index is generated.
150 | #html_use_index = True
151 |
152 | # If true, the index is split into individual pages for each letter.
153 | #html_split_index = False
154 |
155 | # If true, links to the reST sources are added to the pages.
156 | #html_show_sourcelink = True
157 |
158 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
159 | #html_show_sphinx = True
160 |
161 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
162 | #html_show_copyright = True
163 |
164 | # If true, an OpenSearch description file will be output, and all pages will
165 | # contain a tag referring to it. The value of this option must be the
166 | # base URL from which the finished HTML is served.
167 | #html_use_opensearch = ''
168 |
169 | # This is the file name suffix for HTML files (e.g. ".xhtml").
170 | #html_file_suffix = None
171 |
172 | # Output file base name for HTML help builder.
173 | htmlhelp_basename = 'X937doc'
174 |
175 | file_insertion_enabled = True
176 |
177 |
--------------------------------------------------------------------------------
/index.rst:
--------------------------------------------------------------------------------
1 | .. X937 documentation master file, created by
2 | sphinx-quickstart on Sun Apr 28 08:18:41 2013.
3 |
4 | Welcome to UptimeRobot's documentation!
5 | =======================================
6 |
7 | .. toctree::
8 | :maxdepth: 3
9 |
10 | doc/modules
11 |
12 | .. include:: README.rst
13 |
14 |
15 | Indices and tables
16 | ==================
17 |
18 | * :ref:`genindex`
19 | * :ref:`modindex`
20 | * :ref:`search`
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install -r requirements.txt
2 |
3 | requests==1.2.0
4 | pyyaml==3.10
5 | termcolor==1.1.0
6 |
7 | # Testing
8 | pytest==2.3.4
9 | flexmock==0.9.6
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Doesn't like Python3 stuff, so don't include this.
4 | #from __future__ import absolute_import, division, print_function, unicode_literals
5 |
6 | from setuptools import setup, find_packages
7 |
8 | setup(
9 | name = "uptimerobot",
10 | version = "1.0.1",
11 | url = "https:/github.com/spooner",
12 | description = "A module (with command line application) to access uptimetobot.com API",
13 | author = "Bil Bas",
14 | author_email = "bil.bas.dev@gmail.com",
15 | maintainer = "Arne Schirmacher",
16 | #maintainer_email = "",
17 | #url= "",
18 | license = "GNU General Public License v3 (GPLv3)",
19 | install_requires = [
20 | "requests>=1.2.0",
21 | "pyyaml>=3.10",
22 | "termcolor>=1.1.0",
23 | ],
24 | packages = find_packages(),
25 | package_data = {
26 | 'uptimerobot': [".uptimerobot.yml"],
27 | },
28 | entry_points = {
29 | 'console_scripts': [
30 | 'uptimerobot = uptimerobot.cli:main',
31 | ],
32 | },
33 | #include_package_data=True,
34 | zip_safe=True,
35 | classifiers=[
36 | 'Development Status :: 4 - Beta',
37 | #'Development Status :: 5 - Production/Stable',
38 | 'Environment :: Console',
39 | 'Intended Audience :: Developers',
40 | 'Intended Audience :: System Administrators',
41 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
42 | 'Operating System :: MacOS :: MacOS X',
43 | 'Operating System :: Microsoft :: Windows',
44 | 'Operating System :: POSIX',
45 | 'Programming Language :: Python',
46 | 'Topic :: System :: Networking :: Monitoring',
47 | ],
48 | )
--------------------------------------------------------------------------------
/tests/data/alert_contact.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "236",
3 | "value": "uptime@webresourcesdepot.com",
4 | "type": "2",
5 | "status": "2"
6 | }
--------------------------------------------------------------------------------
/tests/data/delete_alert_contact.json:
--------------------------------------------------------------------------------
1 | {
2 | "stat": "ok",
3 | "alertcontact": {
4 | "id": "236"
5 | }
6 | }
--------------------------------------------------------------------------------
/tests/data/delete_monitor.json:
--------------------------------------------------------------------------------
1 | {
2 | "stat": "ok",
3 | "monitor":{
4 | "id":"128798"
5 | }
6 | }
--------------------------------------------------------------------------------
/tests/data/edit_monitor.json:
--------------------------------------------------------------------------------
1 | {
2 | "stat": "ok",
3 | "monitor":{
4 | "id":"128798"
5 | }
6 | }
--------------------------------------------------------------------------------
/tests/data/get_alert_contacts.json:
--------------------------------------------------------------------------------
1 | {
2 | "stat": "ok",
3 | "alertcontacts": {
4 | "alertcontact": [
5 | {
6 | "id": "236",
7 | "value": "uptime@webresourcesdepot.com",
8 | "type": "2",
9 | "status": "2"
10 | },
11 | {
12 | "id": "237",
13 | "value": "uptime@webresourcesdepot.com",
14 | "type": "3",
15 | "status": "2"
16 | }
17 | ]
18 | }
19 | }
--------------------------------------------------------------------------------
/tests/data/get_monitors.json:
--------------------------------------------------------------------------------
1 | {
2 | "stat": "ok",
3 | "monitors": {
4 | "monitor": [
5 | {
6 | "id": "128795",
7 | "friendlyname": "Yahoo",
8 | "url": "http://www.yahoo.com/",
9 | "type": "1",
10 | "subtype": "",
11 | "keywordtype": "0",
12 | "keywordvalue": "",
13 | "httpusername": "",
14 | "httppassword": "",
15 | "port": "",
16 | "status": "2",
17 | "alltimeuptimeratio": "99.98",
18 | "customuptimeratio": "100.00",
19 | "alertcontact": [
20 | {
21 | "id": "4631",
22 | "type": "2",
23 | "value": "uptime@webresourcesdepot.com"
24 | },
25 | {
26 | "id": "2420",
27 | "type": "3",
28 | "value": "umutm"
29 | }
30 | ],
31 | "log": [
32 | {
33 | "type": "2",
34 | "datetime": "09/25/2011 16:12:44",
35 | "alertcontact": [
36 | {
37 | "type": "0",
38 | "value": "uptime@webresourcesdepot.com"
39 | },
40 | {
41 | "type": "3",
42 | "value": "umutm"
43 | }
44 | ]
45 | },
46 | {
47 | "type": "1",
48 | "datetime": "09/25/2011 16:11:44",
49 | "alertcontact": [
50 | {
51 | "type": "0",
52 | "value": "uptime@webresourcesdepot.com"
53 | },
54 | {
55 | "type": "3",
56 | "value": "umutm"
57 | }
58 | ]
59 | }
60 | ]
61 | },
62 | {
63 | "id": "128796",
64 | "friendlyname": "WebResourcesDepot",
65 | "url": "http://www.webresourcesdepot.com/",
66 | "type": "1",
67 | "subtype": "",
68 | "keywordtype": "0",
69 | "keywordvalue": "",
70 | "httpusername": "",
71 | "httppassword": "",
72 | "port": "",
73 | "status": "2",
74 | "alltimeuptimeratio": "99.94",
75 | "customtimeuptimeratio": "89.51",
76 | "alertcontact": [
77 | {
78 | "id": "2420",
79 | "type": "3",
80 | "value": "umutm"
81 | }
82 | ],
83 | "log": [
84 | {
85 | "type": "2",
86 | "datetime": "08/30/2011 16:11:15",
87 | "alertcontact": [
88 | {
89 | "type": "0",
90 | "value": "uptime@webresourcesdepot.com"
91 | },
92 | {
93 | "type": "3",
94 | "value": "umutm"
95 | }
96 | ]
97 | },
98 | {
99 | "type": "1",
100 | "datetime": "08/30/2011 16:09:30",
101 | "alertcontact": [
102 | {
103 | "type": "0",
104 | "value": "uptime@webresourcesdepot.com"
105 | },
106 | {
107 | "type": "3",
108 | "value": "umutm"
109 | }
110 | ]
111 | }
112 | ]
113 | }
114 | ]
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/tests/data/log.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "2",
3 | "datetime": "08/30/2011 16:11:15",
4 | "alertcontact": [
5 | {
6 | "type": "2",
7 | "value": "uptime@webresourcesdepot.com"
8 | },
9 | {
10 | "type": "3",
11 | "value": "umutm"
12 | }
13 | ]
14 | }
--------------------------------------------------------------------------------
/tests/data/monitor.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "128795",
3 | "friendlyname": "Yahoo",
4 | "url": "http://www.yahoo.com/",
5 | "type": "1",
6 | "subtype": "",
7 | "keywordtype": "0",
8 | "keywordvalue": "",
9 | "httpusername": "",
10 | "httppassword": "",
11 | "port": "",
12 | "status": "2",
13 | "alltimeuptimeratio": "99.98",
14 | "customuptimeratio": "100.00-99.00",
15 | "alertcontact": [
16 | {
17 | "id": "4631",
18 | "type": "2",
19 | "value": "uptime@webresourcesdepot.com"
20 | },
21 | {
22 | "id": "2420",
23 | "type": "3",
24 | "value": "umutm"
25 | }
26 | ],
27 | "log": [
28 | {
29 | "type": "2",
30 | "datetime": "09/25/2011 16:12:44",
31 | "alertcontact": [
32 | {
33 | "type": "2",
34 | "value": "uptime@webresourcesdepot.com"
35 | },
36 | {
37 | "type": "3",
38 | "value": "umutm"
39 | }
40 | ]
41 | },
42 | {
43 | "type": "1",
44 | "datetime": "09/25/2011 16:11:44",
45 | "alertcontact": [
46 | {
47 | "type": "2",
48 | "value": "uptime@webresourcesdepot.com"
49 | },
50 | {
51 | "type": "3",
52 | "value": "umutm"
53 | }
54 | ]
55 | }
56 | ]
57 | }
--------------------------------------------------------------------------------
/tests/data/new_alert_contact.json:
--------------------------------------------------------------------------------
1 | {
2 | "stat": "ok",
3 | "alertcontact": {
4 | "id": "4561",
5 | "status": "0"
6 | }
7 | }
--------------------------------------------------------------------------------
/tests/data/new_monitor.json:
--------------------------------------------------------------------------------
1 | {
2 | "stat": "ok",
3 | "monitor":{
4 | "id":"128798"
5 | }
6 | }
--------------------------------------------------------------------------------
/tests/test_alert_contact.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | import sys, os
4 | import json
5 |
6 | import requests
7 | from pytest import raises
8 | from flexmock import flexmock
9 |
10 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
11 |
12 | from uptimerobot.alert_contact import AlertContact
13 |
14 | class TestAlertContact(object):
15 | def setup(self):
16 | filename = os.path.join(os.path.dirname(__file__), "data", "alert_contact.json")
17 | with open(filename) as f:
18 | self.subject = AlertContact(json.load(f))
19 |
20 | def test_init(self):
21 | assert self.subject.id == "236"
22 | assert self.subject.value == "uptime@webresourcesdepot.com"
23 | assert self.subject.type == 2
--------------------------------------------------------------------------------
/tests/test_cli.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | import sys, os
4 |
5 | from pytest import raises
6 | from flexmock import flexmock
7 | from termcolor import colored
8 |
9 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
10 |
11 | from uptimerobot import Client, APIError
12 | from uptimerobot.cli import parse_cli_args
13 |
14 | class TestCli(object):
15 | def setup(self):
16 | self.client = flexmock(Client)
17 |
18 |
19 |
20 |
21 | ###################################################################
22 | # Monitors
23 |
24 | class TestGetMonitor(TestCli):
25 | LINE = colored("-" * 20, 'blue')
26 |
27 |
28 | def test_get_monitors(self, capsys):
29 | result = [flexmock(dump=lambda: print("monitor"))] * 3
30 | self.client.should_receive("get_monitors").with_args(show_logs=False, show_alert_contacts=False, ids=None, show_log_timezone=False, show_log_alert_contacts=False, custom_uptime_ratio=None).and_return(result)
31 | parse_cli_args("get-monitors".split(" "))
32 | out, err = capsys.readouterr()
33 | assert out == ("monitor\n%s\n\n" % self.LINE) * 3
34 |
35 |
36 | def test_get_monitors_by_ids(self, capsys):
37 | result = [flexmock(dump=lambda: print("monitor"))] * 3
38 | self.client.should_receive("get_monitors").with_args(show_logs=False, show_alert_contacts=False, ids=['15830', '32696', '83920'], show_log_timezone=False, show_log_alert_contacts=False, custom_uptime_ratio=None).and_return(result)
39 | parse_cli_args("get-monitors --monitors 15830 32696 83920".split(" "))
40 | out, err = capsys.readouterr()
41 | assert out == ("monitor\n%s\n\n" % self.LINE) * 3
42 |
43 |
44 | def test_get_monitors_by_names(self, capsys):
45 | monitor = flexmock(id="1234", name="fred", dump=lambda: print("monitor fred"))
46 | self.client.should_receive("get_monitors").with_args().and_return([monitor])
47 |
48 | self.client.should_receive("get_monitors").with_args(show_logs=False, show_alert_contacts=False, ids=['1234'], show_log_timezone=False, show_log_alert_contacts=False, custom_uptime_ratio=None).and_return([monitor])
49 |
50 | parse_cli_args("get-monitors --monitors fred".split(" "))
51 | out, err = capsys.readouterr()
52 | assert out == "monitor fred\n%s\n\n" % self.LINE
53 |
54 |
55 | class TestNewMonitor(TestCli):
56 | def test_new_monitor(self, capsys):
57 | self.client.should_receive("new_monitor").with_args(name="fishy", url="http://fish.com", type=1, alert_contacts=None, subtype=None, port=None, keyword=None, keyword_type=None, username=None, password=None).and_return(999)
58 | parse_cli_args("new-monitor fishy http://fish.com".split(" "))
59 | out, err = capsys.readouterr()
60 | assert out == "Created monitor with id: 999\n"
61 |
62 |
63 | def test_new_monitor_all_args(self, capsys):
64 | self.client.should_receive("new_monitor").with_args(name="fishy", url="http://fish.com", type=2, alert_contacts=["1","2"], subtype=1, port=80, keyword="fish", keyword_type=1, username="user", password="pass").and_return(999)
65 | parse_cli_args("new-monitor fishy http://fish.com --type 2 --alerts 1 2 --subtype 1 --port 80 --keyword fish --keyword-type 1 --username user --password pass".split(" "))
66 | out, err = capsys.readouterr()
67 | assert out == "Created monitor with id: 999\n"
68 |
69 |
70 | def test_new_monitor_no_args(self):
71 | with raises(SystemExit):
72 | parse_cli_args("new-monitor".split(" "))
73 |
74 |
75 | class TestEditMonitor(TestCli):
76 | def test_edit_monitor(self, capsys):
77 | self.client.should_receive("edit_monitor").with_args(id="1234", status=None, name=None, url=None, alert_contacts=None, type=None, subtype=None, port=None, keyword=None, keyword_type=None, username=None, password=None).and_return(1234)
78 | parse_cli_args("edit-monitor 1234".split(" "))
79 | out, err = capsys.readouterr()
80 | assert out == "Edited monitor with id: 1234\n"
81 |
82 |
83 | def test_edit_monitor_all_args(self, capsys):
84 | self.client.should_receive("edit_monitor").with_args(id="1234", status=1, name="fishy", url="http://fish.com", alert_contacts=["1", "2"], type=2, subtype=1, port=80, keyword="fish", keyword_type=1, username="user", password="pass").and_return(1234)
85 | parse_cli_args("edit-monitor 1234 --name fishy --url http://fish.com --type 2 --status 1 --alerts 1 2 --subtype 1 --port 80 --keyword fish --keyword-type 1 --username user --password pass".split(" "))
86 | out, err = capsys.readouterr()
87 | assert out == "Edited monitor with id: 1234\n"
88 |
89 |
90 | def test_edit_monitor_no_args(self):
91 | with raises(SystemExit):
92 | parse_cli_args("edit-monitor".split(" "))
93 |
94 |
95 | class TestDeleteMonitor(TestCli):
96 | def test_delete_monitor_by_id(self, capsys):
97 | self.client.should_receive("delete_monitor").with_args(id="1234").and_return(1234)
98 | parse_cli_args("delete-monitor 1234".split(" "))
99 | out, err = capsys.readouterr()
100 | assert out == "Deleted monitor with id: 1234\n"
101 |
102 |
103 | def test_delete_monitor_by_name(self, capsys):
104 | monitor = flexmock(id="1234", name="fred")
105 | self.client.should_receive("get_monitors").with_args().and_return([monitor])
106 |
107 | self.client.should_receive("delete_monitor").with_args(id="1234").and_return(1234)
108 |
109 | parse_cli_args("delete-monitor fred".split(" "))
110 | out, err = capsys.readouterr()
111 | assert out == "Deleted monitor with id: 1234\n"
112 |
113 |
114 | def test_delete_monitor_bad_name(self):
115 | monitor = flexmock(id="1234", name="romy")
116 | self.client.should_receive("get_monitors").with_args().and_return([monitor])
117 | with raises(APIError):
118 | parse_cli_args("delete-monitor fred".split(" "))
119 |
120 |
121 | def test_delete_monitor_no_id(self):
122 | with raises(SystemExit):
123 | parse_cli_args("delete-monitor".split(" "))
124 |
125 |
126 |
127 | ##################################################################
128 | # Alerts
129 |
130 | class TestGetAlerts(TestCli):
131 | def test_get_alerts(self, capsys):
132 | alert = flexmock(dump=lambda: print("alert"))
133 | self.client.should_receive("get_alert_contacts").with_args(ids=None).and_return([alert])
134 | parse_cli_args("get-alerts".split(" "))
135 | out, err = capsys.readouterr()
136 | assert out == "alert\n"
137 |
138 |
139 | def test_get_alerts_ids(self, capsys):
140 | alert = flexmock(dump=lambda: print("alert"))
141 | self.client.should_receive("get_alert_contacts").with_args(ids=["236", "1782", "4790"]).and_return([alert])
142 | parse_cli_args("get-alerts --alerts 236 1782 4790".split(" "))
143 | out, err = capsys.readouterr()
144 | assert out == "alert\n"
145 |
146 |
147 | def test_get_alerts_values(self, capsys):
148 | alert = flexmock(id="1234", value="fred", dump=lambda: print("alert fred"))
149 | self.client.should_receive("get_alert_contacts").with_args().and_return([alert])
150 |
151 | self.client.should_receive("get_alert_contacts").with_args(ids=["1234"]).and_return([alert])
152 | parse_cli_args("get-alerts --alerts fred".split(" "))
153 | out, err = capsys.readouterr()
154 | assert out == "alert fred\n"
155 |
156 |
157 | def test_get_alerts_bad_values(self):
158 | self.client.should_receive("get_alert_contacts").with_args().and_return([])
159 |
160 | with raises(APIError):
161 | parse_cli_args("get-alerts --alerts fred".split(" "))
162 |
163 |
164 |
165 | class TestNewAlert(TestCli):
166 | def test_new_alert(self, capsys):
167 | self.client.should_receive("new_alert_contact").with_args(type=1, value="uptime@webresourcesdepot.com").and_return("1234")
168 | parse_cli_args("new-alert uptime@webresourcesdepot.com --type 1".split(" "))
169 | out, err = capsys.readouterr()
170 | assert out == "Created alert contact with id: 1234\n"
171 |
172 |
173 | def test_new_alert_default_type(self, capsys):
174 | self.client.should_receive("new_alert_contact").with_args(type=2,value="uptime@webresourcesdepot.com").and_return("1234")
175 | parse_cli_args("new-alert uptime@webresourcesdepot.com".split(" "))
176 | out, err = capsys.readouterr()
177 | assert out == "Created alert contact with id: 1234\n"
178 |
179 |
180 | def test_new_alert_bad_type(self):
181 | with raises(SystemExit):
182 | parse_cli_args("new-alert uptime@webresourcesdepot.com --type fred".split(" "))
183 |
184 |
185 | def test_new_alert_no_args(self):
186 | with raises(SystemExit):
187 | parse_cli_args("new-alert".split(" "))
188 |
189 |
190 | class TestDeleteAlert(TestCli):
191 | def test_delete_alert_by_id(self, capsys):
192 | self.client.should_receive("delete_alert_contact").with_args(id="1234").and_return("1234")
193 | parse_cli_args("delete-alert 1234".split(" "))
194 | out, err = capsys.readouterr()
195 | assert out == "Deleted alert contact with id: 1234\n"
196 |
197 |
198 | def test_delete_alert_by_name(self):
199 | alert = flexmock(id="1234", value="fred")
200 | self.client.should_receive("get_alert_contacts").with_args().and_return([alert])
201 | self.client.should_receive("delete_alert_contact").with_args(id="1234").and_return("1234")
202 |
203 | parse_cli_args("delete-alert fred".split(" "))
204 |
205 |
206 | def test_delete_alert_bad_name(self):
207 | self.client.should_receive("get_alert_contacts").with_args().and_return([])
208 | with raises(APIError):
209 | parse_cli_args("delete-alert fred".split(" "))
210 |
211 |
212 | def test_delete_alert_no_args(self):
213 | with raises(SystemExit):
214 | parse_cli_args("delete-alert".split(" "))
--------------------------------------------------------------------------------
/tests/test_client.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | import sys, os
4 | import json
5 |
6 | import requests
7 | from pytest import raises
8 | from flexmock import flexmock
9 |
10 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
11 |
12 | from uptimerobot import Client, APIError, HTTPError
13 |
14 | from uptimerobot.monitor import Monitor
15 | from uptimerobot.log import Log
16 | from uptimerobot.alert_contact import AlertContact
17 |
18 |
19 | class TestClient(object):
20 | API_KEY = "u956-afus321g565fghr519"
21 |
22 | def setup(self):
23 | self.client = Client(self.API_KEY)
24 |
25 |
26 | def response(self, name):
27 | filename = os.path.join(os.path.dirname(__file__), "data", "%s.json" % name)
28 | with open(filename) as f:
29 | return json.load(f)
30 |
31 |
32 | ###########################################################
33 | # Monitors
34 |
35 | class TestGetMonitors(TestClient):
36 | def test_get_all_monitors(self):
37 | flexmock(self.client).should_receive("get").with_args("getMonitors").and_return(self.response("get_monitors"))
38 | monitors = self.client.get_monitors()
39 |
40 | assert len(monitors) == 2
41 | assert all(isinstance(monitor, Monitor) for monitor in monitors)
42 | assert [monitor.id for monitor in monitors] == ["128795", "128796"]
43 |
44 |
45 | def test_get_specific_monitors(self):
46 | flexmock(self.client).should_receive("get").with_args("getMonitors", monitors="128795-128796").and_return(self.response("get_monitors"))
47 | monitors = self.client.get_monitors(ids=["128795", "128796"])
48 |
49 | assert all(isinstance(monitor, Monitor) for monitor in monitors)
50 | assert [monitor.id for monitor in monitors] == ["128795", "128796"]
51 |
52 |
53 | def test_get_all_monitors_all_options(self):
54 | flexmock(self.client).should_receive("get").with_args("getMonitors", customUptimeRatio="1-2-3", logs="1", alertContacts="1", showMonitorAlertContacts="1", showTimezone="1").and_return(self.response("get_monitors"))
55 | monitors = self.client.get_monitors(show_logs=True, show_alert_contacts=True, show_log_alert_contacts=True, show_log_timezone=True, custom_uptime_ratio=[1, 2, 3])
56 |
57 | assert len(monitors) == 2
58 | assert all(isinstance(monitor, Monitor) for monitor in monitors)
59 | assert [monitor.id for monitor in monitors] == ["128795", "128796"]
60 |
61 |
62 | def test_bad_monitors_integer(self):
63 | with raises(TypeError):
64 | self.client.get_monitors(ids=[128795])
65 |
66 |
67 | def test_bad_monitors_not_numeric(self):
68 | with raises(ValueError):
69 | self.client.get_monitors(ids=["fred"])
70 |
71 |
72 | def test_bad_monitors_not_ierable(self):
73 | with raises(TypeError):
74 | self.client.get_monitors(ids=12344)
75 |
76 |
77 | def test_bad_custom_ratio_negative(self):
78 | with raises(TypeError):
79 | self.client.get_monitors(custom_uptime_ratio=[-1])
80 |
81 |
82 | def test_bad_custom_ratio_type(self):
83 | with raises(TypeError):
84 | self.client.get_monitors(custom_uptime_ratio=["5"])
85 |
86 |
87 | def test_bad_custom_ratio_non_iterable(self):
88 | with raises(TypeError):
89 | self.client.get_monitors(custom_uptime_ratio=5)
90 |
91 |
92 | class TestNewMonitor(TestClient):
93 | def test_new_monitor(self):
94 | flexmock(self.client).should_receive("get").with_args("newMonitor", monitorFriendlyName="fred", monitorURL="http://x.y", monitorType="2").and_return(self.response("new_monitor"))
95 | new_id = self.client.new_monitor(name="fred", url="http://x.y", type=2)
96 | assert new_id == "128798"
97 |
98 |
99 | def test_username_and_no_password(self):
100 | with raises(ValueError):
101 | self.client.new_monitor(name="fred", url="abc", type=2, username="fred")
102 |
103 |
104 | def test_password_and_no_username(self):
105 | with raises(ValueError):
106 | self.client.new_monitor(name="fred", url="abc", type=2, password="fred")
107 |
108 |
109 | def test_keyword_and_no_keyword_type(self):
110 | with raises(ValueError):
111 | self.client.new_monitor(name="fred", url="abc", type=2, keyword="fred")
112 |
113 |
114 | def test_keyword_type_and_no_keyword(self):
115 | with raises(ValueError):
116 | self.client.new_monitor(name="fred", url="abc", type=2, keyword_type=1)
117 |
118 | def test_bad_type(self):
119 | with raises(ValueError):
120 | self.client.new_monitor(name="fred", url="abc", type=200)
121 |
122 | def test_bad_type(self):
123 | with raises(ValueError):
124 | self.client.new_monitor(name="fred", url="abc", type=2, subtype=200)
125 |
126 |
127 | def test_bad_keyword_type(self):
128 | with raises(ValueError):
129 | self.client.new_monitor(name="fred", url="abc", type=2, keyword_type=100, keyword="fred")
130 |
131 |
132 | def test_bad_alerts_integer(self):
133 | with raises(TypeError):
134 | self.client.new_monitor(name="fred", url="abc", type=2, alert_contacts=[128795])
135 |
136 |
137 | def test_bad_alerts_not_numeric(self):
138 | with raises(ValueError):
139 | self.client.new_monitor(name="fred", url="abc", type=2, alert_contacts=["fred"])
140 |
141 |
142 | def test_bad_alerts_not_ierable(self):
143 | with raises(TypeError):
144 | self.client.new_monitor(name="fred", url="abc", type=2, alert_contacts=12344)
145 |
146 |
147 | class TestEditMonitor(TestClient):
148 | def test_edit_monitor(self):
149 | flexmock(self.client).should_receive("get").with_args("editMonitor", monitorID="128798").and_return(self.response("edit_monitor"))
150 | edited_id = self.client.edit_monitor(id="128798")
151 | assert edited_id == "128798"
152 |
153 | def test_edit_monitor_with_status_1(self):
154 | flexmock(self.client).should_receive("get").with_args("editMonitor", monitorID="128798", monitorStatus="1").and_return(self.response("edit_monitor"))
155 | edited_id = self.client.edit_monitor(id="128798", status=1)
156 | assert edited_id == "128798"
157 |
158 | def test_edit_monitor_with_status_0(self):
159 | flexmock(self.client).should_receive("get").with_args("editMonitor", monitorID="128798", monitorStatus="0").and_return(self.response("edit_monitor"))
160 | edited_id = self.client.edit_monitor(id="128798", status=0)
161 | assert edited_id == "128798"
162 |
163 |
164 | def test_bad_id_non_numeric(self):
165 | with raises(ValueError):
166 | self.client.edit_monitor(id="fred")
167 |
168 |
169 | def test_bad_id_integer(self):
170 | with raises(TypeError):
171 | self.client.edit_monitor(id=123)
172 |
173 |
174 | def test_bad_type(self):
175 | with raises(ValueError):
176 | self.client.edit_monitor(id="1234", type=200)
177 |
178 |
179 | def test_bad_type(self):
180 | with raises(ValueError):
181 | self.client.edit_monitor(id="1234", subtype=200)
182 |
183 |
184 | def test_bad_status(self):
185 | with raises(ValueError):
186 | self.client.edit_monitor(id="1234", status=200)
187 |
188 |
189 | def test_bad_keyword_type(self):
190 | with raises(ValueError):
191 | self.client.edit_monitor(id="1234", keyword_type=100, keyword="fred")
192 |
193 |
194 | def test_bad_alerts_integer(self):
195 | with raises(TypeError):
196 | self.client.edit_monitor(id="1234", alert_contacts=[128795])
197 |
198 |
199 | def test_bad_alerts_not_numeric(self):
200 | with raises(ValueError):
201 | self.client.edit_monitor(id="1234", alert_contacts=["fred"])
202 |
203 |
204 | def test_bad_alerts_not_ierable(self):
205 | with raises(TypeError):
206 | self.client.edit_monitor(id="1234", alert_contacts=12344)
207 |
208 |
209 | class TestDeleteMonitor(TestClient):
210 | def test_delete_monitor(self):
211 | flexmock(self.client).should_receive("get").with_args("deleteMonitor", monitorID="128798").and_return(self.response("delete_monitor"))
212 | deleted_id = self.client.delete_monitor(id="128798")
213 | assert deleted_id == "128798"
214 |
215 |
216 | def test_bad_id_non_numeric(self):
217 | with raises(ValueError):
218 | self.client.delete_monitor(id="fred")
219 |
220 |
221 | def test_bad_id_integer(self):
222 | with raises(TypeError):
223 | self.client.delete_monitor(id=123)
224 |
225 |
226 | ###########################################################
227 | # Alert Contacts
228 |
229 | class TestGetAlertContacts(TestClient):
230 | def test_all_contacts(self):
231 | flexmock(self.client).should_receive("get").with_args("getAlertContacts").and_return(self.response("get_alert_contacts"))
232 | contacts = self.client.get_alert_contacts()
233 |
234 | assert all(isinstance(contact, AlertContact) for contact in contacts)
235 | assert [contact.id for contact in contacts] == ["236", "237"]
236 |
237 |
238 | def test_specific_contacts(self):
239 | flexmock(self.client).should_receive("get").with_args("getAlertContacts", alertcontacts="236-237").and_return(self.response("get_alert_contacts"))
240 | contacts = self.client.get_alert_contacts(ids=["236", "237"])
241 |
242 | assert all(isinstance(contact, AlertContact) for contact in contacts)
243 | assert [contact.id for contact in contacts] == ["236", "237"]
244 |
245 |
246 | def test_bad_contacts_integer(self):
247 | with raises(TypeError):
248 | self.client.get_alert_contacts(ids=[236])
249 |
250 |
251 | def test_bad_contacts_not_numeric(self):
252 | with raises(ValueError):
253 | monitors = self.client.get_alert_contacts(ids=["fred"])
254 |
255 |
256 | def test_bad_contacts_not_ierable(self):
257 | with raises(TypeError):
258 | monitors = self.client.get_alert_contacts(ids=12344)
259 |
260 |
261 | class TestNewAlertContact(TestClient):
262 | def test_standard(self):
263 | flexmock(self.client).should_receive("get").with_args("newAlertContact", alertContactType="2", alertContactValue="uptime@webresourcesdepot.com").and_return(self.response("new_alert_contact"))
264 | new_id = self.client.new_alert_contact(type=2, value="uptime@webresourcesdepot.com")
265 | assert new_id == "4561"
266 |
267 |
268 | def test_bad_type_value(self):
269 | with raises(ValueError):
270 | self.client.new_alert_contact(type=10, value="uptime@webresourcesdepot.com")
271 |
272 |
273 | def test_bad_value_type(self):
274 | with raises(TypeError):
275 | self.client.new_alert_contact(type=2, value=2)
276 |
277 |
278 | class TestDeleteAlertContact(TestClient):
279 | def test_standard(self):
280 | flexmock(self.client).should_receive("get").with_args("deleteAlertContact", alertContactID="236").and_return(self.response("delete_alert_contact"))
281 | deleted_id = self.client.delete_alert_contact(id="236")
282 | assert deleted_id == "236"
283 |
284 |
285 | def test_bad_id_non_numeric(self):
286 | with raises(ValueError):
287 | self.client.delete_alert_contact(id="fred")
288 |
289 | def test_bad_id_integer(self):
290 | with raises(TypeError):
291 | self.client.delete_alert_contact(id=123)
292 |
293 |
--------------------------------------------------------------------------------
/tests/test_log.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | import sys, os
4 | import json
5 |
6 | import requests
7 | from pytest import raises
8 | from flexmock import flexmock
9 |
10 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
11 |
12 | from uptimerobot.log import Log
13 | from uptimerobot.alert_contact import AlertContact
14 |
15 | class TestLog(object):
16 | def setup(self):
17 | filename = os.path.join(os.path.dirname(__file__), "data", "log.json")
18 | with open(filename) as f:
19 | self.subject = Log(json.load(f))
20 |
21 | def test_init(self):
22 | assert self.subject.type == 2
23 | assert self.subject.datetime.year == 2011
24 | assert self.subject.datetime.hour == 16
25 |
26 | assert len(self.subject.alert_contacts) == 2
27 |
28 | assert self.subject.alert_contacts[0].type == 2
29 | assert self.subject.alert_contacts[0].value == "uptime@webresourcesdepot.com"
30 |
31 | assert self.subject.alert_contacts[1].type == 3
32 | assert self.subject.alert_contacts[1].value == "umutm"
--------------------------------------------------------------------------------
/tests/test_monitor.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | import sys, os
4 | import json
5 |
6 | import requests
7 | from pytest import raises
8 | from flexmock import flexmock
9 |
10 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
11 |
12 | from uptimerobot.monitor import Monitor
13 | from uptimerobot.log import Log
14 | from uptimerobot.alert_contact import AlertContact
15 |
16 |
17 | class TestMonitor(object):
18 | def setup(self):
19 | filename = os.path.join(os.path.dirname(__file__), "data", "monitor.json")
20 | with open(filename) as f:
21 | self.subject = Monitor(json.load(f))
22 |
23 | def test_init(self):
24 | assert self.subject.id == "128795"
25 | assert self.subject.name == "Yahoo"
26 | assert self.subject.url == "http://www.yahoo.com/"
27 |
28 | assert self.subject.all_time_uptime_ratio == 99.98
29 | assert self.subject.custom_uptime_ratio == [100.0, 99.0]
30 |
31 | assert len(self.subject.alert_contacts) == 2
32 |
33 | assert self.subject.alert_contacts[0].id == "4631"
34 | assert self.subject.alert_contacts[0].type == 2
35 | assert self.subject.alert_contacts[0].value == "uptime@webresourcesdepot.com"
36 |
37 | assert self.subject.alert_contacts[1].id == "2420"
38 | assert self.subject.alert_contacts[1].type == 3
39 | assert self.subject.alert_contacts[1].value == "umutm"
40 |
41 | assert len(self.subject.logs) == 2
42 |
43 | assert self.subject.logs[0].type == 2
44 | assert self.subject.logs[0].datetime.minute == 12
45 | assert len(self.subject.logs[0].alert_contacts) == 2
46 |
47 | assert self.subject.logs[1].type == 1
48 | assert self.subject.logs[1].datetime.minute == 11
49 | assert len(self.subject.logs[1].alert_contacts) == 2
50 |
--------------------------------------------------------------------------------
/uptimerobot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from __future__ import absolute_import, division, print_function, unicode_literals
4 |
5 | from uptimerobot.cli import main
6 |
7 | """
8 | Run CLI directly, for development purposes.
9 | When egg is installed, then "uptimerobot" command is available
10 | """
11 |
12 | main()
13 |
--------------------------------------------------------------------------------
/uptimerobot/.uptimerobot.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | # UptimeRobot API key MUST BE SET BY THE USER (in config or on the command line).
4 |
5 | api_key: nokey # By default, we use a dummy key which won't work!
6 |
7 | # Only optional parameters are defaulted here.
8 | # Remember that alerts and monitors are STRINGS, not numbers.
9 |
10 | get_monitors:
11 | monitors: null # e.g ['012', 'my monitor', '1451']
12 | show_alerts: False
13 | show_log: False
14 | log_alerts: False
15 | log_timezone: False
16 | uptime: null # e.g [1, 5, 10]
17 |
18 | new_monitor:
19 | type: 1 # http(s)
20 | subtype: null
21 | port: null
22 | keyword_type: null
23 | keyword: null
24 | username: null
25 | password: null
26 | alerts: null # e.g. ['12315', 'my alert']
27 |
28 | edit_monitor:
29 | # Probably not a good idea to default any of these.
30 | name: null
31 | status: null
32 | url: null
33 | type: null
34 | subtype: null
35 | port: null
36 | keyword_type: null
37 | keyword: null
38 | username: null
39 | password: null
40 | alerts: null # e.g. ['12315', 'my alert']
41 |
42 | get_alerts:
43 | alerts: null # e.g. ['12315', 'my alert']
44 |
45 | new_alert:
46 | type: 2 # Default to email
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/uptimerobot/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | __all__ = ["Client", "UptimeRobotError", "APIError", "HTTPError"]
4 |
5 |
6 | class UptimeRobotError(Exception):
7 | pass
8 |
9 |
10 | class APIError(UptimeRobotError):
11 | pass
12 |
13 |
14 | class HTTPError(UptimeRobotError):
15 | pass
16 |
17 |
18 | from .client import Client
--------------------------------------------------------------------------------
/uptimerobot/alert_contact.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | from termcolor import colored
4 |
5 | class AlertContact(object):
6 | class Type:
7 | SMS = 1
8 | EMAIL = 2
9 | TWITTER = 3
10 | BOXCAR = 4
11 |
12 | TYPES = {
13 | Type.SMS: "sms",
14 | Type.EMAIL: "email",
15 | Type.TWITTER: "twitter",
16 | Type.BOXCAR: "boxcar",
17 | }
18 |
19 | class Status:
20 | NOT_ACTIVATED = 0
21 | PAUSED = 1
22 | ACTIVE = 2
23 |
24 | STATUSES = {
25 | Status.NOT_ACTIVATED: "not activated",
26 | Status.PAUSED: "paused",
27 | Status.ACTIVE: "active",
28 | }
29 |
30 |
31 | def __init__(self, data):
32 | self.id = data.get("id", None)
33 | self.type = int(data["type"])
34 | self.value = data["value"]
35 | self.status = int(data["status"]) if "status" in data else None
36 |
37 | type_str = property(lambda self: self.TYPES[self.type])
38 | status_str = property(lambda self: self.STATUSES[self.status])
39 |
40 |
41 | def dump(self):
42 | # No id/type if inside a log.
43 | if self.id is not None and self.status is not None:
44 | if self.status == self.Status.ACTIVE:
45 | color = "green"
46 | elif self.status == self.Status.NOT_ACTIVATED:
47 | color = "red"
48 | else:
49 | color = "yellow"
50 |
51 | status = colored(self.status_str.title(), color)
52 |
53 | # List of alerts
54 | print(" %s: %s [%s] #%s" % (self.type_str, self.value, status, self.id))
55 | elif self.id is not None and self.status is None:
56 | # In monitor.
57 | print(" %s: %s #%s" % (self.type_str, self.value, self.id))
58 | else:
59 | # In log.
60 | print(" %s: %s" % (self.type_str, self.value))
--------------------------------------------------------------------------------
/uptimerobot/cli.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | from sys import argv, stderr, modules
4 | from argparse import ArgumentParser, RawTextHelpFormatter
5 | import re, os
6 |
7 | import yaml
8 | from termcolor import colored
9 |
10 | from . import UptimeRobotError, APIError
11 | from .client import Client
12 | from .monitor import Monitor
13 | from .alert_contact import AlertContact
14 |
15 |
16 | LOCAL_CONFIG_FILE = ".uptimerobot.yml"
17 | USER_CONFIG_FILE = os.path.expanduser(os.path.join("~", LOCAL_CONFIG_FILE))
18 | DEFAULT_CONFIG_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), LOCAL_CONFIG_FILE))
19 |
20 |
21 | def dict_str(dict):
22 | """Layout a list of keys and values for the help text"""
23 |
24 | str = ""
25 | for key, value in dict.items():
26 | str += " %2d: %s\n" % (key, value)
27 | return str
28 |
29 |
30 | def parse_get_monitors(parser, defaults, api_key):
31 | command = parser.add_parser('get-monitors',
32 | description="Get information about some or all monitors",
33 | help="Get information about some or all monitors")
34 |
35 | parse_api_key(command, api_key)
36 |
37 | command.add_argument('--monitors', metavar="MONITOR", type=str, nargs='+',
38 | help='IDs or names of monitors')
39 |
40 | command.add_argument('--uptime', metavar="NUM-HOURS", type=int, nargs='+',
41 | default=defaults["uptime"],
42 | help='Show custom uptime ratios, for one or more periods (in hours)')
43 |
44 | command.add_argument('--show-log', action='store_true',
45 | default=defaults["show_log"],
46 | help="Show logs associated with this monitor")
47 |
48 | command.add_argument('--log-alerts', action='store_true',
49 | default=defaults["log_alerts"],
50 | help="Show logs with their associated alert contacts (ignored without --show-log)")
51 |
52 | command.add_argument('--show-alerts', action='store_true',
53 | default=defaults["show_alerts"],
54 | help="shows alert contacts associated with this monitor")
55 |
56 | command.add_argument('--log-timezone', action='store_true',
57 | default=defaults["log_timezone"],
58 | help="shows timezone for the logs (ignored without --show-log)")
59 |
60 |
61 | def parse_new_monitor(parser, defaults, api_key):
62 | description = """
63 | Create a new monitor
64 |
65 | Type:
66 | %s
67 |
68 | Subtype:
69 | %s
70 |
71 | Keyword Type:
72 | %s
73 | """ % (dict_str(Monitor.TYPES), dict_str(Monitor.SUBTYPES), dict_str(Monitor.KEYWORD_TYPES))
74 |
75 | command = parser.add_parser('new-monitor',
76 | formatter_class=RawTextHelpFormatter,
77 | help="Create a new monitor",
78 | description=description)
79 |
80 | # Required:
81 | command.add_argument('name', metavar='NAME', type=str,
82 | help='Friendly name for new monitor')
83 |
84 | command.add_argument('url', metavar='URL', type=str,
85 | help='URL for new monitor')
86 |
87 | # Options:
88 |
89 | parse_api_key(command, api_key)
90 |
91 | command.add_argument('--type', metavar='N', type=int,
92 | choices=Monitor.TYPES.keys(),
93 | default=defaults["type"],
94 | help='Type of monitor to create')
95 |
96 | command.add_argument('--subtype', type=int, metavar="N",
97 | choices=Monitor.SUBTYPES.keys(),
98 | default=defaults["subtype"],
99 | help='Subtype to monitor')
100 |
101 | command.add_argument('--port', type=int, metavar="N",
102 | default=defaults["port"],
103 | help='Port to monitor')
104 |
105 | command.add_argument('--keyword-type', type=int, metavar="N",
106 | choices=Monitor.KEYWORD_TYPES.keys(),
107 | default=defaults["keyword_type"],
108 | help='Type of keyword to monitor')
109 |
110 | command.add_argument('--keyword', type=str, metavar="STR",
111 | default=defaults["keyword"],
112 | help='Keyword to monitor')
113 |
114 | command.add_argument('--username', type=str, metavar="STR",
115 | default=defaults["username"],
116 | help='HTTP username to use for private site')
117 |
118 | command.add_argument('--password', type=str, metavar="STR",
119 | default=defaults["password"],
120 | help='HTTP password to use for private site')
121 |
122 | command.add_argument('--alerts', metavar="ALERT", type=str, nargs='+',
123 | default=defaults["alerts"],
124 | help='IDs / values of alert contacts to use')
125 |
126 |
127 | def parse_edit_monitor(parser, defaults, api_key):
128 | description = """
129 | Edit an existing monitor
130 |
131 | Type:
132 | %s
133 |
134 | Subtype:
135 | %s
136 |
137 | Keyword Type:
138 | %s
139 |
140 | Status:
141 | %s
142 | """ % (dict_str(Monitor.TYPES), dict_str(Monitor.SUBTYPES), dict_str(Monitor.KEYWORD_TYPES), dict_str(Monitor.STATUSES))
143 |
144 | command = parser.add_parser('edit-monitor',
145 | formatter_class=RawTextHelpFormatter,
146 | description=description,
147 | help="Edit an existing monitor")
148 |
149 | command.add_argument('id', metavar='ID', type=str,
150 | help='ID of monitor to edit')
151 |
152 | parse_api_key(command, api_key)
153 |
154 | command.add_argument('--name', type=str, metavar="STR",
155 | default=defaults["name"],
156 | help='Friendly name of monitor')
157 |
158 | command.add_argument('--status', type=int, metavar="N",
159 | default=defaults["status"],
160 | choices=Monitor.STATUSES.keys(),
161 | help='Status to set the monitor to')
162 |
163 | command.add_argument('--url', type=str, metavar="STR",
164 | default=defaults["url"],
165 | help='URL to monitor')
166 |
167 | command.add_argument('--type', type=int, metavar="N",
168 | default=defaults["type"],
169 | choices=Monitor.TYPES.keys(),
170 | help='Type to monitor')
171 |
172 | command.add_argument('--subtype', type=int, metavar="N",
173 | default=defaults["subtype"],
174 | choices=Monitor.SUBTYPES.keys(),
175 | help='Subtype to monitor')
176 |
177 | command.add_argument('--port', type=int, metavar="N",
178 | default=defaults["port"],
179 | help='Port to monitor')
180 |
181 | command.add_argument('--keyword-type', type=int, metavar="N",
182 | default=defaults["keyword_type"],
183 | choices=Monitor.KEYWORD_TYPES.keys(),
184 | help='Type of keyword to monitor')
185 |
186 | command.add_argument('--keyword', type=str, metavar="STR",
187 | default=defaults["keyword"],
188 | help='Keyword to monitor')
189 |
190 | command.add_argument('--username', type=str, metavar="STR",
191 | default=defaults["username"],
192 | help='HTTP username to use for private site')
193 |
194 | command.add_argument('--password', type=str, metavar="STR",
195 | default=defaults["password"],
196 | help='HTTP password to use for private site')
197 |
198 | command.add_argument('--alerts', metavar="ID", type=str, nargs='+',
199 | default=defaults["alerts"],
200 | help='IDs of alert contacts to use')
201 |
202 |
203 | def parse_delete_monitor(parser, api_key):
204 | command = parser.add_parser('delete-monitor',
205 | description="Delete a monitor",
206 | help="Delete a monitor")
207 |
208 | parse_api_key(command, api_key)
209 |
210 | command.add_argument('monitor', metavar='MONITOR', type=str,
211 | help='ID/name of monitor to delete')
212 |
213 |
214 | def parse_get_alerts(parser, defaults, api_key):
215 | command = parser.add_parser('get-alerts',
216 | description="Get information about some or all alert contact",
217 | help="Get information about some or all alert contacts")
218 |
219 | parse_api_key(command, api_key)
220 |
221 | command.add_argument('--alerts', metavar="ALERT", type=str, nargs='+',
222 | default=defaults["alerts"],
223 | help='IDs/values of alert contacts')
224 |
225 |
226 | def parse_new_alert(parser, defaults, api_key):
227 | description = """
228 | Create a new alert contact
229 |
230 | Type:
231 | %s
232 | """ % dict_str(AlertContact.TYPES)
233 |
234 |
235 | command = parser.add_parser('new-alert',
236 | formatter_class=RawTextHelpFormatter,
237 | description=description,
238 | help="Create a new alert contact")
239 | command.add_argument('value', metavar='VALUE', type=str,
240 | help='Value of contact (email address, sms number, twitter user, iOS device)')
241 |
242 | parse_api_key(command, api_key)
243 |
244 | command.add_argument('--type', metavar='STR', type=int,
245 | choices=AlertContact.TYPES.keys(),
246 | default=defaults["type"],
247 | help='Type of contact to create')
248 |
249 |
250 | def parse_delete_alert(parser, api_key):
251 | command = parser.add_parser('delete-alert',
252 | description="Delete an alert contact",
253 | help="Delete an alert contact")
254 |
255 | parse_api_key(command, api_key)
256 |
257 | command.add_argument('alert', metavar='ALERT', type=str,
258 | help='ID/value of alert contact to delete')
259 |
260 |
261 | def parse_api_key(parser, api_key):
262 | parser.add_argument('--api-key', metavar="STR", type=str,
263 | default=api_key,
264 | help="Your uptimerobot.com api-key (for account or individual monitor).")
265 |
266 |
267 | def create_parser(defaults):
268 | description = """
269 | Manage monitors and alert contacts at UptimeRobot.com
270 |
271 | If file exists, application will take defaults from:
272 | ./.uptimerobot.yml
273 | ~/.uptimerobot.yml
274 | """
275 |
276 | parser = ArgumentParser(description=description,
277 | formatter_class=RawTextHelpFormatter,
278 | usage="uptimerobot [-h] SUBCOMMAND [OPTION, ...]")
279 | sub_commands = parser.add_subparsers(title='Subcommands',
280 | dest="subcommand")
281 |
282 | api_key = defaults["api_key"]
283 |
284 | parse_get_monitors(sub_commands, defaults["get_monitors"], api_key)
285 | parse_new_monitor(sub_commands, defaults["new_monitor"], api_key)
286 | parse_edit_monitor(sub_commands, defaults["edit_monitor"], api_key)
287 | parse_delete_monitor(sub_commands, api_key)
288 |
289 | parse_get_alerts(sub_commands, defaults["get_alerts"], api_key)
290 | parse_new_alert(sub_commands, defaults["new_alert"], api_key)
291 | parse_delete_alert(sub_commands, api_key)
292 |
293 | return parser
294 |
295 |
296 | def get_monitor_ids(client, ids_and_names):
297 | """Get monitor ids from a list of ids and names"""
298 |
299 | if ids_and_names:
300 | # Split ids and values.
301 | ids = list(filter(lambda m: re.match(client.ID_PATTERN, m), ids_and_names))
302 | names = list(filter(lambda m: not re.match(client.ID_PATTERN, m), ids_and_names))
303 |
304 | # Look up the ids of any values given.
305 | if names:
306 | monitors = filter(lambda m: (m.name in names), client.get_monitors())
307 | ids += [m.id for m in monitors]
308 | else:
309 | ids = None
310 |
311 | return ids
312 |
313 |
314 | def get_alert_contact_ids(client, ids_and_values):
315 | """Get alert contact ids from a list of ids and values"""
316 |
317 | if ids_and_values:
318 | # Split ids and values.
319 | ids = list(filter(lambda a: re.match(client.ID_PATTERN, a), ids_and_values))
320 | values = list(filter(lambda a: not re.match(client.ID_PATTERN, a), ids_and_values))
321 |
322 | # Look up the ids of any values given.
323 | if values:
324 | alerts = filter(lambda a: (a.value in values), client.get_alert_contacts())
325 | ids += [a.id for a in alerts]
326 | else:
327 | ids = None
328 |
329 | return ids
330 |
331 |
332 | def get_monitors(client, options):
333 | monitors = get_monitor_ids(client, options.monitors)
334 |
335 | if monitors is not None and len(monitors) == 0:
336 | raise APIError("Alert contact not found with value: %s" % options.monitors)
337 |
338 | monitors = client.get_monitors(ids=monitors,
339 | show_logs=options.show_log,
340 | show_alert_contacts=options.show_alerts,
341 | show_log_alert_contacts=options.log_alerts,
342 | show_log_timezone=options.log_timezone,
343 | custom_uptime_ratio=options.uptime)
344 | for m in monitors:
345 | m.dump()
346 | print(colored("-" * 20, "blue"))
347 | print()
348 |
349 |
350 | def new_monitor(client, options):
351 | alert_contacts = get_alert_contact_ids(client, options.alerts)
352 |
353 | id = client.new_monitor(name=options.name,
354 | url=options.url,
355 | type=options.type,
356 | subtype=options.subtype,
357 | port=options.port,
358 | keyword_type=options.keyword_type,
359 | keyword=options.keyword,
360 | username=options.username,
361 | password=options.password,
362 | alert_contacts=alert_contacts)
363 |
364 | print("Created monitor with id: %s" % id)
365 |
366 |
367 | def edit_monitor(client, options):
368 | alert_contacts = get_alert_contact_ids(client, options.alerts)
369 |
370 | id = client.edit_monitor(id=options.id,
371 | status=options.status,
372 | name=options.name,
373 | url=options.url,
374 | type=options.type,
375 | subtype=options.subtype,
376 | port=options.port,
377 | keyword_type=options.keyword_type,
378 | keyword=options.keyword,
379 | username=options.username,
380 | password=options.password,
381 | alert_contacts=alert_contacts)
382 |
383 | print("Edited monitor with id: %s" % id)
384 |
385 |
386 | def delete_monitor(client, options):
387 | monitors = get_monitor_ids(client, [options.monitor])
388 |
389 | if len(monitors) == 0:
390 | raise APIError("Monitor not found with name: %s" % options.monitor)
391 |
392 | id = client.delete_monitor(id=monitors[0])
393 | print("Deleted monitor with id: %s" % id)
394 |
395 |
396 | def get_alerts(client, options):
397 | alerts = get_alert_contact_ids(client, options.alerts)
398 |
399 | if alerts is not None and len(alerts) == 0:
400 | raise APIError("No alerts found:: %s" % options.alerts)
401 |
402 | for alert in client.get_alert_contacts(ids=alerts):
403 | alert.dump()
404 |
405 |
406 | def new_alert(client, options):
407 | id = client.new_alert_contact(type=options.type,
408 | value=options.value)
409 |
410 | print("Created alert contact with id: %s" % id)
411 |
412 |
413 | def delete_alert(client, options):
414 | alerts = get_alert_contact_ids(client, [options.alert])
415 |
416 | if len(alerts) == 0:
417 | raise APIError("Alert contact not found with value: %s" % options.alert)
418 |
419 | id = client.delete_alert_contact(id=alerts[0])
420 | print("Deleted alert contact with id: %s" % id)
421 |
422 |
423 | def dict_merge(first, second):
424 | """Recursively merge dicts and set non-dict values"""
425 |
426 | # Very dumb implementation, but it is fine for our usage.
427 | for k, v in second.items():
428 | if k in first and isinstance(first[k], dict):
429 | dict_merge(first[k], v)
430 | else:
431 | first[k] = v
432 |
433 | return first
434 |
435 |
436 | def parse_cli_args(args):
437 | """
438 | Parse arguments given to CLI application and run client
439 | accordingly
440 | """
441 |
442 | with open(DEFAULT_CONFIG_FILE) as f:
443 | config = yaml.load(f)
444 |
445 | # See if we can get overriding config from ./ and/or ~/
446 | try:
447 | # ~/.uptimerobot.yml will override the defaults.
448 | with open(USER_CONFIG_FILE) as f:
449 | dict_merge(config, yaml.load(f))
450 | except IOError:
451 | pass
452 |
453 | try:
454 | # ./.uptimerobot.yml is the most important.
455 | with open(LOCAL_CONFIG_FILE) as f:
456 | dict_merge(config, yaml.load(f))
457 | except IOError:
458 | pass
459 |
460 |
461 | parser = create_parser(config)
462 | options = parser.parse_args(args)
463 |
464 | client = Client(options.api_key)
465 |
466 | # Call the handler function dynamically.
467 | getattr(modules[__name__], options.subcommand.replace("-", "_"))(client, options)
468 |
469 |
470 | def main():
471 | """Command line access to the API (accessed directly from "uptimerobot" command)."""
472 | try:
473 | parse_cli_args(argv[1:])
474 | except UptimeRobotError as ex:
475 | print("%s: %s" % (type(ex).__name__, ex), file=stderr)
476 | exit(1)
477 | except (ValueError, TypeError) as ex:
478 | print("Error in parameter value: %s" % ex, file=stderr)
479 | exit(1)
--------------------------------------------------------------------------------
/uptimerobot/client.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | import re
4 | import sys
5 | import json
6 |
7 | import requests
8 |
9 | from . import APIError, HTTPError
10 | from .monitor import Monitor
11 | from .alert_contact import AlertContact
12 |
13 | # Ensure that we can test against the appropriate string types.
14 | if sys.version_info < (3, 0):
15 | string = basestring
16 | else:
17 | string = (str, bytes)
18 |
19 |
20 | class Client(object):
21 | """An uptimerobot API client"""
22 |
23 |
24 | URL = "http://api.uptimerobot.com/"
25 | LIST_SEPARATOR = "-"
26 | ID_PATTERN = "^\d+$"
27 |
28 |
29 | def __init__(self, api_key):
30 | self.api_key = api_key
31 |
32 |
33 | def get(self, action, **values):
34 | payload = {
35 | "apiKey": self.api_key,
36 | "format": "json",
37 | "noJsonCallback": 1,
38 | }
39 |
40 | payload.update(values)
41 |
42 | response = requests.get(self.URL + action, params=payload)
43 |
44 | # Handle client/server errors with the request.
45 | if response.status_code != requests.codes.ok:
46 | try:
47 | raise response.raise_for_status()
48 | except Exception as ex:
49 | raise HTTPError(ex)
50 |
51 | # Parse the json in the correct response.
52 | data = json.loads(response.text)
53 |
54 | # Request went through, but was bad in some way.
55 | if data["stat"] == "fail":
56 | raise APIError(data["message"])
57 |
58 | return data
59 |
60 |
61 | def get_monitors(self, ids=None, show_logs=False,
62 | show_log_alert_contacts=False,
63 | show_alert_contacts=False,
64 | custom_uptime_ratio=False,
65 | show_log_timezone=False):
66 | """
67 | Args
68 | ids
69 | IDs of the monitors to list. If None, then get all contacts. [list]
70 | logs
71 | Show logs [Boolean]
72 | alert_contacts
73 | Show alert contacts [Boolean]
74 | show_monitor_alert_contacts
75 | Show monitors alert contacts [Boolean]
76 | custom_uptime_ratio
77 | Number of days to calculate uptime over [list]
78 | show_log_timezone
79 | Show the timezone for the log times [Boolean]
80 |
81 | Returns
82 | List of Monitor detail objects.
83 |
84 | """
85 |
86 | variables = {}
87 |
88 | if ids:
89 | if any(not isinstance(id, string) for id in ids):
90 | raise TypeError("ids must be strings")
91 |
92 | if any(not re.match(self.ID_PATTERN, id) for id in ids):
93 | raise ValueError("ids must be numeric")
94 |
95 | variables["monitors"] = self.LIST_SEPARATOR.join(ids)
96 |
97 | if show_logs:
98 | variables["logs"] = "1"
99 |
100 | if show_log_timezone:
101 | variables["showTimezone"] = "1"
102 |
103 | if show_log_alert_contacts:
104 | variables["alertContacts"] = "1"
105 |
106 | if show_alert_contacts:
107 | variables["showMonitorAlertContacts"] = "1"
108 |
109 | if custom_uptime_ratio:
110 | if not all(isinstance(n, int) and n > 0 for n in custom_uptime_ratio):
111 | raise TypeError("custom_uptime_ratio must be a list of positive integers")
112 |
113 | variables["customUptimeRatio"] = self.LIST_SEPARATOR.join(str(n) for n in custom_uptime_ratio)
114 |
115 |
116 | data = self.get("getMonitors", **variables)
117 |
118 | monitors = [Monitor(mon, custom_uptime_ratio) for mon in data["monitors"]["monitor"]]
119 |
120 | return monitors
121 |
122 |
123 | def new_monitor(self, name, url, type,
124 | subtype=None,
125 | port=None,
126 | keyword_type=None,
127 | keyword=None,
128 | username=None,
129 | password=None,
130 | alert_contacts=None):
131 | """
132 | Args
133 | name
134 | Human-readable name to assign to the monitor [str].
135 | url
136 | URL [str]
137 | type
138 | Monitor type [int]
139 | subtype
140 | subtype of the monitor [int]
141 | keyword_type
142 | Type of keyword to use (requires keyword be set) [int]
143 | keyword
144 | Keyword to use (requires keyword_type be set)
145 | http_username
146 | Username to use for private site (requires http_password be set)
147 | http_password
148 | Password to use for private site (requires http_username be set)
149 | alert_contacts
150 | Alert contacts to give the monitor [list]
151 |
152 | Returns
153 | ID of monitor created.
154 |
155 | """
156 |
157 | if type not in Monitor.TYPES:
158 | raise ValueError("type must be one of %s" % ", ".join(str(m) for m in Monitor.TYPES.keys()))
159 |
160 | variables = {
161 | "monitorFriendlyName": name,
162 | "monitorURL": url,
163 | "monitorType": str(type),
164 | }
165 |
166 | if subtype is not None:
167 | if subtype not in Monitor.SUBTYPES:
168 | raise ValueError("subtype must be one of %s" % ", ".join(str(m) for m in Monitor.SUBTYPES.keys()))
169 |
170 | variables["monitorSubType"] = str(subtype)
171 |
172 | if port is not None:
173 | variables["monitorPort"] = str(port)
174 |
175 | if keyword_type and keyword:
176 | if keyword_type not in Monitor.KEYWORD_TYPES:
177 | raise ValueError("keyword_type must be one of %s" % ", ".join(str(m) for m in Monitor.KEYWORD_TYPES.keys()))
178 |
179 | variables["monitorKeywordType"] = str(keyword_type)
180 | variables["monitorKeywordValue"] = keyword
181 | elif keyword_type is not None or keyword is not None:
182 | raise ValueError("Requires both keyword_type and keyword if either are specified")
183 |
184 | if username is not None and password is not None:
185 | variables["monitorHTTPUsername"] = username
186 | variables["monitorHTTPPassword"] = password
187 | elif username is not None or password is not None:
188 | raise ValueError("Requires both username and password if either are specified")
189 |
190 | if alert_contacts:
191 | if any(not isinstance(id, string) for id in alert_contacts):
192 | raise TypeError("alert_contacts must be strings")
193 |
194 | if any(not re.match(self.ID_PATTERN, id) for id in alert_contacts):
195 | raise ValueError("alert_contacts must be numeric")
196 |
197 | variables["monitorAlertContacts"] = self.LIST_SEPARATOR.join(alert_contacts)
198 |
199 | data = self.get("newMonitor", **variables)
200 |
201 | return data["monitor"]["id"]
202 |
203 |
204 | def edit_monitor(self, id,
205 | status=None,
206 | name=None,
207 | url=None,
208 | type=None,
209 | subtype=None,
210 | port=None,
211 | keyword_type=None,
212 | keyword=None,
213 | username=None,
214 | password=None,
215 | alert_contacts=None):
216 | """
217 | Args
218 | id
219 | ID number of the monitor to edit [str]
220 | status
221 | Status to set [int]
222 | name
223 | Human-readable name to assign to the monitor.
224 | url
225 | URL to monitor
226 | type
227 | Monitor type [int]
228 | subtype
229 | subtype of the monitor [int]
230 | keyword_type
231 | Type of keyword to use (requires keyword be set) [int]
232 | keyword
233 | Keyword to use (requires keyword_type be set)
234 | username
235 | Username to use for private site (requires http_password be set)
236 | password
237 | Password to use for private site (requires http_username be set)
238 | alert_contacts
239 | Alert contacts to give the monitor [list]
240 |
241 | Returns
242 | ID of monitor edited.
243 |
244 | """
245 |
246 | if not isinstance(id, string):
247 | raise TypeError("id must be a string")
248 |
249 | if not re.match(self.ID_PATTERN, id):
250 | raise ValueError("id must be numeric")
251 |
252 | variables = {
253 | "monitorID": id,
254 | }
255 |
256 | if status is not None:
257 | if status not in Monitor.STATUSES:
258 | raise ValueError("status must be one of %s" % ", ".join(str(m) for m in Monitor.STATUSES.keys()))
259 |
260 | variables["monitorStatus"] = str(status)
261 |
262 | if name is not None:
263 | variables["monitorFriendlyName"] = name
264 |
265 | if url is not None:
266 | variables["monitorURL"] = url
267 |
268 | if type is not None:
269 | if type not in Monitor.TYPES:
270 | raise ValueError("type must be one of %s" % ", ".join(str(m) for m in Monitor.TYPES.keys()))
271 |
272 | variables["monitorType"] = str(type)
273 |
274 | if subtype is not None:
275 | if subtype not in Monitor.SUBTYPES:
276 | raise ValueError("subtype must be one of %s" % ", ".join(str(m) for m in Monitor.SUBTYPES.keys()))
277 |
278 | variables["monitorSubType"] = str(subtype)
279 |
280 | if port is not None:
281 | variables["monitorPort"] = str(port)
282 |
283 | if keyword_type is not None:
284 | if keyword_type not in Monitor.KEYWORD_TYPES:
285 | raise ValueError("keyword_type must be one of %s" % ", ".join(str(m) for m in Monitor.KEYWORD_TYPES.keys()))
286 |
287 | variables["monitorKeywordType"] = str(keyword_type)
288 |
289 | if keyword:
290 | variables["monitorKeywordValue"] = keyword
291 |
292 | if username:
293 | variables["monitorHTTPUsername"] = username
294 |
295 | if password:
296 | variables["monitorHTTPPassword"] = password
297 |
298 | if alert_contacts:
299 | if any(not isinstance(id, string) for id in alert_contacts):
300 | raise TypeError("alert_contacts must be strings")
301 |
302 | if any(not re.match(self.ID_PATTERN, id) for id in alert_contacts):
303 | raise ValueError("alert_contacts must be numeric")
304 |
305 | variables["monitorAlertContacts"] = self.LIST_SEPARATOR.join(alert_contacts)
306 |
307 |
308 | data = self.get("editMonitor", **variables)
309 |
310 | return data["monitor"]["id"]
311 |
312 |
313 | def delete_monitor(self, id):
314 | """
315 | Args
316 | id
317 | ID of the monitor to delete [str]
318 |
319 | Returns
320 | ID of monitor deleted [str]
321 |
322 | """
323 |
324 | if not isinstance(id, string):
325 | raise TypeError("id must be a string")
326 |
327 | if not re.match(self.ID_PATTERN, id):
328 | raise ValueError("id must be numeric")
329 |
330 | data = self.get("deleteMonitor", monitorID=id)
331 |
332 | return data["monitor"]["id"]
333 |
334 |
335 | def get_alert_contacts(self, ids=None):
336 | """
337 | Args
338 | ids
339 | IDs of the alert contacts to list. If None, then get all contacts [list.
340 |
341 | Returns
342 | List of AlertContact detail objects.
343 |
344 | """
345 |
346 | variables = {}
347 |
348 | if ids is not None:
349 | if any(not isinstance(id, string) for id in ids):
350 | raise TypeError("ids must be strings")
351 |
352 | if any(not re.match(self.ID_PATTERN, id) for id in ids):
353 | raise ValueError("ids must be numeric")
354 |
355 | variables["alertcontacts"] = self.LIST_SEPARATOR.join(ids)
356 |
357 | data = self.get("getAlertContacts", **variables)
358 |
359 | alerts = [AlertContact(ac) for ac in data["alertcontacts"]["alertcontact"]]
360 |
361 | return alerts
362 |
363 |
364 | def new_alert_contact(self, type, value):
365 | """
366 | Args
367 | type
368 | Type of the new alert to create [int]
369 | value
370 | email address (or ) to alert [str]
371 |
372 | Returns
373 | ID of alert contact created [str]
374 |
375 | """
376 |
377 | if type not in AlertContact.TYPES:
378 | raise ValueError("type must be one of %s" % ", ".join(str(t) for t in AlertContact.TYPES))
379 |
380 | if not isinstance(value, string):
381 | raise TypeError("value must be a string")
382 |
383 | data = self.get("newAlertContact", alertContactType=str(type), alertContactValue=value)
384 |
385 | return data["alertcontact"]["id"]
386 |
387 |
388 | def delete_alert_contact(self, id):
389 | """
390 | Args
391 | id
392 | ID of the alert contact to delete [str]
393 |
394 | Returns
395 | ID of alert contact deleted [str]
396 |
397 | """
398 |
399 | if not isinstance(id, string):
400 | raise TypeError("id must be a string")
401 |
402 | if not re.match(self.ID_PATTERN, id):
403 | raise ValueError("id must be numeric")
404 |
405 | data = self.get("deleteAlertContact", alertContactID=id)
406 |
407 | return data["alertcontact"]["id"]
--------------------------------------------------------------------------------
/uptimerobot/log.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | from datetime import datetime
4 |
5 | from termcolor import colored
6 |
7 | from .alert_contact import AlertContact
8 |
9 | class Log(object):
10 | TIMESTAMP_FORMAT = "%m/%d/%Y %H:%M:%S"
11 | TIMESTAMP_FORMAT_ALT = "%m/%d/%Y %H:%M:%S %p"
12 |
13 |
14 | class Type:
15 | DOWN = 1
16 | UP = 2
17 | STARTED = 98
18 | PAUSED = 99
19 |
20 | TYPES = {
21 | Type.DOWN: "down",
22 | Type.UP: "up",
23 | Type.STARTED: "started",
24 | Type.PAUSED: "paused",
25 | }
26 |
27 | def __init__(self, data):
28 | # Sometimes the alert data has no 'value'!
29 | alert_data = filter(lambda ac: ac.get("value"), data.get("alertcontact", []))
30 |
31 | self.alert_contacts = [AlertContact(ac) for ac in alert_data]
32 |
33 | try:
34 | self.datetime = datetime.strptime(data["datetime"], self.TIMESTAMP_FORMAT_ALT)
35 | except ValueError as ex:
36 | self.datetime = datetime.strptime(data["datetime"], self.TIMESTAMP_FORMAT)
37 |
38 | self.type = int(data["type"])
39 |
40 |
41 | type_str = property(lambda self: self.TYPES[self.type])
42 |
43 |
44 | def dump(self):
45 | if self.type == self.Type.UP:
46 | color = "green"
47 | elif self.type == self.Type.DOWN:
48 | color = "red"
49 | else:
50 | color = "yellow"
51 |
52 | status = colored(self.type_str.title(), color)
53 | print(" %s [%s]" % (self.datetime.strftime(self.TIMESTAMP_FORMAT), status))
54 |
55 | if self.alert_contacts:
56 | for alert in self.alert_contacts:
57 | alert.dump()
--------------------------------------------------------------------------------
/uptimerobot/monitor.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import, division, print_function, unicode_literals
2 |
3 | from .log import Log
4 | from .alert_contact import AlertContact
5 | from termcolor import colored
6 |
7 |
8 | class Monitor(object):
9 | class Type:
10 | HTTP = 1
11 | KEYWORD = 2
12 | PING = 3
13 | PORT = 4
14 |
15 | TYPES = {
16 | Type.HTTP: "http(s)",
17 | Type.KEYWORD: "keyword",
18 | Type.PING: "ping",
19 | Type.PORT: "port",
20 | }
21 |
22 | class Subtype:
23 | HTTP = 1
24 | HTTPS = 2
25 | FTP = 3
26 | SMTP = 4
27 | POP3 = 5
28 | IMAP = 6
29 | CUSTOM = 99
30 |
31 |
32 | SUBTYPES = {
33 | Subtype.HTTP: "http",
34 | Subtype.HTTPS: "https",
35 | Subtype.FTP: "ftp",
36 | Subtype.SMTP: "smtp",
37 | Subtype.POP3: "pop3",
38 | Subtype.IMAP: "imap",
39 | Subtype.CUSTOM: "custom",
40 | }
41 |
42 | class KeywordType:
43 | EXISTS = 1
44 | NOT_EXISTS = 2
45 |
46 | KEYWORD_TYPES = {
47 | KeywordType.EXISTS: "exists",
48 | KeywordType.NOT_EXISTS: "not exists",
49 | }
50 |
51 | class Status:
52 | PAUSED = 0
53 | NOT_CHECKED_YET = 1
54 | UP = 2
55 | SEEMS_DOWN = 8
56 | DOWN = 9
57 |
58 | STATUSES = {
59 | Status.PAUSED: "paused",
60 | Status.NOT_CHECKED_YET: "not checked yet",
61 | Status.UP: "up",
62 | Status.SEEMS_DOWN: "seems down",
63 | Status.DOWN: "down",
64 | }
65 |
66 | def __init__(self, data, custom_uptime_ratio_periods=[]):
67 | self.alert_contacts = [AlertContact(ac) for ac in data.get("alertcontact", [])]
68 | self.logs = [Log(log) for log in data.get("log", [])]
69 | self.custom_uptime_ratio_periods = custom_uptime_ratio_periods
70 |
71 | self.id = data["id"]
72 | self.name = data["friendlyname"]
73 | self.url = data["url"]
74 | self.type = int(data["type"])
75 | self.subtype = int(data["subtype"]) if data["subtype"] else None
76 |
77 | self.keyword_type = int(data["keywordtype"]) if data["keywordtype"] else None
78 | self.keyword = data["keywordvalue"]
79 |
80 | self.http_username = data["httpusername"]
81 | self.http_password = data["httppassword"]
82 | self.port = int(data["port"]) if data["port"] else None
83 |
84 | self.status = int(data["status"])
85 | self.all_time_uptime_ratio = float(data["alltimeuptimeratio"])
86 |
87 | if "customuptimeratio" in data:
88 | self.custom_uptime_ratio = [float(n) for n in data["customuptimeratio"].split("-")]
89 | else:
90 | self.custom_uptime_ratio = []
91 |
92 |
93 | @property
94 | def subtype_str(self):
95 | if self.subtype:
96 | return self.SUBTYPES[self.subtype]
97 | else:
98 | return None
99 |
100 | keyword_type_str = property(lambda self: self.KEYWORD_TYPES[self.keyword_type])
101 | type_str = property(lambda self: self.TYPES[self.type])
102 | status_str = property(lambda self: self.STATUSES[self.status])
103 |
104 |
105 | def dump(self):
106 | if self.status in [self.Status.UP]:
107 | color = "green"
108 | elif self.status in [self.Status.SEEMS_DOWN, self.Status.DOWN]:
109 | color = "red"
110 | else:
111 | color = "yellow"
112 |
113 | status = colored(self.status_str.title(), color)
114 | print("%s [%s] #%s" % (self.name, status, self.id))
115 |
116 | if self.port:
117 | print("URL: %s:%d" % (self.url, self.port))
118 | else:
119 | print("URL: %s" % self.url)
120 |
121 |
122 | if self.http_username:
123 | print("User: %s (%s)" % self.http_username, self.http_password)
124 |
125 | print("Type: %s" % self.type_str)
126 |
127 | if self.subtype:
128 | print("Subtype: %s" % self.subtype_str)
129 |
130 | print("All Time Uptime Ratio: %.2f%%" % self.all_time_uptime_ratio)
131 |
132 | if self.custom_uptime_ratio:
133 | for period, ratio in zip(self.custom_uptime_ratio_periods, self.custom_uptime_ratio):
134 | str = "Uptime Ratio over %d hour%s:" % (period, "" if period == 1 else "s")
135 | print("%-30s %.2f%%" % (str, ratio))
136 |
137 | if self.keyword_type:
138 | print("Keyword: %s (%s)" % (self.keyword, self.keyword_type_str))
139 |
140 | if self.alert_contacts:
141 | print()
142 | print("Alert contacts:")
143 | for alert in self.alert_contacts:
144 | alert.dump()
145 |
146 | if self.logs:
147 | print()
148 | print("Log:")
149 | for log in self.logs:
150 | log.dump()
151 | print()
--------------------------------------------------------------------------------