├── .circleci
└── config.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── circle.yml
├── registry.py
├── requirements-build.txt
├── requirements-ci.txt
└── test.py
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | # Python CircleCI 2.0 configuration file
2 | #
3 | # Check https://circleci.com/docs/2.0/language-python/ for more details
4 | #
5 | version: 2
6 | jobs:
7 | build:
8 | docker:
9 | # specify the version you desire here
10 | # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers`
11 | - image: circleci/python:3.6.1
12 |
13 | # Specify service dependencies here if necessary
14 | # CircleCI maintains a library of pre-built images
15 | # documented at https://circleci.com/docs/2.0/circleci-images/
16 | # - image: circleci/postgres:9.4
17 |
18 | working_directory: ~/repo
19 |
20 | steps:
21 | - checkout
22 |
23 | # Download and cache dependencies
24 | - restore_cache:
25 | keys:
26 | - v1-dependencies-{{ checksum "requirements-ci.txt" }}
27 | # fallback to using the latest cache if no exact match is found
28 | - v1-dependencies-
29 |
30 | - run:
31 | name: install dependencies
32 | command: |
33 | python3 -m venv venv
34 | . venv/bin/activate
35 | pip install -r requirements-ci.txt
36 |
37 | - save_cache:
38 | paths:
39 | - ./venv
40 | key: v1-dependencies-{{ checksum "requirements-ci.txt" }}
41 |
42 | # run tests!
43 | # this example uses Django's built-in test-runner
44 | # other common Python testing frameworks include pytest and nose
45 | # https://pytest.org
46 | # https://nose.readthedocs.io
47 | - run:
48 | name: run tests
49 | command: |
50 | . venv/bin/activate
51 | coverage run --include=test.py,registry.py test.py
52 |
53 | - run:
54 | name: generate report
55 | command: |
56 | . venv/bin/activate
57 | mkdir -p /tmp/coverage
58 | coverage html -d /tmp/coverage
59 | mv .coverage /tmp/coverage
60 |
61 | - store_artifacts:
62 | path: /tmp/coverage
63 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by .ignore support plugin (hsz.mobi)
2 | .gitignore
3 | .idea/
4 | /.vscode
5 | *.pyc
6 | venv/
7 | pyvenv.cfg
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:2.7-alpine
2 |
3 | ADD requirements-build.txt /
4 |
5 | RUN pip install -r /requirements-build.txt
6 |
7 | ADD registry.py /
8 |
9 | ENTRYPOINT ["/registry.py"]
10 |
--------------------------------------------------------------------------------
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://circleci.com/gh/andrey-pohilko/registry-cli/tree/master)
2 |
3 | # registry-cli
4 | registry.py is a script for easy manipulation of docker-registry from command line (and from scripts)
5 |
6 | ## Table of Contents
7 |
8 | * [Installation](#installation)
9 | * [Docker image](#docker-image)
10 | * [Python script](#python-script)
11 | * [Listing images](#listing-images)
12 | * [Username and password](#username-and-password)
13 | * [Deleting images](#deleting-images)
14 | * [Disable ssl verification](#disable-ssl-verification)
15 | * [Nexus docker registry](#nexus-docker-registry)
16 | * [Important notes](#important-notes)
17 | * [garbage-collection in docker-registry](#garbage-collection-in-docker-registry)
18 | * [enable image deletion in docker-registry](#enable-image-deletion-in-docker-registry)
19 | * [Contribution](#contribution)
20 |
21 | ## Installation
22 |
23 | ### Docker image
24 |
25 | You can download ready-made docker image with the script and all python dependencies pre-installed:
26 |
27 | ```
28 | docker pull anoxis/registry-cli
29 | ```
30 |
31 | In this case, replace `registry.py` with `docker run --rm anoxis/registry-cli`
32 | in all commands below, e.g.
33 | ```
34 | docker run --rm anoxis/registry-cli -r http://example.com:5000
35 | ```
36 |
37 | Note: when you use the docker image and registry on the same computer (registry is on localhost), then due to internal network created by docker you have to link to the registry's network and refer registry container by its name, not localhost.
38 | E.g. your registry container is named "registry",
39 | then the command to launch registry-cli would be
40 | ```bash
41 | docker run --rm --link registry anoxis/registry-cli -r http://registry:5000
42 | ```
43 | ### python script
44 |
45 | Download registry.py and set it as executable
46 | ```
47 | chmod 755 registry.py
48 | ```
49 |
50 | Install dependencies:
51 | ```
52 | sudo pip install -r requirements-build.txt
53 | ```
54 |
55 | ## Listing images
56 |
57 | The below command will list all images and all tags in your registry:
58 | ```
59 | registry.py -l user:pass -r https://example.com:5000
60 | ```
61 |
62 | List all images, tags and layers:
63 | ```
64 | registry.py -l user:pass -r https://example.com:5000 --layers
65 | ```
66 |
67 | List particular image(s) or image:tag (all tags of ubuntu and alpine in this example)
68 | ```
69 | registry.py -l user:pass -r https://example.com:5000 -i ubuntu alpine
70 | ```
71 |
72 | Same as above but with layers
73 | ```
74 | registry.py -l user:pass -r https://example.com:5000 -i ubuntu alpine --layers
75 | ```
76 |
77 | ## Username and password
78 |
79 | It is optional, you can omit it in case if you use insecure registry without authentication (up to you,
80 | but its really insecure; make sure you protect your entire registry from anyone)
81 |
82 | username and password pair can be provided in the following forms
83 | ```
84 | -l username:password
85 | -l 'username':'password'
86 | -l "username":"password"
87 | ```
88 | Username cannot contain colon (':') (I don't think it will contain ever, but anyway I warned you).
89 | Password, in its turn, can contain as many colons as you wish.
90 |
91 |
92 | ## Deleting images
93 |
94 | Keep only last 10 versions (useful for CI):
95 | Delete all tags of all images but keep last 10 tags (you can put this command to your build script
96 | after building images)
97 | ```
98 | registry.py -l user:pass -r https://example.com:5000 --delete
99 | ```
100 | If number of tags is less than 10 it will not delete any
101 |
102 | You can change the number of tags to keep, e.g. 5:
103 | ```
104 | registry.py -l user:pass -r https://example.com:5000 --delete --num 5
105 | ```
106 |
107 | You may also specify tags to be deleted using a list of regexp based names.
108 | The following command would delete all tags containing "snapshot-" and beginning with "stable-" and a 4 digit number:
109 |
110 | ```
111 | registry.py -l user:pass -r https://example.com:5000 --delete --tags-like "snapshot-" "^stable-[0-9]{4}.*"
112 | ```
113 |
114 | As one manifest may be referenced by more than one tag, you may add tags, whose manifests should NOT be deleted.
115 | A tag that would otherwise be deleted, but whose manifest references one of those "kept" tags, is spared for deletion.
116 | In the following case, all tags beginning with "snapshot-" will be deleted, save those whose manifest point to "stable" or "latest":
117 |
118 | ```
119 | registry.py -l user:pass -r https://example.com:5000 --delete --tags-like "snapshot-" --keep-tags "stable" "latest"
120 | ```
121 | The last parameter is also available as regexp option with `--keep-tags-like`.
122 |
123 |
124 | Delete all tags for particular image (e.g. delete all ubuntu tags):
125 | ```
126 | registry.py -l user:pass -r https://example.com:5000 -i ubuntu --delete-all
127 | ```
128 |
129 | Delete all tags for all images (do you really want to do it?):
130 | ```
131 | registry.py -l user:pass -r https://example.com:5000 --delete-all --dry-run
132 | ```
133 |
134 | Delete all tags by age in hours for the particular image (e.g. older than 24 hours, with `--keep-tags` and `--keep-tags-like` options, `--dry-run` for safe).
135 | ```
136 | registry.py -r https://example.com:5000 -i api-docs-origin/master --dry-run --delete-by-hours 24 --keep-tags c59c02c25f023263fd4b5d43fc1ff653f08b3d4x --keep-tags-like late
137 | ```
138 |
139 | Note that deleting by age will not prevent more recent tags from being deleted if there are more than 10 (or specified `--num` value). In order to keep all tags within a designated period, use the `--keep-by-hours` flag:
140 | ```
141 | registry.py -r https://example.com:5000 --dry-run --delete --keep-by-hours 72 --keep-tags-like latest
142 | ```
143 | ## Disable ssl verification
144 |
145 | If you are using docker registry with a self signed ssl certificate, you can disable ssl verification:
146 | ```
147 | registry.py -l user:pass -r https://example.com:5000 --no-validate-ssl
148 | ```
149 |
150 | ## Nexus docker registry
151 |
152 | Add `--digest-method` flag
153 |
154 | ```
155 | registry.py -l user:pass -r https://example.com:5000 --digest-method GET
156 | ```
157 |
158 | ## Important notes:
159 |
160 | ### garbage-collection in docker-registry
161 | 1. docker registry API does not actually delete tags or images, it marks them for later
162 | garbage collection. So, make sure you run something like below
163 | (or put them in your crontab):
164 | ```
165 | cd [path-where-your-docker-compose.yml]
166 | docker-compose stop registry
167 | docker-compose run --rm \
168 | registry bin/registry garbage-collect --delete-untagged \
169 | /etc/docker/registry/config.yml
170 | docker-compose up -d registry
171 | ```
172 | or (if you are not using docker-compose):
173 | ```
174 | docker stop registry:2
175 | docker run --rm registry:2 bin/registry garbage-collect --delete-untagged \
176 | /etc/docker/registry/config.yml
177 | docker start registry:2
178 | ```
179 | for more detail on garbage collection read here:
180 | https://docs.docker.com/registry/garbage-collection/
181 |
182 | ### enable image deletion in docker-registry
183 | Make sure to enable it by either creating environment variable
184 | `REGISTRY_STORAGE_DELETE_ENABLED: "true"`
185 | or adding relevant configuration option to the docker-registry's config.yml.
186 | For more on docker-registry configuration, read here:
187 | https://docs.docker.com/registry/configuration/
188 |
189 | You may get `Error 405` message from script (`Functionality not supported`) when this option is not enabled.
190 |
191 |
192 | ## Contribution
193 | You are very welcome to contribute to this script. Of course, when making changes,
194 | please include your changes into `test.py` and run tests to check that your changes
195 | do not break existing functionality.
196 |
197 | For tests to work, more libraries are needed
198 | ```
199 | pip install -r requirements-ci.txt
200 | ```
201 |
202 | Running tests is as simple as
203 | ```
204 | python test.py
205 | ```
206 |
207 | Test will print few error messages, like so
208 | ```
209 | Testing started at 9:31 AM ...
210 | tag digest not found: 400
211 | error 400
212 | ```
213 | this is ok, because test simulates invalid inputs also.
214 |
215 | # Contact
216 |
217 | Please feel free to contact me at anoxis@gmail.com if you wish to add more functionality
218 | or want to contribute.
219 |
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | dependencies:
2 | pre:
3 | - pip install -r requirements-ci.txt
4 |
5 | test:
6 | override:
7 | - coverage run --include=test.py,registry.py test.py
8 | post:
9 | - mkdir -p $CIRCLE_ARTIFACTS/coverage
10 | - coverage html -d $CIRCLE_ARTIFACTS/coverage
11 | - mv .coverage $CIRCLE_ARTIFACTS
12 |
--------------------------------------------------------------------------------
/registry.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | ######
4 | # github repository: https://github.com/andrey-pohilko/registry-cli
5 | #
6 | # please read more details about the script, usage options and license info there
7 | ######
8 |
9 | import requests
10 | import ast
11 | from requests.packages.urllib3.exceptions import InsecureRequestWarning
12 | import json
13 | import pprint
14 | import base64
15 | import re
16 | import sys
17 | import os
18 | import argparse
19 | import www_authenticate
20 | from datetime import timedelta, datetime as dt
21 | from getpass import getpass
22 | from multiprocessing.pool import ThreadPool
23 | from dateutil.parser import parse
24 | from dateutil.tz import tzutc
25 |
26 | # this is a registry manipulator, can do following:
27 | # - list all images (including layers)
28 | # - delete images
29 | # - all except last N images
30 | # - all images and/or tags
31 | #
32 | # run
33 | # registry.py -h
34 | # to get more help
35 | #
36 | # important: after removing the tags, run the garbage collector
37 | # on your registry host:
38 | # docker-compose -f [path_to_your_docker_compose_file] run \
39 | # registry bin/registry garbage-collect \
40 | # /etc/docker/registry/config.yml
41 | #
42 | # or if you are not using docker-compose:
43 | # docker run registry:2 bin/registry garbage-collect \
44 | # /etc/docker/registry/config.yml
45 | #
46 | # for more detail on garbage collection read here:
47 | # https://docs.docker.com/registry/garbage-collection/
48 |
49 |
50 | # number of image versions to keep
51 | CONST_KEEP_LAST_VERSIONS = 10
52 |
53 | # print debug messages
54 | DEBUG = False
55 |
56 | # this class is created for testing
57 | class Requests:
58 |
59 | def request(self, method, url, **kwargs):
60 | return requests.request(method, url, **kwargs)
61 |
62 | def bearer_request(self, method, url, auth, **kwargs):
63 | global DEBUG
64 | if DEBUG: print("[debug][funcname]: bearer_request()")
65 |
66 | if DEBUG:
67 | print('[debug][registry][request]: {0} {1}'.format(method, url))
68 | if 'Authorization' in kwargs['headers']:
69 | print('[debug][registry][request]: Authorization header:')
70 |
71 | token_parsed = kwargs['headers']['Authorization'].split('.')
72 | pprint.pprint(ast.literal_eval(decode_base64(token_parsed[0])))
73 | pprint.pprint(ast.literal_eval(decode_base64(token_parsed[1])))
74 |
75 | res = requests.request(method, url, **kwargs)
76 | if str(res.status_code)[0] == '2':
77 | if DEBUG: print("[debug][registry] accepted")
78 | return (res, kwargs['headers']['Authorization'])
79 |
80 | if res.status_code == 401:
81 | if DEBUG: print("[debug][registry] Access denied. Refreshing token...")
82 | oauth = www_authenticate.parse(res.headers['Www-Authenticate'])
83 |
84 | if DEBUG:
85 | print('[debug][auth][answer] Auth header:')
86 | pprint.pprint(oauth['bearer'])
87 |
88 | # print('[info] retreiving bearer token for {0}'.format(oauth['bearer']['scope']))
89 | request_url = '{0}'.format(oauth['bearer']['realm'])
90 | query_separator = '?'
91 | if 'service' in oauth['bearer']:
92 | request_url += '{0}service={1}'.format(query_separator, oauth['bearer']['service'])
93 | query_separator = '&'
94 | if 'scope' in oauth['bearer']:
95 | request_url += '{0}scope={1}'.format(query_separator, oauth['bearer']['scope'])
96 |
97 | if DEBUG:
98 | print('[debug][auth][request] Refreshing auth token: POST {0}'.format(request_url))
99 |
100 | if args.auth_method == 'GET':
101 | try_oauth = requests.get(request_url, auth=auth, **kwargs)
102 | else:
103 | try_oauth = requests.post(request_url, auth=auth, **kwargs)
104 |
105 | try:
106 | oauth_response = ast.literal_eval(try_oauth._content.decode('utf-8'))
107 | token = oauth_response['access_token'] if 'access_token' in oauth_response else oauth_response['token']
108 | except SyntaxError:
109 | print('\n\n[ERROR] couldnt accure token: {0}'.format(try_oauth._content))
110 | sys.exit(1)
111 |
112 | if DEBUG:
113 | print('[debug][auth] token issued: ')
114 | token_parsed=token.split('.')
115 | pprint.pprint(ast.literal_eval(decode_base64(token_parsed[0])))
116 | pprint.pprint(ast.literal_eval(decode_base64(token_parsed[1])))
117 |
118 | kwargs['headers']['Authorization'] = 'Bearer {0}'.format(token)
119 | else:
120 | return (res, kwargs['headers']['Authorization'])
121 |
122 | res = requests.request(method, url, **kwargs)
123 | return (res, kwargs['headers']['Authorization'])
124 |
125 |
126 | def natural_keys(text):
127 | """
128 | alist.sort(key=natural_keys) sorts in human order
129 | http://nedbatchelder.com/blog/200712/human_sorting.html
130 | (See Toothy's implementation in the comments)
131 | """
132 |
133 | def __atoi(text):
134 | return int(text) if text.isdigit() else text
135 |
136 | return [__atoi(c) for c in re.split('(\d+)', text)]
137 |
138 |
139 | def decode_base64(data):
140 | """Decode base64, padding being optional.
141 |
142 | :param data: Base64 data as an ASCII byte string
143 | :returns: The decoded byte string.
144 |
145 | """
146 | data = data.replace('Bearer ','')
147 | # print('[debug] base64 string to decode:\n{0}'.format(data))
148 | missing_padding = len(data) % 4
149 | if missing_padding != 0:
150 | data += b'='* (4 - missing_padding)
151 | return base64.decodestring(data)
152 |
153 |
154 | def get_error_explanation(context, error_code):
155 | error_list = {"delete_tag_405": 'You might want to set REGISTRY_STORAGE_DELETE_ENABLED: "true" in your registry',
156 | "get_tag_digest_404": "Try adding flag --digest-method=GET"}
157 |
158 | key = "%s_%s" % (context, error_code)
159 |
160 | if key in error_list.keys():
161 | return(error_list[key])
162 |
163 | return ''
164 |
165 | def get_auth_schemes(r,path):
166 | """ Returns list of auth schemes(lowcased) if www-authenticate: header exists
167 | returns None if no header found
168 | - www-authenticate: basic
169 | - www-authenticate: bearer
170 | """
171 |
172 | if DEBUG: print("[debug][funcname]: get_auth_schemes()")
173 |
174 | try_oauth = requests.head('{0}{1}'.format(r.hostname,path), verify=not r.no_validate_ssl)
175 |
176 | if 'Www-Authenticate' in try_oauth.headers:
177 | oauth = www_authenticate.parse(try_oauth.headers['Www-Authenticate'])
178 | if DEBUG:
179 | print('[debug][docker] Auth schemes found:{0}'.format([m for m in oauth]))
180 | return [m.lower() for m in oauth]
181 | if DEBUG:
182 | print('[debug][docker] No Auth schemes found')
183 | return []
184 |
185 | # class to manipulate registry
186 | class Registry:
187 |
188 | # this is required for proper digest processing
189 | HEADERS = {"Accept":
190 | "application/vnd.docker.distribution.manifest.v2+json"}
191 |
192 | def __init__(self):
193 | self.username = None
194 | self.password = None
195 | self.auth_schemes = []
196 | self.hostname = None
197 | self.no_validate_ssl = False
198 | self.http = None
199 | self.last_error = None
200 | self.digest_method = "HEAD"
201 |
202 | def parse_login(self, login):
203 | if login is not None:
204 |
205 | if ':' not in login:
206 | self.last_error = "Please provide -l in the form USER:PASSWORD"
207 | return (None, None)
208 |
209 | self.last_error = None
210 | (username, password) = login.split(':', 1)
211 | username = username.strip('"').strip("'")
212 | password = password.strip('"').strip("'")
213 | return (username, password)
214 |
215 | return (None, None)
216 |
217 |
218 | @staticmethod
219 | def _create(host, login, no_validate_ssl, digest_method = "HEAD"):
220 | r = Registry()
221 |
222 | (r.username, r.password) = r.parse_login(login)
223 | if r.last_error is not None:
224 | print(r.last_error)
225 | sys.exit(1)
226 |
227 | r.hostname = host
228 | r.no_validate_ssl = no_validate_ssl
229 | r.http = Requests()
230 | r.digest_method = digest_method
231 | return r
232 |
233 | @staticmethod
234 | def create(*args, **kw):
235 | return Registry._create(*args, **kw)
236 |
237 |
238 | def send(self, path, method="GET"):
239 | if 'bearer' in self.auth_schemes:
240 | (result, self.HEADERS['Authorization']) = self.http.bearer_request(
241 | method, "{0}{1}".format(self.hostname, path),
242 | auth=(('', '') if self.username in ["", None]
243 | else (self.username, self.password)),
244 | headers=self.HEADERS,
245 | verify=not self.no_validate_ssl)
246 | else:
247 | result = self.http.request(
248 | method, "{0}{1}".format(self.hostname, path),
249 | headers=self.HEADERS,
250 | auth=(None if self.username == ""
251 | else (self.username, self.password)),
252 | verify=not self.no_validate_ssl)
253 |
254 | # except Exception as error:
255 | # print("cannot connect to {0}\nerror {1}".format(
256 | # self.hostname,
257 | # error))
258 | # sys.exit(1)
259 | if str(result.status_code)[0] == '2':
260 | self.last_error = None
261 | return result
262 |
263 | self.last_error = result.status_code
264 | return None
265 |
266 | def list_images(self):
267 | result = self.send('/v2/_catalog?n=10000')
268 | if result is None:
269 | return []
270 |
271 | return json.loads(result.text)['repositories']
272 |
273 | def list_tags(self, image_name):
274 | result = self.send("/v2/{0}/tags/list".format(image_name))
275 | if result is None:
276 | return []
277 |
278 | try:
279 | tags_list = json.loads(result.text)['tags']
280 | except ValueError:
281 | self.last_error = "list_tags: invalid json response"
282 | return []
283 |
284 | if tags_list is not None:
285 | tags_list.sort(key=natural_keys)
286 |
287 | return tags_list
288 |
289 | # def list_tags_like(self, tag_like, args_tags_like):
290 | # for tag_like in args_tags_like:
291 | # print("tag like: {0}".format(tag_like))
292 | # for tag in all_tags_list:
293 | # if re.search(tag_like, tag):
294 | # print("Adding {0} to tags list".format(tag))
295 |
296 | def get_tag_digest(self, image_name, tag):
297 | image_headers = self.send("/v2/{0}/manifests/{1}".format(
298 | image_name, tag), method=self.digest_method)
299 |
300 | if image_headers is None:
301 | print(" tag digest not found: {0}.".format(self.last_error))
302 | print(get_error_explanation("get_tag_digest", self.last_error))
303 | return None
304 |
305 | tag_digest = image_headers.headers['Docker-Content-Digest']
306 |
307 | return tag_digest
308 |
309 | def delete_tag(self, image_name, tag, dry_run, tag_digests_to_ignore):
310 | if dry_run:
311 | print('would delete tag {0}'.format(tag))
312 | return False
313 |
314 | tag_digest = self.get_tag_digest(image_name, tag)
315 |
316 | if tag_digest in tag_digests_to_ignore:
317 | print("Digest {0} for tag {1} is referenced by another tag or has already been deleted and will be ignored".format(
318 | tag_digest, tag))
319 | return True
320 |
321 | if tag_digest is None:
322 | return False
323 |
324 | delete_result = self.send("/v2/{0}/manifests/{1}".format(
325 | image_name, tag_digest), method="DELETE")
326 |
327 | if delete_result is None:
328 | print("failed, error: {0}".format(self.last_error))
329 | print(get_error_explanation("delete_tag", self.last_error))
330 | return False
331 |
332 | tag_digests_to_ignore.append(tag_digest)
333 |
334 | print("done")
335 | return True
336 |
337 |
338 | def list_tag_layers(self, image_name, tag):
339 | layers_result = self.send("/v2/{0}/manifests/{1}".format(
340 | image_name, tag))
341 |
342 | if layers_result is None:
343 | print("error {0}".format(self.last_error))
344 | return []
345 |
346 | json_result = json.loads(layers_result.text)
347 | if json_result['schemaVersion'] == 1:
348 | layers = json_result['fsLayers']
349 | else:
350 | layers = json_result['layers']
351 |
352 | return layers
353 |
354 | def get_tag_config(self, image_name, tag):
355 | config_result = self.send(
356 | "/v2/{0}/manifests/{1}".format(image_name, tag))
357 |
358 | if config_result is None:
359 | print(" tag digest not found: {0}".format(self.last_error))
360 | return []
361 |
362 | json_result = json.loads(config_result.text)
363 | if json_result['schemaVersion'] == 1:
364 | print("Docker schemaVersion 1 isn't supported for deleting by age now")
365 | sys.exit(1)
366 | return json_result['config']
367 |
368 | def get_image_age(self, image_name, image_config):
369 | container_header = {"Accept": "{0}".format(
370 | image_config['mediaType'])}
371 |
372 | if 'bearer' in self.auth_schemes:
373 | container_header['Authorization'] = self.HEADERS['Authorization']
374 | (response, self.HEADERS['Authorization']) = self.http.bearer_request("GET", "{0}{1}".format(self.hostname, "/v2/{0}/blobs/{1}".format(
375 | image_name, image_config['digest'])),
376 | auth=(('', '') if self.username in ["", None]
377 | else (self.username, self.password)),
378 | headers=container_header,
379 | verify=not self.no_validate_ssl)
380 | else:
381 | response = self.http.request("GET", "{0}{1}".format(self.hostname, "/v2/{0}/blobs/{1}".format(
382 | image_name, image_config['digest'])),
383 | headers=container_header,
384 | auth=(None if self.username == ""
385 | else (self.username, self.password)),
386 | verify=not self.no_validate_ssl)
387 |
388 | if str(response.status_code)[0] == '2':
389 | self.last_error = None
390 | image_age = json.loads(response.text)
391 | return image_age['created']
392 | print(" blob not found: {0}".format(self.last_error))
393 | self.last_error = response.status_code
394 | return []
395 |
396 |
397 | def parse_args(args=None):
398 | parser = argparse.ArgumentParser(
399 | description="List or delete images from Docker registry",
400 | formatter_class=argparse.RawDescriptionHelpFormatter,
401 | epilog=("""
402 | IMPORTANT: after removing the tags, run the garbage collector
403 | on your registry host:
404 |
405 | docker-compose -f [path_to_your_docker_compose_file] run \\
406 | registry bin/registry garbage-collect \\
407 | /etc/docker/registry/config.yml
408 |
409 | or if you are not using docker-compose:
410 |
411 | docker run registry:2 bin/registry garbage-collect \\
412 | /etc/docker/registry/config.yml
413 |
414 | for more detail on garbage collection read here:
415 | https://docs.docker.com/registry/garbage-collection/
416 | """))
417 | parser.add_argument(
418 | '-l', '--login',
419 | help="Login and password for access to docker registry",
420 | required=False,
421 | metavar="USER:PASSWORD")
422 |
423 | parser.add_argument(
424 | '-w', '--read-password',
425 | help="Read password from stdin (and prompt if stdin is a TTY); " +
426 | "the final line-ending character(s) will be removed; " +
427 | "the :PASSWORD portion of the -l option is not required and " +
428 | "will be ignored",
429 | action='store_const',
430 | default=False,
431 | const=True)
432 |
433 | parser.add_argument(
434 | '-r', '--host',
435 | help="Hostname for registry server, e.g. https://example.com:5000",
436 | required=True,
437 | metavar="URL")
438 |
439 | parser.add_argument(
440 | '-d', '--delete',
441 | help=('If specified, delete all but last {0} tags '
442 | 'of all images').format(CONST_KEEP_LAST_VERSIONS),
443 | action='store_const',
444 | default=False,
445 | const=True)
446 |
447 | parser.add_argument(
448 | '-n', '--num',
449 | help=('Set the number of tags to keep'
450 | '({0} if not set)').format(CONST_KEEP_LAST_VERSIONS),
451 | default=CONST_KEEP_LAST_VERSIONS,
452 | nargs='?',
453 | metavar='N')
454 |
455 | parser.add_argument(
456 | '--debug',
457 | help=('Turn debug output'),
458 | action='store_const',
459 | default=False,
460 | const=True)
461 |
462 | parser.add_argument(
463 | '--dry-run',
464 | help=('If used in combination with --delete,'
465 | 'then images will not be deleted'),
466 | action='store_const',
467 | default=False,
468 | const=True)
469 |
470 | parser.add_argument(
471 | '-i', '--image',
472 | help='Specify images and tags to list/delete',
473 | nargs='+',
474 | metavar="IMAGE:[TAG]")
475 |
476 | parser.add_argument(
477 | '--images-like',
478 | nargs='+',
479 | help="List of images (regexp check) that will be handled",
480 | required=False,
481 | default=[])
482 |
483 | parser.add_argument(
484 | '--keep-tags',
485 | nargs='+',
486 | help="List of tags that will be omitted from deletion if used in combination with --delete or --delete-all",
487 | required=False,
488 | default=[])
489 |
490 | parser.add_argument(
491 | '--tags-like',
492 | nargs='+',
493 | help="List of tags (regexp check) that will be handled",
494 | required=False,
495 | default=[])
496 |
497 | parser.add_argument(
498 | '--keep-tags-like',
499 | nargs='+',
500 | help="List of tags (regexp check) that will be omitted from deletion if used in combination with --delete or --delete-all",
501 | required=False,
502 | default=[])
503 |
504 | parser.add_argument(
505 | '--no-validate-ssl',
506 | help="Disable ssl validation",
507 | action='store_const',
508 | default=False,
509 | const=True)
510 |
511 | parser.add_argument(
512 | '--delete-all',
513 | help="Will delete all tags. Be careful with this!",
514 | const=True,
515 | default=False,
516 | action="store_const")
517 |
518 | parser.add_argument(
519 | '--layers',
520 | help=('Show layers digests for all images and all tags'),
521 | action='store_const',
522 | default=False,
523 | const=True)
524 |
525 | parser.add_argument(
526 | '--delete-by-hours',
527 | help=('Will delete all tags that are older than specified hours. Be careful!'),
528 | default=False,
529 | nargs='?',
530 | metavar='Hours')
531 |
532 | parser.add_argument(
533 | '--keep-by-hours',
534 | help=('Will keep all tags that are newer than specified hours.'),
535 | default=False,
536 | nargs='?',
537 | metavar='Hours')
538 |
539 | parser.add_argument(
540 | '--digest-method',
541 | help=('Use HEAD for standard docker registry or GET for NEXUS'),
542 | default='HEAD',
543 | metavar="HEAD|GET"
544 | )
545 | parser.add_argument(
546 | '--auth-method',
547 | help=('Use POST or GET to get JWT tokens'),
548 | default='POST',
549 | metavar="POST|GET"
550 | )
551 | parser.add_argument(
552 | '--order-by-date',
553 | help=('Orders images by date instead of by tag name.'
554 | 'Useful if your tag names are not in a fixed order.'),
555 | action='store_true'
556 | )
557 | parser.add_argument(
558 | '--plain',
559 | help=('Turn plain output, one image:tag per line.'
560 | 'Useful if your want to send the results to another command.'),
561 | action='store_true',
562 | default=False
563 | )
564 | return parser.parse_args(args)
565 |
566 |
567 | def delete_tags(
568 | registry, image_name, dry_run, tags_to_delete, tags_to_keep):
569 |
570 | keep_tag_digests = []
571 |
572 | if tags_to_keep:
573 | print("Getting digests for tags to keep:")
574 | for tag in tags_to_keep:
575 |
576 | print("Getting digest for tag {0}".format(tag))
577 | digest = registry.get_tag_digest(image_name, tag)
578 | if digest is None:
579 | print("Tag {0} does not exist for image {1}. Ignore here.".format(
580 | tag, image_name))
581 | continue
582 |
583 | print("Keep digest {0} for tag {1}".format(digest, tag))
584 |
585 | keep_tag_digests.append(digest)
586 |
587 | def delete(tag):
588 | print(" deleting tag {0}".format(tag))
589 | registry.delete_tag(image_name, tag, dry_run, keep_tag_digests)
590 |
591 | p = ThreadPool(4)
592 | tasks = []
593 | for tag in tags_to_delete:
594 | if tag in tags_to_keep:
595 | continue
596 | tasks.append(p.apply_async(delete, args=(tag,)))
597 | for task in tasks:
598 | task.get()
599 | p.close()
600 | p.join()
601 |
602 | # deleting layers is disabled because
603 | # it also deletes shared layers
604 | ##
605 | # for layer in registry.list_tag_layers(image_name, tag):
606 | # layer_digest = layer['digest']
607 | # registry.delete_tag_layer(image_name, layer_digest, dry_run)
608 |
609 |
610 | def get_tags_like(args_tags_like, tags_list, plain):
611 | result = set()
612 | for tag_like in args_tags_like:
613 | if not plain:
614 | print("tag like: {0}".format(tag_like))
615 | for tag in tags_list:
616 | if re.search(tag_like, tag):
617 | if not plain:
618 | print("Adding {0} to tags list".format(tag))
619 | result.add(tag)
620 | return result
621 |
622 |
623 | def get_tags(all_tags_list, image_name, tags_like, plain):
624 | # check if there are args for special tags
625 | result = set()
626 | if tags_like:
627 | result = get_tags_like(tags_like, all_tags_list, plain)
628 | else:
629 | result.update(all_tags_list)
630 |
631 | # get tags from image name if any
632 | if ":" in image_name:
633 | (image_name, tag_name) = image_name.split(":")
634 | result = set([tag_name])
635 |
636 | return result
637 |
638 |
639 | def delete_tags_by_age(registry, image_name, dry_run, hours, tags_to_keep):
640 | image_tags = registry.list_tags(image_name)
641 | tags_to_delete = []
642 | print('---------------------------------')
643 | for tag in image_tags:
644 | image_config = registry.get_tag_config(image_name, tag)
645 |
646 | if image_config == []:
647 | print("tag not found")
648 | continue
649 |
650 | image_age = registry.get_image_age(image_name, image_config)
651 |
652 | if image_age == []:
653 | print("timestamp not found")
654 | continue
655 |
656 | if parse(image_age).astimezone(tzutc()) < dt.now(tzutc()) - timedelta(hours=int(hours)):
657 | print("will be deleted tag: {0} timestamp: {1}".format(
658 | tag, image_age))
659 | tags_to_delete.append(tag)
660 |
661 | print('------------deleting-------------')
662 | delete_tags(registry, image_name, dry_run, tags_to_delete, tags_to_keep)
663 |
664 |
665 | def get_newer_tags(registry, image_name, hours, tags_list):
666 | def newer(tag):
667 | image_config = registry.get_tag_config(image_name, tag)
668 | if image_config == []:
669 | print("tag not found")
670 | return None
671 | image_age = registry.get_image_age(image_name, image_config)
672 | if image_age == []:
673 | print("timestamp not found")
674 | return None
675 | if parse(image_age).astimezone(tzutc()) >= dt.now(tzutc()) - timedelta(hours=int(hours)):
676 | print("Keeping tag: {0} timestamp: {1}".format(
677 | tag, image_age))
678 | return tag
679 | print("Will delete tag: {0} timestamp: {1}".format(tag, image_age))
680 | return None
681 |
682 | print('---------------------------------')
683 | p = ThreadPool(4)
684 | result = list(x for x in p.map(newer, tags_list) if x)
685 | p.close()
686 | p.join()
687 | return result
688 |
689 |
690 | def get_datetime_tags(registry, image_name, tags_list, plain):
691 | def newer(tag):
692 | image_config = registry.get_tag_config(image_name, tag)
693 | if image_config == []:
694 | print("tag not found")
695 | return None
696 | image_age = registry.get_image_age(image_name, image_config)
697 | if image_age == []:
698 | print("timestamp not found")
699 | return None
700 | return {
701 | "tag": tag,
702 | "datetime": parse(image_age).astimezone(tzutc())
703 | }
704 |
705 | if not plain:
706 | print('---------------------------------')
707 | p = ThreadPool(4)
708 | result = list(x for x in p.map(newer, tags_list) if x)
709 | p.close()
710 | p.join()
711 | return result
712 |
713 |
714 | def keep_images_like(image_list, regexp_list):
715 | if image_list is None or regexp_list is None:
716 | return []
717 | result = []
718 | regexp_list = list(map(re.compile, regexp_list))
719 | for image in image_list:
720 | for regexp in regexp_list:
721 | if re.search(regexp, image):
722 | result.append(image)
723 | break
724 | return result
725 |
726 |
727 | def get_ordered_tags(registry, image_name, tags_list, order_by_date=False):
728 | if order_by_date:
729 | tags_date = get_datetime_tags(registry, image_name, tags_list)
730 | sorted_tags_by_date = sorted(
731 | tags_date,
732 | key=lambda x: x["datetime"]
733 | )
734 | return [x["tag"] for x in sorted_tags_by_date]
735 |
736 | return sorted(tags_list, key=natural_keys)
737 |
738 |
739 | def main_loop(args):
740 | global DEBUG
741 |
742 | DEBUG = True if args.debug else False
743 |
744 | keep_last_versions = int(args.num)
745 |
746 | if args.no_validate_ssl:
747 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
748 |
749 | if args.read_password:
750 | if args.login is None:
751 | print("Please provide -l when using -w")
752 | sys.exit(1)
753 |
754 | if ':' in args.login:
755 | (username, password) = args.login.split(':', 1)
756 | else:
757 | username = args.login
758 |
759 | if sys.stdin.isatty():
760 | # likely interactive usage
761 | password = getpass()
762 |
763 | else:
764 | # allow password to be piped or redirected in
765 | password = sys.stdin.read()
766 |
767 | if len(password) == 0:
768 | print("Password was not provided")
769 | sys.exit(1)
770 |
771 | if password[-(len(os.linesep)):] == os.linesep:
772 | password = password[0:-(len(os.linesep))]
773 |
774 | args.login = username + ':' + password
775 |
776 | registry = Registry.create(args.host, args.login, args.no_validate_ssl,
777 | args.digest_method)
778 |
779 | registry.auth_schemes = get_auth_schemes(registry,'/v2/_catalog')
780 |
781 | if args.delete:
782 | print("Will delete all but {0} last tags".format(keep_last_versions))
783 |
784 | if args.image is not None:
785 | image_list = args.image
786 | else:
787 | image_list = registry.list_images()
788 | if args.images_like:
789 | image_list = keep_images_like(image_list, args.images_like)
790 |
791 | # loop through registry's images
792 | # or through the ones given in command line
793 | for image_name in image_list:
794 | if not args.plain:
795 | print("---------------------------------")
796 | print("Image: {0}".format(image_name))
797 | all_tags_list = registry.list_tags(image_name)
798 |
799 | if not all_tags_list:
800 | print(" no tags!")
801 | continue
802 |
803 | if args.order_by_date:
804 | tags_list = get_ordered_tags(registry, image_name, all_tags_list, args.order_by_date)
805 | else:
806 | tags_list = get_tags(all_tags_list, image_name, args.tags_like, args.plain)
807 |
808 | # print(tags and optionally layers
809 | for tag in tags_list:
810 | if not args.plain:
811 | print(" tag: {0}".format(tag))
812 | else:
813 | print("{0}:{1}".format(image_name, tag))
814 |
815 | if args.layers:
816 | for layer in registry.list_tag_layers(image_name, tag):
817 | if 'size' in layer:
818 | print(" layer: {0}, size: {1}".format(
819 | layer['digest'], layer['size']))
820 | else:
821 | print(" layer: {0}".format(
822 | layer['blobSum']))
823 |
824 | # add tags to "tags_to_keep" list if we have regexp "tags_to_keep"
825 | # entries, a number of hours for "keep_by_hours" or if the user
826 | # explicitly specified tags to always keep.
827 | keep_tags = []
828 | keep_tags.extend(args.keep_tags)
829 | if args.keep_tags_like:
830 | keep_tags.extend(get_tags_like(args.keep_tags_like, tags_list))
831 | if args.keep_by_hours:
832 | keep_tags.extend(get_newer_tags(registry, image_name,
833 | args.keep_by_hours, tags_list))
834 | keep_tags = list(set(keep_tags)) # Eliminate duplicates
835 |
836 | # delete tags if told so
837 | if args.delete or args.delete_all:
838 | if args.delete_all:
839 | tags_list_to_delete = list(tags_list)
840 | else:
841 | ordered_tags_list = get_ordered_tags(registry, image_name, tags_list, args.order_by_date)
842 | tags_list_to_delete = ordered_tags_list[:-keep_last_versions]
843 |
844 | # A manifest might be shared between different tags. Explicitly add those
845 | # tags that we want to preserve to the keep_tags list, to prevent
846 | # any manifest they are using from being deleted.
847 | tags_list_to_keep = [
848 | tag for tag in tags_list if tag not in tags_list_to_delete]
849 | keep_tags.extend(tags_list_to_keep)
850 |
851 | keep_tags.sort() # Make order deterministic for testing
852 | delete_tags(
853 | registry, image_name, args.dry_run,
854 | tags_list_to_delete, keep_tags)
855 |
856 | # delete tags by age in hours
857 | if args.delete_by_hours:
858 | delete_tags_by_age(registry, image_name, args.dry_run,
859 | args.delete_by_hours, keep_tags)
860 |
861 | if __name__ == "__main__":
862 | args = parse_args()
863 | try:
864 | main_loop(args)
865 | except KeyboardInterrupt:
866 | print("Ctrl-C pressed, quitting")
867 | sys.exit(1)
868 |
--------------------------------------------------------------------------------
/requirements-build.txt:
--------------------------------------------------------------------------------
1 | certifi==2017.7.27.1
2 | chardet==3.0.4
3 | idna>=2.5
4 | python-dateutil==2.8.0
5 | requests>=2.20.0
6 | urllib3>=1.23
7 | www-authenticate==0.9.2
--------------------------------------------------------------------------------
/requirements-ci.txt:
--------------------------------------------------------------------------------
1 | mock
2 | coverage
3 | certifi
4 | chardet
5 | python-dateutil==2.8.0
6 | idna>=2.5
7 | requests>=2.20.0
8 | urllib3>=1.23
9 | www-authenticate
10 |
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from datetime import datetime
4 |
5 | from dateutil.tz import tzutc, tzoffset
6 |
7 | from registry import Registry, Requests, get_tags, parse_args, \
8 | delete_tags, delete_tags_by_age, get_error_explanation, get_newer_tags, \
9 | keep_images_like, main_loop, get_datetime_tags, get_ordered_tags
10 | from mock import MagicMock, patch
11 | import requests
12 |
13 |
14 | class ReturnValue:
15 |
16 | def __init__(self, status_code=200, text=""):
17 | self.status_code = status_code
18 | self.text = text
19 |
20 |
21 | class MockRequests:
22 |
23 | def __init__(self, return_value=ReturnValue()):
24 | self.return_value = return_value
25 | self.request = MagicMock(return_value=self.return_value)
26 |
27 | def reset_return_value(self, status_code=200, text=""):
28 | self.return_value.status_code = status_code
29 | self.return_value.text = text
30 |
31 |
32 | class TestRequestsClass(unittest.TestCase):
33 |
34 | def test_requests_created(self):
35 | # simply create requests class and make sure it raises an exception
36 | # from requests module
37 | # this test will fail if port 45272 is open on local machine
38 | # is so, either change port below or check what is this service you are
39 | # running on port 45272
40 | with self.assertRaises(requests.exceptions.ConnectionError):
41 | Requests().request("GET", "http://localhost:45272")
42 |
43 |
44 | class TestCreateMethod(unittest.TestCase):
45 |
46 | def test_create_nologin(self):
47 | r = Registry.create("testhost", None, False)
48 | self.assertTrue(isinstance(r.http, Requests))
49 | self.assertEqual(r.hostname, "testhost")
50 | self.assertEqual(r.no_validate_ssl, False)
51 |
52 | def test_create_login(self):
53 | r = Registry.create("testhost2", "testlogin:testpass", False)
54 | self.assertEqual(r.hostname, "testhost2")
55 | self.assertTrue(isinstance(r.http, Requests))
56 | self.assertEqual(r.username, "testlogin")
57 | self.assertEqual(r.password, "testpass")
58 |
59 | def test_validate_ssl(self):
60 | r = Registry.create("testhost3", None, True)
61 | self.assertTrue(isinstance(r.http, Requests))
62 | self.assertTrue(r.no_validate_ssl)
63 | self.assertEqual(r.username, None)
64 | self.assertEqual(r.password, None)
65 |
66 | def test_invalid_login(self):
67 | with self.assertRaises(SystemExit):
68 | Registry.create("testhost4", "invalid_login", False)
69 |
70 |
71 | class TestParseLogin(unittest.TestCase):
72 |
73 | def setUp(self):
74 | self.registry = Registry()
75 |
76 | def test_login_args_ok(self):
77 | (username, password) = self.registry.parse_login("username:password")
78 | self.assertEqual(username, "username")
79 | self.assertEqual(password, "password")
80 | self.assertEqual(self.registry.last_error, None)
81 |
82 | def test_login_args_double_colon(self):
83 | (username, password) = self.registry.parse_login("username:pass:word")
84 | self.assertEqual(username, "username")
85 | self.assertEqual(password, "pass:word")
86 | self.assertEqual(self.registry.last_error, None)
87 |
88 | # this test becomes reduntant
89 | def test_login_args_no_colon(self):
90 | (username, password) = self.registry.parse_login("username/password")
91 | self.assertEqual(username, None)
92 | self.assertEqual(password, None)
93 | self.assertEqual(self.registry.last_error,
94 | "Please provide -l in the form USER:PASSWORD")
95 |
96 | def test_login_args_singlequoted(self):
97 | (username, password) = self.registry.parse_login("'username':password")
98 | self.assertEqual(username, 'username')
99 | self.assertEqual(password, "password")
100 | self.assertEqual(self.registry.last_error, None)
101 |
102 | def test_login_args_doublequoted(self):
103 | (username, password) = self.registry.parse_login('"username":"password"')
104 | self.assertEqual(username, 'username')
105 | self.assertEqual(password, "password")
106 | self.assertEqual(self.registry.last_error, None)
107 |
108 | def test_login_colon_username(self):
109 | """
110 | this is to test that if username contains colon,
111 | then the result will be invalid in this case
112 | and no error will be printed
113 | """
114 | (username, password) = self.registry.parse_login(
115 | "'user:name':'pass:word'")
116 | self.assertEqual(username, 'user')
117 | self.assertEqual(password, "name':'pass:word")
118 |
119 |
120 | class TestRegistrySend(unittest.TestCase):
121 |
122 | def setUp(self):
123 | self.registry = Registry()
124 | self.registry.http = MockRequests()
125 | self.registry.hostname = "http://testdomain.com"
126 |
127 | def test_get_ok(self):
128 | self.registry.http.reset_return_value(200)
129 | response = self.registry.send('/test_string')
130 |
131 | self.assertEqual(response.status_code, 200)
132 | self.assertEqual(self.registry.last_error, None)
133 | self.registry.http.request.assert_called_with('GET',
134 | 'http://testdomain.com/test_string',
135 | auth=(None, None),
136 | headers=self.registry.HEADERS,
137 | verify=True)
138 |
139 | def test_invalid_status_code(self):
140 | self.registry.http.reset_return_value(400)
141 | response = self.registry.send('/v2/catalog')
142 | self.assertEqual(response, None)
143 | self.assertEqual(self.registry.last_error, 400)
144 |
145 | def test_login_pass(self):
146 | self.registry.username = "test_login"
147 | self.registry.password = "test_password"
148 | self.registry.http.reset_return_value(200)
149 | response = self.registry.send('/v2/catalog')
150 | self.assertEqual(response.status_code, 200)
151 | self.assertEqual(self.registry.last_error, None)
152 | self.registry.http.request.assert_called_with('GET',
153 | 'http://testdomain.com/v2/catalog',
154 | auth=("test_login",
155 | "test_password"),
156 | headers=self.registry.HEADERS,
157 | verify=True)
158 |
159 | class TestGetErrorExplanation(unittest.TestCase):
160 | def test_get_tag_digest_404(self):
161 | self.assertEqual(get_error_explanation("delete_tag", "405"),
162 | 'You might want to set REGISTRY_STORAGE_DELETE_ENABLED: "true" in your registry')
163 |
164 | def test_delete_digest_405(self):
165 | self.assertEqual(get_error_explanation("get_tag_digest", "404"),
166 | "Try adding flag --digest-method=GET")
167 |
168 |
169 | class TestListImages(unittest.TestCase):
170 |
171 | def setUp(self):
172 | self.registry = Registry()
173 | self.registry.http = MockRequests()
174 | self.registry.hostname = "http://testdomain.com"
175 |
176 | def test_list_images_ok(self):
177 | self.registry.http.reset_return_value(status_code=200,
178 | text='{"repositories":["image1","image2"]}')
179 | response = self.registry.list_images()
180 | self.assertEqual(response, ["image1", "image2"])
181 | self.assertEqual(self.registry.last_error, None)
182 |
183 | def test_list_images_invalid_http_response(self):
184 | self.registry.http.reset_return_value(404)
185 | response = self.registry.list_images()
186 | self.assertEqual(response, [])
187 | self.assertEqual(self.registry.last_error, 404)
188 |
189 |
190 | class TestListTags(unittest.TestCase):
191 |
192 | def setUp(self):
193 | self.registry = Registry()
194 | self.registry.http = MockRequests()
195 | self.registry.hostname = "http://testdomain.com"
196 | self.registry.http.reset_return_value(200)
197 |
198 | def test_list_one_tag_ok(self):
199 | self.registry.http.reset_return_value(status_code=200,
200 | text=u'{"name":"image1","tags":["0.1.306"]}')
201 |
202 | response = self.registry.list_tags('image1')
203 | self.assertEqual(response, ["0.1.306"])
204 | self.assertEqual(self.registry.last_error, None)
205 |
206 | def test_list_tags_invalid_http_response(self):
207 | self.registry.http.reset_return_value(status_code=400,
208 | text="")
209 |
210 | response = self.registry.list_tags('image1')
211 | self.assertEqual(response, [])
212 | self.assertEqual(self.registry.last_error, 400)
213 |
214 | def test_list_tags_invalid_json(self):
215 | self.registry.http.reset_return_value(status_code=200,
216 | text="invalid_json")
217 |
218 | response = self.registry.list_tags('image1')
219 | self.assertEqual(response, [])
220 | self.assertEqual(self.registry.last_error,
221 | "list_tags: invalid json response")
222 |
223 | def test_list_one_tag_sorted(self):
224 | self.registry.http.reset_return_value(status_code=200,
225 | text=u'{"name":"image1","tags":["0.1.306", "0.1.300", "0.1.290"]}')
226 |
227 | response = self.registry.list_tags('image1')
228 | self.assertEqual(response, ["0.1.290", "0.1.300", "0.1.306"])
229 | self.assertEqual(self.registry.last_error, None)
230 |
231 | def test_list_tags_like_various(self):
232 | tags_list = set(['FINAL_0.1', 'SNAPSHOT_0.1',
233 | "0.1.SNAP", "1.0.0_FINAL"])
234 | for plain in [True, False]:
235 | self.assertEqual(get_tags(tags_list, "", set(
236 | ["FINAL"]), plain), set(["FINAL_0.1", "1.0.0_FINAL"]))
237 | self.assertEqual(get_tags(tags_list, "", set(
238 | ["SNAPSHOT"]), plain), set(['SNAPSHOT_0.1']))
239 | self.assertEqual(get_tags(tags_list, "", set(), plain),
240 | set(['FINAL_0.1', 'SNAPSHOT_0.1', "0.1.SNAP", "1.0.0_FINAL"]))
241 | self.assertEqual(get_tags(tags_list, "", set(["ABSENT"]), plain), set())
242 | self.assertEqual(
243 | get_tags(tags_list, "IMAGE:TAG00", "", plain), set(["TAG00"]))
244 | self.assertEqual(get_tags(tags_list, "IMAGE:TAG00", set(
245 | ["WILL_NOT_BE_CONSIDERED"]), plain), set(["TAG00"]))
246 |
247 |
248 | class TestListDigest(unittest.TestCase):
249 |
250 | def setUp(self):
251 | self.registry = Registry()
252 | self.registry.http = MockRequests()
253 | self.registry.hostname = "http://testdomain.com"
254 | self.registry.http.reset_return_value(200)
255 |
256 | def test_get_digest_ok(self):
257 | self.registry.http.reset_return_value(status_code=200,
258 | text=('{'
259 | '"schemaVersion": 2,\n '
260 | '"mediaType": "application/vnd.docker.distribution.manifest.v2+json"'
261 | '"digest": "sha256:357ea8c3d80bc25792e010facfc98aee5972ebc47e290eb0d5aea3671a901cab"'
262 | ))
263 |
264 | self.registry.http.return_value.headers = {
265 | 'Content-Length': '4935',
266 | 'Docker-Content-Digest': 'sha256:85295b0e7456a8fbbc886722b483f87f2bff553fa0beeaf37f5d807aff7c1e52',
267 | 'X-Content-Type-Options': 'nosniff'
268 | }
269 |
270 | response = self.registry.get_tag_digest('image1', '0.1.300')
271 | self.registry.http.request.assert_called_with(
272 | "HEAD",
273 | "http://testdomain.com/v2/image1/manifests/0.1.300",
274 | auth=(None, None),
275 | headers=self.registry.HEADERS,
276 | verify=True
277 | )
278 |
279 | self.assertEqual(
280 | response, 'sha256:85295b0e7456a8fbbc886722b483f87f2bff553fa0beeaf37f5d807aff7c1e52')
281 | self.assertEqual(self.registry.last_error, None)
282 |
283 | def test_get_digest_nexus_ok(self):
284 | self.registry.http.reset_return_value(status_code=200,
285 | text=('{'
286 | '"schemaVersion": 2,\n '
287 | '"mediaType": "application/vnd.docker.distribution.manifest.v2+json"'
288 | '"digest": "sha256:357ea8c3d80bc25792e010facfc98aee5972ebc47e290eb0d5aea3671a901cab"'
289 | ))
290 |
291 | self.registry.http.return_value.headers = {
292 | 'Content-Length': '4935',
293 | 'Docker-Content-Digest': 'sha256:85295b0e7456a8fbbc886722b483f87f2bff553fa0beeaf37f5d807aff7c1e52',
294 | 'X-Content-Type-Options': 'nosniff'
295 | }
296 |
297 | self.registry.digest_method = "GET"
298 | response = self.registry.get_tag_digest('image1', '0.1.300')
299 | self.registry.http.request.assert_called_with(
300 | "GET",
301 | "http://testdomain.com/v2/image1/manifests/0.1.300",
302 | auth=(None, None),
303 | headers=self.registry.HEADERS,
304 | verify=True
305 | )
306 |
307 | self.assertEqual(
308 | response, 'sha256:85295b0e7456a8fbbc886722b483f87f2bff553fa0beeaf37f5d807aff7c1e52')
309 | self.assertEqual(self.registry.last_error, None)
310 |
311 |
312 | def test_invalid_status_code(self):
313 | self.registry.http.reset_return_value(400)
314 | response = self.registry.get_tag_digest('image1', '0.1.300')
315 | self.assertEqual(response, None)
316 |
317 | def test_invalid_headers(self):
318 | self.registry.http.reset_return_value(200, "invalid json")
319 | self.registry.http.return_value.headers = "invalid headers"
320 | with self.assertRaises(TypeError):
321 | self.registry.get_tag_digest('image1', '0.1.300')
322 |
323 |
324 | class TestTagConfig(unittest.TestCase):
325 |
326 | def setUp(self):
327 | self.registry = Registry()
328 | self.registry.http = MockRequests()
329 | self.registry.hostname = "http://testdomain.com"
330 | self.registry.http.reset_return_value(200)
331 |
332 | def test_get_tag_config_ok(self):
333 | self.registry.http.reset_return_value(
334 | 200,
335 | '''
336 | {
337 | "schemaVersion": 2,
338 | "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
339 | "config": {
340 | "mediaType": "application/vnd.docker.container.image.v1+json",
341 | "size": 12953,
342 | "digest": "sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8"
343 | },
344 | "layers": [
345 | {
346 | "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
347 | "size": 51480140,
348 | "digest": "sha256:c6b13209f43b945816b7658a567720983ac5037e3805a779d5772c61599b4f73"
349 | }
350 | ]
351 | }
352 | '''
353 | )
354 |
355 | response = self.registry.get_tag_config('image1', '0.1.300')
356 |
357 | self.registry.http.request.assert_called_with(
358 | "GET",
359 | "http://testdomain.com/v2/image1/manifests/0.1.300",
360 | auth=(None, None),
361 | headers=self.registry.HEADERS,
362 | verify=True)
363 |
364 | self.assertEqual(
365 | response, {'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 12953, 'digest': 'sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8'})
366 | self.assertEqual(self.registry.last_error, None)
367 |
368 | def test_tag_config_scheme_v1(self):
369 | with self.assertRaises(SystemExit):
370 | self.registry.http.reset_return_value(
371 | 200,
372 | '''
373 | {
374 | "schemaVersion": 1
375 | }
376 | '''
377 | )
378 | response = self.registry.get_tag_config('image1', '0.1.300')
379 |
380 | def test_invalid_status_code(self):
381 | self.registry.http.reset_return_value(400, "whatever")
382 |
383 | response = self.registry.get_tag_config('image1', '0.1.300')
384 |
385 | self.registry.http.request.assert_called_with(
386 | "GET",
387 | "http://testdomain.com/v2/image1/manifests/0.1.300",
388 | auth=(None, None),
389 | headers=self.registry.HEADERS,
390 | verify=True
391 | )
392 |
393 | self.assertEqual(response, [])
394 | self.assertEqual(self.registry.last_error, 400)
395 |
396 |
397 | class TestImageAge(unittest.TestCase):
398 |
399 | def setUp(self):
400 | self.registry = Registry()
401 | self.registry.http = MockRequests()
402 | self.registry.hostname = "http://testdomain.com"
403 | self.registry.http.reset_return_value(200)
404 |
405 | def test_image_age_ok(self):
406 | self.registry.http.reset_return_value(
407 | 200,
408 | '''
409 | {
410 | "architecture": "amd64",
411 | "author": "Test",
412 | "config": {},
413 | "container": "c467822c5981cd446068eebafd81cb5cde60d4341a945f3fbf67e456dde5af51",
414 | "container_config": {},
415 | "created": "2017-12-27T12:47:33.511765448Z",
416 | "docker_version": "1.11.2",
417 | "history": []
418 | }
419 | '''
420 | )
421 | json_payload = {'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 12953,
422 | 'digest': 'sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8'}
423 | header = {"Accept": "{0}".format(json_payload['mediaType'])}
424 | response = self.registry.get_image_age('image1', json_payload)
425 |
426 | self.registry.http.request.assert_called_with(
427 | "GET",
428 | "http://testdomain.com/v2/image1/blobs/sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8",
429 | auth=(None, None),
430 | headers=header,
431 | verify=True)
432 |
433 | self.assertEqual(
434 | response, "2017-12-27T12:47:33.511765448Z")
435 | self.assertEqual(self.registry.last_error, None)
436 |
437 | def test_image_age_nok(self):
438 | self.registry.http.reset_return_value(400, "err")
439 | json_payload = {'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 12953,
440 | 'digest': 'sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8'}
441 | header = {"Accept": "{0}".format(json_payload['mediaType'])}
442 | response = self.registry.get_image_age('image1', json_payload)
443 |
444 | self.registry.http.request.assert_called_with(
445 | "GET",
446 | "http://testdomain.com/v2/image1/blobs/sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8",
447 | auth=(None, None),
448 | headers=header,
449 | verify=True)
450 |
451 | self.assertEqual(response, [])
452 | self.assertEqual(self.registry.last_error, 400)
453 |
454 |
455 | class TestListLayers(unittest.TestCase):
456 |
457 | def setUp(self):
458 | self.registry = Registry()
459 | self.registry.http = MockRequests()
460 | self.registry.hostname = "http://testdomain.com"
461 | self.registry.http.reset_return_value(200)
462 |
463 | def test_list_layers_schema_version_2_ok(self):
464 | self.registry.http.reset_return_value(
465 | 200,
466 | '''
467 | {
468 | "schemaVersion": 2,
469 | "layers": "layers_list"
470 | }
471 | '''
472 | )
473 |
474 | response = self.registry.list_tag_layers('image1', '0.1.300')
475 |
476 | self.registry.http.request.assert_called_with(
477 | "GET",
478 | "http://testdomain.com/v2/image1/manifests/0.1.300",
479 | auth=(None, None),
480 | headers=self.registry.HEADERS,
481 | verify=True
482 | )
483 |
484 | self.assertEqual(response, "layers_list")
485 | self.assertEqual(self.registry.last_error, None)
486 |
487 | def test_list_layers_schema_version_1_ok(self):
488 | self.registry.http.reset_return_value(
489 | 200,
490 | '''
491 | {
492 | "schemaVersion": 1,
493 | "fsLayers": "layers_list"
494 | }
495 | '''
496 | )
497 |
498 | response = self.registry.list_tag_layers('image1', '0.1.300')
499 |
500 | self.registry.http.request.assert_called_with(
501 | "GET",
502 | "http://testdomain.com/v2/image1/manifests/0.1.300",
503 | auth=(None, None),
504 | headers=self.registry.HEADERS,
505 | verify=True
506 | )
507 |
508 | self.assertEqual(response, "layers_list")
509 | self.assertEqual(self.registry.last_error, None)
510 |
511 | def test_list_layers_invalid_status_code(self):
512 | self.registry.http.reset_return_value(400, "whatever")
513 |
514 | response = self.registry.list_tag_layers('image1', '0.1.300')
515 |
516 | self.registry.http.request.assert_called_with(
517 | "GET",
518 | "http://testdomain.com/v2/image1/manifests/0.1.300",
519 | auth=(None, None),
520 | headers=self.registry.HEADERS,
521 | verify=True
522 | )
523 |
524 | self.assertEqual(response, [])
525 | self.assertEqual(self.registry.last_error, 400)
526 |
527 |
528 | class TestDeletion(unittest.TestCase):
529 |
530 | def setUp(self):
531 | self.registry = Registry()
532 | self.registry.http = MockRequests()
533 | self.registry.hostname = "http://testdomain.com"
534 | self.registry.http.reset_return_value(200, "MOCK_DIGEST")
535 | self.registry.http.return_value.headers = {
536 | 'Content-Length': '4935',
537 | 'Docker-Content-Digest': 'MOCK_DIGEST_HEADER',
538 | 'X-Content-Type-Options': 'nosniff'
539 | }
540 |
541 | def test_delete_tag_dry_run(self):
542 | response = self.registry.delete_tag("image1", 'test_tag', True, [])
543 | self.assertFalse(response)
544 |
545 | def test_delete_tag_ok(self):
546 | keep_tag_digests = ['DIGEST1', 'DIGEST2']
547 | response = self.registry.delete_tag(
548 | 'image1', 'test_tag', False, keep_tag_digests)
549 | self.assertEqual(response, True)
550 | self.assertEqual(self.registry.http.request.call_count, 2)
551 | self.registry.http.request.assert_called_with(
552 | "DELETE",
553 | "http://testdomain.com/v2/image1/manifests/MOCK_DIGEST_HEADER",
554 | auth=(None, None),
555 | headers=self.registry.HEADERS,
556 | verify=True
557 | )
558 | self.assertTrue("MOCK_DIGEST_HEADER" in keep_tag_digests)
559 |
560 | def test_delete_tag_ignored(self):
561 | response = self.registry.delete_tag(
562 | 'image1', 'test_tag', False, ['MOCK_DIGEST_HEADER'])
563 | self.assertEqual(response, True)
564 | self.assertEqual(self.registry.http.request.call_count, 1)
565 | self.registry.http.request.assert_called_with(
566 | "HEAD",
567 | "http://testdomain.com/v2/image1/manifests/test_tag",
568 | auth=(None, None),
569 | headers=self.registry.HEADERS,
570 | verify=True
571 | )
572 |
573 | def test_delete_tag_no_digest(self):
574 | self.registry.http.reset_return_value(400, "")
575 | response = self.registry.delete_tag('image1', 'test_tag', False, [])
576 | self.assertFalse(response)
577 | self.assertEqual(self.registry.last_error, 400)
578 |
579 |
580 | class TestDeleteTagsFunction(unittest.TestCase):
581 |
582 | def setUp(self):
583 | self.registry = Registry()
584 | self.delete_mock = MagicMock()
585 | self.registry.delete_tag = self.delete_mock
586 | self.registry.http = MockRequests()
587 | self.registry.hostname = "http://testdomain.com"
588 | self.registry.http.reset_return_value(200, "MOCK_DIGEST")
589 | self.registry.http.return_value.headers = {
590 | 'Content-Length': '4935',
591 | 'Docker-Content-Digest': 'MOCK_DIGEST_HEADER',
592 | 'X-Content-Type-Options': 'nosniff'
593 | }
594 |
595 | def test_delete_tags_no_keep(self):
596 | delete_tags(self.registry, "imagename", False, ["tag_to_delete"], [])
597 | self.delete_mock.assert_called_with(
598 | "imagename",
599 | "tag_to_delete",
600 | False,
601 | []
602 | )
603 |
604 | def test_delete_tags_keep(self):
605 | digest_mock = MagicMock(return_value="DIGEST_MOCK")
606 | self.registry.get_tag_digest = digest_mock
607 |
608 | delete_tags(self.registry, "imagename",
609 | False, ["tag1", "tag2"], ["tag2"])
610 |
611 | digest_mock.assert_called_with("imagename", "tag2")
612 |
613 | self.delete_mock.assert_called_with(
614 | "imagename",
615 | "tag1",
616 | False,
617 | ['DIGEST_MOCK']
618 | )
619 |
620 | def test_delete_tags_digest_none(self):
621 | digest_mock = MagicMock(return_value=None)
622 | self.registry.get_tag_digest = digest_mock
623 | delete_tags(self.registry, "imagename",
624 | False, ["tag1", "tag2"], ["tag2"])
625 |
626 | digest_mock.assert_called_with("imagename", "tag2")
627 |
628 | self.delete_mock.assert_called_with(
629 | "imagename",
630 | "tag1",
631 | False,
632 | []
633 | )
634 |
635 |
636 | class TestDeleteTagsByAge(unittest.TestCase):
637 |
638 | def setUp(self):
639 | self.registry = Registry()
640 | self.registry.http = MockRequests()
641 |
642 | self.get_tag_config_mock = MagicMock(return_value={'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 12953,
643 | 'digest': 'sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8'})
644 | self.registry.get_tag_config = self.get_tag_config_mock
645 | self.get_image_age_mock = MagicMock(
646 | return_value="2017-12-27T12:47:33.511765448Z")
647 | self.registry.get_image_age = self.get_image_age_mock
648 | self.list_tags_mock = MagicMock(return_value=["image"])
649 | self.registry.list_tags = self.list_tags_mock
650 | self.get_tag_digest_mock = MagicMock()
651 | self.registry.get_tag_digest = self.get_tag_digest_mock
652 | self.registry.http = MockRequests()
653 | self.registry.hostname = "http://testdomain.com"
654 | self.registry.http.reset_return_value(200, "MOCK_DIGEST")
655 |
656 | @patch('registry.delete_tags')
657 | def test_delete_tags_by_age_no_keep(self, delete_tags_patched):
658 | delete_tags_by_age(self.registry, "imagename", False, 24, [])
659 | self.list_tags_mock.assert_called_with(
660 | "imagename"
661 | )
662 | self.list_tags_mock.assert_called_with("imagename")
663 | self.get_tag_config_mock.assert_called_with("imagename", "image")
664 | delete_tags_patched.assert_called_with(
665 | self.registry, "imagename", False, ["image"], [])
666 |
667 | @patch('registry.delete_tags')
668 | def test_delete_tags_by_age_no_keep_with_non_utc_value(self, delete_tags_patched):
669 | self.registry.get_image_age.return_value = "2017-12-27T12:47:33.511765448+02:00"
670 | delete_tags_by_age(self.registry, "imagename", False, 24, [])
671 | self.list_tags_mock.assert_called_with(
672 | "imagename"
673 | )
674 | self.list_tags_mock.assert_called_with("imagename")
675 | self.get_tag_config_mock.assert_called_with("imagename", "image")
676 | delete_tags_patched.assert_called_with(
677 | self.registry, "imagename", False, ["image"], [])
678 |
679 | @patch('registry.delete_tags')
680 | def test_delete_tags_by_age_keep_tags(self, delete_tags_patched):
681 | delete_tags_by_age(self.registry, "imagename", False, 24, ["latest"])
682 | self.list_tags_mock.assert_called_with(
683 | "imagename"
684 | )
685 | self.list_tags_mock.assert_called_with("imagename")
686 | self.get_tag_config_mock.assert_called_with("imagename", "image")
687 | delete_tags_patched.assert_called_with(
688 | self.registry, "imagename", False, ["image"], ["latest"])
689 |
690 | @patch('registry.delete_tags')
691 | def test_delete_tags_by_age_dry_run(self, delete_tags_patched):
692 | delete_tags_by_age(self.registry, "imagename", True, 24, ["latest"])
693 | self.list_tags_mock.assert_called_with(
694 | "imagename"
695 | )
696 | self.list_tags_mock.assert_called_with("imagename")
697 | self.get_tag_config_mock.assert_called_with("imagename", "image")
698 | delete_tags_patched.assert_called_with(
699 | self.registry, "imagename", True, ["image"], ["latest"])
700 |
701 |
702 | class TestGetNewerTags(unittest.TestCase):
703 |
704 | def setUp(self):
705 | self.registry = Registry()
706 | self.registry.http = MockRequests()
707 |
708 | self.get_tag_config_mock = MagicMock(return_value={'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 12953,
709 | 'digest': 'sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8'})
710 | self.registry.get_tag_config = self.get_tag_config_mock
711 | self.get_image_age_mock = MagicMock(
712 | return_value="2017-12-27T12:47:33.511765448Z")
713 | self.registry.get_image_age = self.get_image_age_mock
714 | self.list_tags_mock = MagicMock(return_value=["image"])
715 | self.registry.list_tags = self.list_tags_mock
716 | self.get_tag_digest_mock = MagicMock()
717 | self.registry.get_tag_digest = self.get_tag_digest_mock
718 | self.registry.http = MockRequests()
719 | self.registry.hostname = "http://testdomain.com"
720 | self.registry.http.reset_return_value(200, "MOCK_DIGEST")
721 |
722 | def test_keep_tags_by_age_no_keep(self):
723 | self.assertEqual(
724 | get_newer_tags(self.registry, "imagename", 23, ["latest"]),
725 | []
726 | )
727 |
728 | def test_keep_tags_by_age_keep(self):
729 | self.assertEqual(
730 | get_newer_tags(self.registry, "imagename", 24, ["latest"]),
731 | ["latest"]
732 | )
733 |
734 | def test_keep_tags_by_age_no_keep_non_utc_datetime(self):
735 | self.registry.get_image_age.return_value = "2017-12-27T12:47:33.511765448+02:00"
736 | self.assertEqual(
737 | get_newer_tags(self.registry, "imagename", 23, ["latest"]),
738 | []
739 | )
740 |
741 |
742 | class TestGetDatetimeTags(unittest.TestCase):
743 |
744 | def setUp(self):
745 | self.registry = Registry()
746 | self.registry.http = MockRequests()
747 |
748 | self.get_tag_config_mock = MagicMock(return_value={'mediaType': 'application/vnd.docker.container.image.v1+json', 'size': 12953,
749 | 'digest': 'sha256:8d71dfbf239c0015ad66993d55d3954cee2d52d86f829fdff9ccfb9f23b75aa8'})
750 | self.registry.get_tag_config = self.get_tag_config_mock
751 | self.get_image_age_mock = MagicMock(
752 | return_value="2017-12-27T12:47:33.511765448Z")
753 | self.registry.get_image_age = self.get_image_age_mock
754 | self.list_tags_mock = MagicMock(return_value=["image"])
755 | self.registry.list_tags = self.list_tags_mock
756 | self.get_tag_digest_mock = MagicMock()
757 | self.registry.get_tag_digest = self.get_tag_digest_mock
758 | self.registry.http = MockRequests()
759 | self.registry.hostname = "http://testdomain.com"
760 | self.registry.http.reset_return_value(200, "MOCK_DIGEST")
761 |
762 | def test_get_datetime_tags(self):
763 | for plain in [True, False]:
764 | self.assertEqual(
765 | get_datetime_tags(self.registry, "imagename", ["latest"], plain),
766 | [{"tag": "latest", "datetime": datetime(2017, 12, 27, 12, 47, 33, 511765, tzinfo=tzutc())}]
767 | )
768 |
769 | def test_get_non_utc_datetime_tags(self):
770 | self.registry.get_image_age.return_value = "2019-07-18T16:33:15.864962122+02:00"
771 | for plain in [True, False]:
772 | self.assertEqual(
773 | get_datetime_tags(self.registry, "imagename", ["latest"], plain),
774 | [{"tag": "latest", "datetime": datetime(2019, 7, 18, 16, 33, 15, 864962, tzinfo=tzoffset(None, 7200))}]
775 | )
776 |
777 |
778 | class TestGetOrderedTags(unittest.TestCase):
779 | def setUp(self):
780 | self.tags = ["e61d48b", "ff24a83", "ddd514c", "f4ba381", "9d5fab2"]
781 |
782 | def test_tags_are_ordered_by_name_by_default(self):
783 | tags = ["v1", "v10", "v2"]
784 | ordered_tags = get_ordered_tags(registry=None, image_name=None, tags_list=tags)
785 | self.assertEqual(ordered_tags, ["v1", "v2", "v10"])
786 |
787 | @patch('registry.get_datetime_tags')
788 | def test_tags_are_ordered_ascending_by_date_if_the_option_is_given(self, get_datetime_tags_patched):
789 | tags = ["e61d48b", "ff24a83", "ddd514c", "f4ba381", "9d5fab2"]
790 | get_datetime_tags_patched.return_value = [
791 | {
792 | "tag": "e61d48b",
793 | "datetime": datetime(2025, 1, 1, tzinfo=tzutc())
794 | },
795 | {
796 | "tag": "ff24a83",
797 | "datetime": datetime(2024, 1, 1, tzinfo=tzutc())
798 | },
799 | {
800 | "tag": "ddd514c",
801 | "datetime": datetime(2023, 1, 1, tzinfo=tzutc())
802 | },
803 | {
804 | "tag": "f4ba381",
805 | "datetime": datetime(2022, 1, 1, tzinfo=tzutc())
806 | },
807 | {
808 | "tag": "9d5fab2",
809 | "datetime": datetime(2021, 1, 1, tzinfo=tzutc())
810 | }
811 | ]
812 | ordered_tags = get_ordered_tags(registry="registry", image_name="image", tags_list=tags, order_by_date=True)
813 | get_datetime_tags_patched.assert_called_once_with("registry", "image", tags)
814 | self.assertEqual(ordered_tags, ["9d5fab2", "f4ba381", "ddd514c", "ff24a83", "e61d48b"])
815 |
816 |
817 | class TestKeepImagesLike(unittest.TestCase):
818 |
819 | # tests the filtering works
820 | def test_keep_images_like(self):
821 | self.images = ["lorem", "ipsum", "dolor", "sit", "amet"]
822 | self.assertEqual(keep_images_like(self.images, ["bad"]), [])
823 | self.assertEqual(keep_images_like(self.images, ["lorem"]), ["lorem"])
824 | self.assertEqual(keep_images_like(self.images, ["lorem", "ipsum"]), ["lorem", "ipsum"])
825 | self.assertEqual(keep_images_like(self.images, ["i"]), ["ipsum", "sit"])
826 | self.assertEqual(keep_images_like(self.images, ["^i"]), ["ipsum"])
827 | self.assertEqual(keep_images_like([], ["^i"]), [])
828 | self.assertEqual(keep_images_like(self.images, []), [])
829 | self.assertEqual(keep_images_like([], []), [])
830 | self.assertEqual(keep_images_like(None, None), [])
831 |
832 | # mock Registry.create that sets things up
833 | # we need this because we want to call main_loop
834 | # which creates the Registry object by itself calling create
835 | @staticmethod
836 | def mock_create(h, l, n, d="HEAD"):
837 | r = Registry._create(h, l, n, d)
838 | r.http = MockRequests()
839 | r.list_images = MagicMock(return_value=['a', 'b', 'c'])
840 | return r
841 |
842 | @patch('registry.Registry.create', mock_create)
843 | @patch('registry.get_auth_schemes') # called in main_loop, turn to noop
844 | @patch('registry.keep_images_like')
845 | def test_main_calls(self, keep_images_like_patched, get_auth_schemes_patched):
846 | # check if keep_images_like is called when passed --images-like
847 | main_loop(parse_args(('-r', 'localhost:8989', '--images-like', 'me')))
848 | keep_images_like_patched.assert_called_with(['a', 'b', 'c'], ['me'])
849 |
850 | # check if keep_images_like is *not* called when passed --images-like
851 | keep_images_like_patched.reset_mock()
852 | args = parse_args(('-r', 'localhost:8989'))
853 | args.image = [] # this makes the for loop in main_loop not run at all
854 | main_loop(args)
855 | keep_images_like_patched.assert_not_called()
856 |
857 |
858 | class TestKeepTags(unittest.TestCase):
859 | @staticmethod
860 | def create_mock_registry(host, login, no_validate_ssl, digest_method="HEAD"):
861 | r = Registry._create(host, login, no_validate_ssl, digest_method)
862 | r.http = MockRequests()
863 | r.list_images = MagicMock(return_value=['a'])
864 | r.list_tags = MagicMock(return_value=['1', '2', '3', '4', '5', '6', '7'])
865 | return r
866 |
867 | # We store the actual mock registry here so we can later compare it in
868 | # `assert_called_with()`.
869 | mock_registry = create_mock_registry.__func__('localhost:8989', None, True)
870 |
871 | def return_mock_registry(self, host, login, no_validate_ssl, digest_method="HEAD"):
872 | return TestKeepTags.mock_registry
873 |
874 | @patch('registry.Registry.create', return_mock_registry)
875 | @patch('registry.get_auth_schemes') # called in main_loop, turn to noop
876 | @patch('registry.delete_tags')
877 | def test_keep_tags(self, delete_tags_patched, get_auth_schemes_patched):
878 | # Check if delete_tags is called from main_loop (directly or indirectly
879 | # through delete_tags_by_age) with `keep_tags` set to the tags we want to keep.
880 | main_loop(parse_args(('--delete', '--num', '5', '-r', 'localhost:8989', '--keep-tags', '1')))
881 | delete_tags_patched.assert_called_with(TestKeepTags.mock_registry, 'a', False, ['1', '2'], ['1', '3', '4', '5', '6', '7'])
882 |
883 |
884 | class TestArgParser(unittest.TestCase):
885 |
886 | def test_no_args(self):
887 | with self.assertRaises(SystemExit):
888 | parse_args("")
889 |
890 | def test_all_args(self):
891 | args_list = ["-r", "hostname",
892 | "-l", "loginstring",
893 | "-d",
894 | "-n", "15",
895 | "--dry-run",
896 | "-i", "imagename1", "imagename2",
897 | "--keep-tags", "keep1", "keep2",
898 | "--tags-like", "tags_like_text",
899 | "--no-validate-ssl",
900 | "--delete-all",
901 | "--layers",
902 | "--delete-by-hours", "24",
903 | "--keep-by-hours", "24",
904 | "--digest-method", "GET",
905 | "--order-by-date"]
906 | args = parse_args(args_list)
907 | self.assertTrue(args.delete)
908 | self.assertTrue(args.layers)
909 | self.assertTrue(args.no_validate_ssl)
910 | self.assertTrue(args.delete_all)
911 | self.assertTrue(args.layers)
912 | self.assertTrue(args.order_by_date)
913 | self.assertEqual(args.image, ["imagename1", "imagename2"])
914 | self.assertEqual(args.num, "15")
915 | self.assertEqual(args.login, "loginstring")
916 | self.assertEqual(args.tags_like, ["tags_like_text"])
917 | self.assertEqual(args.host, "hostname")
918 | self.assertEqual(args.keep_tags, ["keep1", "keep2"])
919 | self.assertEqual(args.delete_by_hours, "24")
920 | self.assertEqual(args.keep_by_hours, "24")
921 | self.assertEqual(args.digest_method, "GET")
922 |
923 | def test_default_args(self):
924 | args_list = ["-r", "hostname",
925 | "-l", "loginstring"]
926 | args = parse_args(args_list)
927 | self.assertEqual(args.digest_method, "HEAD")
928 | self.assertFalse(args.order_by_date)
929 |
930 |
931 | if __name__ == '__main__':
932 | unittest.main()
933 |
--------------------------------------------------------------------------------