├── .gitignore
├── LICENSE.txt
├── MANIFEST.in
├── README
├── README.rst
├── bin
└── turbolift.local.py
├── docs
├── INSTALL_EMBED.rst
├── benchmarks.rst
├── command_line_args.rst
└── environment_vars.rst
├── examples
├── EXAMPLE_BACKUP_SCRIPT.sh
├── EXAMPLE_CONFIGFILE.cfg
├── EXAMPLE_ENVIRONMENT_FILE.rc
├── EXAMPLE_MYSQL_BACKUP_SCRIPT.sh
├── Example_Library_Usage
│ ├── create_container.py
│ ├── delete_objects.py
│ ├── list_containers.py
│ ├── list_objects.py
│ └── upload_files.py
└── SYNC_SFTP-CDN_SCRIPT.sh
├── requirements.txt
├── setup.py
├── test-requirements.txt
├── tox.ini
└── turbolift
├── __init__.py
├── authentication
├── __init__.py
├── auth.py
└── utils.py
├── clouderator
├── __init__.py
├── actions.py
└── utils.py
├── exceptions.py
├── executable.py
├── methods
├── __init__.py
├── archive.py
├── cdn_command.py
├── clone.py
├── delete_items.py
├── download.py
├── list_items.py
├── show_items.py
├── update_items.py
└── upload_items.py
├── utils.py
└── worker.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled source #
2 | ###################
3 | *.com
4 | *.class
5 | *.dll
6 | *.exe
7 | *.o
8 | *.so
9 | *.pyc
10 | build/
11 | dist/
12 |
13 | # Packages #
14 | ############
15 | # it's better to unpack these files and commit the raw source
16 | # git has its own built in compression methods
17 | *.7z
18 | *.dmg
19 | *.gz
20 | *.iso
21 | *.jar
22 | *.rar
23 | *.tar
24 | *.zip
25 |
26 | # Logs and databases #
27 | ######################
28 | *.log
29 | *.sql
30 | *.sqlite
31 |
32 | # OS generated files #
33 | ######################
34 | .DS_Store
35 | .DS_Store?
36 | ._*
37 | .Spotlight-V100
38 | .Trashes
39 | .idea
40 | .tox
41 | *.egg-info
42 | Icon?
43 | ehthumbs.db
44 | Thumbs.db
45 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include *.txt
2 |
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
1 | Turbolift, the Cloud Files Uploader
2 | ###################################
3 | :date: 2013-09-05 09:51
4 | :tags: rackspace, upload, mass, Cloud Files, files, api
5 | :category: \*nix
6 |
7 | Turbolift Files to Rackspace Cloud Files -Swift-
8 | ================================================
9 |
10 | General Overview
11 | ----------------
12 |
13 | If you have found yourself in a situation where you needed or wanted to upload a whole bunch of files to Cloud Files
14 | quickly, this is what you are looking for. Turbolift is an assistant for uploading files to the the Rackspace Cloud
15 | Files Repository with a bunch of options.
16 |
17 | You'll also probably want to read `The Rackspace Cloud Files API guide`__ (PDF) :
18 | The guide will provide you an overview of all of the available functions for Cloud Files.
19 |
20 | __ http://docs.rackspace.com/files/api/v1/cf-devguide/cf-devguide-latest.pdf
21 |
22 | The Process by which this application works is simple. All you have to do is Literally fill in the command line
23 | arguments and press enter. The application is a multiprocessing Cloud Files Uploader which will upload any directory
24 | or file provided to it.
25 |
26 | Functions of the Application :
27 | * Upload a directory, (recursively)
28 | * Upload a single file
29 | * Upload a local directory (recursively) and sync it with a Cloud Files Container
30 | * Download a Container to a local directory
31 | * Download changed objects from a Container to a local directory
32 | * Compresses a Local Directory, then uploads it
33 | * List all Containers
34 | * List all Objects in a Container
35 | * Delete an Object in a Container
36 | * Delete an entire Container
37 | * Clone one Container in one region to another Container in the same or Different Region.
38 | * Set Custom headers on Objects/Containers
39 |
40 |
41 | Turbolift can be managed with a config file. The option ``--system-config`` references a config file.
42 | Additionally, the Environment Variable ``TURBO_CONFIG`` can be used to reference a config file as well.
43 | All of Turbolift's options can be set in the config file. This makes managing Turbolift very simple.
44 |
45 | Please read `command_line_args`_ for more information on Command Line Arguments and functions.
46 |
47 |
48 | If you would like to setup Turbolift to use an environment variable file I would recommend you have a look at the `turboliftrc_example`_ file and the `environment_vars`_ document.
49 |
50 |
51 | Please also review the `Turbolift Wiki`_ for more information.
52 |
53 |
54 | Prerequisites :
55 | * For all the things to work right please make sure you have ``python-dev``.
56 | * All systems require the ``python-setuptools`` package.
57 | * Python => 2.6 but < 3.0
58 | * A File or some Files you want uploaded
59 |
60 | Installation :
61 | Installation is simple::
62 |
63 | git clone git://github.com/cloudnull/turbolift.git
64 | cd turbolift
65 | python setup.py install
66 |
67 | Installation NOTICE :
68 | If you are installing on a system that is not Running Python => 2.6 but < 3.0, please review the document `INSTALL_EMBED`_. This is a tested installation of Turbolift on Ubuntu 8.04, which ships with Python 2.5. The guide is a simple walk through for compiling stand alone python and installing Turbolift in that stand alone installation.
69 |
70 | Python Modules Needed, for full operation :
71 | NOTE : All of the modules needed should be part of the "standard" Library as of Python 2.6. The setup file will
72 | install the two needed dependencies which may not have made it onto your system.
73 |
74 |
75 | Application Usage
76 | -----------------
77 |
78 | Here is the Basic Usage
79 |
80 |
81 | .. code-block:: bash
82 |
83 | turbolift -u [CLOUD-USERNAME] -a [CLOUD-API-KEY] --os-rax-auth [REGION] upload -s [PATH-TO-DIRECTORY] -c [CONTAINER-NAME]
84 |
85 |
86 | Run ``turbolift -h`` for a full list of available flags and operations
87 |
88 |
89 | Turbolift can easily be set to run on via script or as a CRON job, please see, `turbolift_example_script`_ for more ideas / information on using Turbolift as a script.
90 |
91 |
92 | Systems Tested on
93 | -----------------
94 |
95 | The application has been tested on :
96 | * Debian 6
97 | * Ubuntu 10.04 - 12.04
98 | * Mac OS X 10.8
99 | * CentOS[RHEL] 6
100 |
101 |
102 | For information on Benchmarks from my own testing, please have a look here at the `benchmarks`_ file.
103 |
104 |
105 | Turbolift is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. The License in service for this program is GPLv3. please see http://www.gnu.org/licenses/gpl-3.0.txt for more information.
106 |
107 |
108 | .. _INSTALL_EMBED: https://github.com/cloudnull/turbolift/wiki/Install-Embed-Ubuntu
109 | .. _command_line_args: https://github.com/cloudnull/turbolift/wiki/Command-Line-Args
110 | .. _environment_vars: https://github.com/cloudnull/turbolift/wiki/Environment-Vars
111 | .. _benchmarks: https://github.com/cloudnull/turbolift/wiki/Benchmarks
112 | .. _turboliftrc_example: https://github.com/cloudnull/turbolift/wiki/Turbolift.rc-Example
113 | .. _turbolift_example_script: https://github.com/cloudnull/turbolift/wiki/Example-Script
114 | .. _Turbolift Wiki: https://github.com/cloudnull/turbolift/wiki
115 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | Turbolift, the Cloud Files Uploader
2 | ###################################
3 | :date: 2013-09-05 09:51
4 | :tags: rackspace, upload, mass, Cloud Files, files, api
5 | :category: \*nix
6 |
7 | Turbolift Files to Rackspace Cloud Files -Swift-
8 | ================================================
9 |
10 | General Overview
11 | ----------------
12 |
13 | If you have found yourself in a situation where you needed or wanted to upload a whole bunch of files to Cloud Files
14 | quickly, this is what you are looking for. Turbolift is an assistant for uploading files to the the Rackspace Cloud
15 | Files Repository with a bunch of options.
16 |
17 | You'll also probably want to read `The Rackspace Cloud Files API guide`__ (PDF) :
18 | The guide will provide you an overview of all of the available functions for Cloud Files.
19 |
20 | __ http://docs.rackspace.com/files/api/v1/cf-devguide/cf-devguide-latest.pdf
21 |
22 | The Process by which this application works is simple. All you have to do is Literally fill in the command line
23 | arguments and press enter. The application is a multiprocessing Cloud Files Uploader which will upload any directory
24 | or file provided to it.
25 |
26 | Functions of the Application :
27 | * Upload a directory, (recursively)
28 | * Upload a single file
29 | * Upload a local directory (recursively) and sync it with a Cloud Files Container
30 | * Download a Container to a local directory
31 | * Download changed objects from a Container to a local directory
32 | * Compresses a Local Directory, then uploads it
33 | * List all Containers
34 | * List all Objects in a Container
35 | * Delete an Object in a Container
36 | * Delete an entire Container
37 | * Clone one Container in one region to another Container in the same or Different Region.
38 | * Set Custom headers on Objects/Containers
39 |
40 |
41 | Turbolift can be managed with a config file. The option ``--system-config`` references a config file.
42 | Additionally, the Environment Variable ``TURBO_CONFIG`` can be used to reference a config file as well.
43 | All of Turbolift's options can be set in the config file. This makes managing Turbolift very simple.
44 |
45 | Please read `command_line_args`_ for more information on Command Line Arguments and functions.
46 |
47 |
48 | If you would like to setup Turbolift to use an environment variable file I would recommend you have a look at the `turboliftrc_example`_ file and the `environment_vars`_ document.
49 |
50 |
51 | Please also review the `Turbolift Wiki`_ for more information.
52 |
53 |
54 | Prerequisites :
55 | * For all the things to work right please make sure you have ``python-dev``.
56 | * All systems require the ``python-setuptools`` package.
57 | * Python => 2.6 but < 3.0
58 | * A File or some Files you want uploaded
59 |
60 | Installation :
61 | Installation is simple::
62 |
63 | git clone git://github.com/cloudnull/turbolift.git
64 | cd turbolift
65 | python setup.py install
66 |
67 | Installation NOTICE :
68 | If you are installing on a system that is not Running Python => 2.6 but < 3.0, please review the document `INSTALL_EMBED`_. This is a tested installation of Turbolift on Ubuntu 8.04, which ships with Python 2.5. The guide is a simple walk through for compiling stand alone python and installing Turbolift in that stand alone installation.
69 |
70 | Python Modules Needed, for full operation :
71 | NOTE : All of the modules needed should be part of the "standard" Library as of Python 2.6. The setup file will
72 | install the two needed dependencies which may not have made it onto your system.
73 |
74 |
75 | Application Usage
76 | -----------------
77 |
78 | Here is the Basic Usage
79 |
80 |
81 | .. code-block:: bash
82 |
83 | turbolift -u [CLOUD-USERNAME] -a [CLOUD-API-KEY] --os-rax-auth [REGION] upload -s [PATH-TO-DIRECTORY] -c [CONTAINER-NAME]
84 |
85 |
86 | Run ``turbolift -h`` for a full list of available flags and operations
87 |
88 |
89 | Turbolift can easily be set to run on via script or as a CRON job, please see, `turbolift_example_script`_ for more ideas / information on using Turbolift as a script.
90 |
91 |
92 | Systems Tested on
93 | -----------------
94 |
95 | The application has been tested on :
96 | * Debian 6
97 | * Ubuntu 10.04 - 12.04
98 | * Mac OS X 10.8
99 | * CentOS[RHEL] 6
100 |
101 |
102 | For information on Benchmarks from my own testing, please have a look here at the `benchmarks`_ file.
103 |
104 |
105 | Turbolift is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. The License in service for this program is GPLv3. please see http://www.gnu.org/licenses/gpl-3.0.txt for more information.
106 |
107 |
108 | .. _INSTALL_EMBED: https://github.com/cloudnull/turbolift/wiki/Install-Embed-Ubuntu
109 | .. _command_line_args: https://github.com/cloudnull/turbolift/wiki/Command-Line-Args
110 | .. _environment_vars: https://github.com/cloudnull/turbolift/wiki/Environment-Vars
111 | .. _benchmarks: https://github.com/cloudnull/turbolift/wiki/Benchmarks
112 | .. _turboliftrc_example: https://github.com/cloudnull/turbolift/wiki/Turbolift.rc-Example
113 | .. _turbolift_example_script: https://github.com/cloudnull/turbolift/wiki/Example-Script
114 | .. _Turbolift Wiki: https://github.com/cloudnull/turbolift/wiki
115 | .. _SLO / DLO docs: http://docs.openstack.org/developer/swift/overview_large_objects.html
116 |
--------------------------------------------------------------------------------
/bin/turbolift.local.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # =============================================================================
3 | # Copyright [2015] [Kevin Carter]
4 | # License Information :
5 | # This software has no warranty, it is provided 'as is'. It is your
6 | # responsibility to validate the behavior of the routines and its accuracy
7 | # using the code provided. Consult the GNU General Public license for further
8 | # details (see GNU General Public License).
9 | # http://www.gnu.org/licenses/gpl.html
10 | # =============================================================================
11 |
12 | import os
13 | import sys
14 |
15 | possible_topdir = os.path.normpath(
16 | os.path.join(
17 | os.path.abspath(sys.argv[0]),
18 | os.pardir,
19 | os.pardir
20 | )
21 | )
22 |
23 | base_path = os.path.join(possible_topdir, 'turbolift', '__init__.py')
24 | if os.path.exists(base_path):
25 | sys.path.insert(0, possible_topdir)
26 |
27 | from turbolift import executable
28 | executable.execute()
29 |
--------------------------------------------------------------------------------
/docs/INSTALL_EMBED.rst:
--------------------------------------------------------------------------------
1 | Install Python Source and Turbolift
2 | ###################################
3 | :date: 2012-02-14 16:22
4 | :tags: rackspace, upload, mass, Cloud Files, files, api
5 | :category: \*nix
6 |
7 |
8 | Installing Dependencies
9 | ^^^^^^^^^^^^^^^^^^^^^^^
10 |
11 | **To install Python 2.6/2.7 on a system that does not have it, you will need the following.**
12 |
13 | * build-essential
14 | * git-core
15 | * curl
16 | * openssl
17 | * libssl-dev
18 |
19 | *Overview*:
20 | You must have root (sudo) access to your system and or the ability to locally compile. You need to have GCC and make, which will be used to compile python. You will also need to have git, openssl and the ssl development files installed on your system.
21 |
22 |
23 | Note:
24 | I tested this installation on Ubuntu 8.04LTS which was shipped with Python 2.5. Here is the Ubuntu ISO I used : http://old-releases.ubuntu.com/releases/hardy/
25 |
26 |
27 | Here is the command that I ran to get the needed system dependencies in Ubuntu 8.04
28 |
29 | .. code-block:: bash
30 |
31 | apt-get update && apt-get install build-essential git-core curl openssl libssl-dev
32 |
33 |
34 | Installing Python2.7
35 | ^^^^^^^^^^^^^^^^^^^^
36 |
37 | Information based on http://docs.python.org/2/using/unix.html#getting-and-installing-the-latest-version-of-python
38 |
39 | .. code-block:: bash
40 |
41 | # go to temp dir
42 | cd /tmp
43 |
44 | # Get the source
45 | wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz
46 |
47 | # uncompress and go to directory
48 | tar -xzf Python-2.7.5.tgz
49 | cd Python-2.7.5
50 |
51 | # Configure the build with a prefix (install dir) of /opt/python27, compile, and install.
52 | ./configure --prefix=/opt/python27
53 | make
54 | make install
55 |
56 | # now go to your new installation of python and test.
57 | /opt/python27/bin/python -V
58 |
59 |
60 | You are going to need the package `setuptools` as well, so we might as well install that now. Information found here https://pypi.python.org/pypi/setuptools/0.8#installation-instructions
61 |
62 | .. code-block:: bash
63 |
64 | # Install setuptools python module
65 | wget --no-check-certificate https://bitbucket.org/pypa/setuptools/raw/0.8/ez_setup.py -O - | /opt/python27/bin/python
66 |
67 |
68 | Installing Turbolift
69 | ^^^^^^^^^^^^^^^^^^^^
70 |
71 | .. code-block:: bash
72 |
73 | # Information based on https://github.com/cloudnull/turbolift
74 |
75 | # Get the source
76 | git clone git://github.com/cloudnull/turbolift.git
77 |
78 | # go to the turbolift directory
79 | cd turbolift
80 |
81 | # Install turbolift with the new version of Python
82 | /opt/python27/bin/python setup.py install
83 |
84 |
85 | Your path to the turbolift application will be `/opt/python27/bin/turbolift`
86 |
87 |
88 | Done. That was easy
89 | ^^^^^^^^^^^^^^^^^^^
90 |
91 | I recommend that you add the new installation of Python to your local Path, however this is not required.
92 |
93 | .. code-block:: bash
94 |
95 | # to make the application more accessible, add /opt/python27/bin to your PATH.
96 | echo 'PATH=$PATH:/opt/python27/bin' >> $HOME/.bashrc
97 |
98 |
--------------------------------------------------------------------------------
/docs/benchmarks.rst:
--------------------------------------------------------------------------------
1 | Turbolift, the Cloud Files Uploader
2 | ###################################
3 | :date: 2013-09-05 09:51
4 | :tags: rackspace, upload, mass, Cloud Files, files, api
5 | :category: \*nix
6 |
7 | Turbolift Files to Rackspace Cloud Files -Swift-
8 | ================================================
9 |
10 | Bench Marks
11 | -----------
12 |
13 | To show the speed of the application here are some benchmarks on uploading 30,000 64K files to a single container.
14 |
15 |
16 | Definitions and Information:
17 | * ``ServiceNet`` - is the internal network found on all Rackspace Cloud Servers. When Using ServiceNet Uploads are sent over the internal network interface to the Cloud Files repository found in the same Data Center. `You can NOT use ServiceNet to upload to a different Data Center.`
18 | * ``Public Network`` - Uploads sent over the general Internet to a Cloud Files repository
19 | * Total Size of all 30,000 files ``1875M``
20 | * Test performed on a Rackspace Cloud Server at the size 512MB
21 |
22 | * 20 Mbps Public interface
23 | * 40 Mbps Internal Interface
24 |
25 |
26 | Command Used For Tests::
27 |
28 | time turbolift --cc 150 --os-rax-auth $location upload --source /tmp/uptest/ --container $location-Test-$num
29 |
30 |
31 | **Note that the username and api authentication key have been exported into local environment variables**
32 |
33 |
34 | Test Results Using ServiceNet :
35 | :Test 1: 7m25.459s
36 | :Test 2: 7m25.459s
37 | :Test 3: 7m26.990s
38 | :Avg Time: 7 Minutes, 25.9 Seconds
39 |
40 |
41 | Test Results Using The Public Network :
42 | :Test 1: 14m43.879s
43 | :Test 2: 14m1.751s
44 | :Test 3: 13m37.173s
45 | :Avg Time: 13 Minutes, 9.95 Seconds
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/docs/command_line_args.rst:
--------------------------------------------------------------------------------
1 | Turbolift, the Cloud Files Uploader
2 | ###################################
3 | :date: 2013-09-05 09:51
4 | :tags: rackspace, upload, mass, Cloud Files, files, api
5 | :category: \*nix
6 |
7 | Turbolift Files to Rackspace Cloud Files -Swift-
8 | ================================================
9 |
10 | Command Line Arguments
11 | ----------------------
12 |
13 | Authentication Arguments:
14 | ~~~~~~~~~~~~~~~~~~~~~~~~~
15 |
16 | - ``os-apikey`` | APIKEY for the Cloud Account
17 | - ``os-password`` | Password for the Cloud Account
18 | - ``os-user`` | Username for the Cloud Account
19 | - ``os-tenant`` | Specify the users tenantID
20 | - ``os-token`` | Specify a token for TOKEN Authentication
21 | - ``os-region`` | Specify an Endpoint
22 | - ``os-rax-auth`` | Specify a Rackspace Cloud Auth-URL and Endpoint [ dfw, ord, lon, iad, syd, hkg ].
23 | - ``os-hp-auth`` | Specify an HP Cloud Auth-URL and Endpoint [ region-b.geo-1 ]. Notice that HP only have ONE Swift region at this time.
24 | - ``os-auth-url`` | Specify the Auth URL
25 | - ``os-version`` | Gives Version Number
26 |
27 |
28 | Optional Arguments:
29 | ~~~~~~~~~~~~~~~~~~~
30 |
31 | - ``help`` | Show helpful information on the script and its available functions
32 | - ``preserve-path`` | Preserves the File Path when uploading to a container. Useful for pesudo directory structure.
33 | - ``internal`` | Use ServiceNet Endpoint for Cloud Files
34 | - ``error-retry`` | Allows for a retry integer to be set, Default is 5
35 | - ``cc`` | Operational Concurrency
36 | - ``service-type`` | Override the service type
37 | - ``system-config`` | Allows Turbolift to use a config file for it's credentials.
38 | - ``quiet`` | Makes Turbolift Quiet
39 | - ``verbose`` | Shows Progress While Uploading
40 | - ``debug`` | Turn up verbosity to over 9000
41 |
42 |
43 | Header Arguments:
44 | ~~~~~~~~~~~~~~~~~
45 |
46 | - ``base-headers`` | Allows for the use of custom headers as the base Header
47 | - ``container-headers`` | Allows for custom headers to be set on Container(s)
48 | - ``object-headers`` | Allows for custom headers to be set on Object(s)
49 |
50 |
51 | Positional Arguments:
52 | ~~~~~~~~~~~~~~~~~~~~~
53 |
54 | - ``upload`` | Use the Upload Function for a local Source.
55 | - ``tsync`` | DEPRECATED, use ``upload --sync``
56 | - ``archive`` | Compress files or directories into a single archive. Multiple Source Directories can be added to a single Archive.
57 | - ``delete`` | Deletes all of the files that are found in a container, This will also delete the container by default.
58 | - ``download`` | Downloads all of the files in a container to a provided source. This also downloads all of the pesudo directories and its contents, while preserving the structure.
59 | - ``list`` | List all containers or objects in a container.
60 | - ``show`` | Information on a container or object in a container.
61 | - ``clone`` | Clone a container to another container to the same or different region.
62 | - ``cdn-command`` | Enable / Disable the CDN on a Container. Additional Headers can be set with this function.
63 |
64 | All Positional arguments ALL have additional Help information. To see this additional help information, please use `` -h/--help``
65 |
--------------------------------------------------------------------------------
/docs/environment_vars.rst:
--------------------------------------------------------------------------------
1 | Turbolift, the Cloud Files Uploader
2 | ###################################
3 | :date: 2013-09-05 09:51
4 | :tags: rackspace, upload, mass, Cloud Files, files, api
5 | :category: \*nix
6 |
7 | Turbolift Files to Rackspace Cloud Files -Swift-
8 | ================================================
9 |
10 | Environment Variables
11 | ---------------------
12 |
13 | The Application can except Environment Variables for simpler authentication if you are commonly uploading files to the same user environment::
14 |
15 | # COMMON TURBOLIFT ENVS, THESE ARE THE BASIC REQUIREMENTS
16 | # =======================================================
17 | export OS_USERNAME=YOU_USERNAME
18 | export OS_API_KEY=SOME_RANDOM_SET_OF_THINGS
19 | export OS_RAX_AUTH=THE_NAME_OF_THE_TARGET_REGION
20 |
21 |
22 | # NOT REQUIRED FOR AUTH
23 | #export OS_PASSWORD=USED_FOR_PASSWORD_AUTH
24 | #export OS_TENANT=OPENSTACK_TENANT_NAME
25 | #export OS_TOKEN=USED_FOR_TOKEN_AUTH
26 | #export OS_REGION_NAME=REGION_NAME
27 | #export OS_AUTH_URL=AUTH_URL_SET_IF_NEEDED
28 |
29 | # NOT REQUIRED OPTIONS
30 | #export TURBO_CONFIG=PATH_TO_CONFIG_FILE
31 | #export TURBO_LOGS=LOG_LOCATION
32 | #export TURBO_ERROR_RETRY=INT
33 | #export TURBO_CONCURRENCY=INT
34 | #export TURBO_QUIET=True|False
35 | #export TURBO_VERBOSE=True|False
36 | #export TURBO_DEBUG=True|False
37 | #export TURBO_INTERNAL=True|False
38 |
39 |
40 | NOTE: that these variables are similar with the Openstack NOVA compute project's NOVA client environment variables. You'll may want to read more about the `Rackspace NOVA Client`_ which contains more information on these variables and the inner workings of The Rackspace Public Cloud.
41 |
42 |
43 | .. _Rackspace NOVA Client: https://github.com/rackspace/rackspace-novaclient
--------------------------------------------------------------------------------
/examples/EXAMPLE_BACKUP_SCRIPT.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # =============================================================================
3 | # Copyright [2015] [Kevin Carter]
4 | # License Information :
5 | # This software has no warranty, it is provided 'as is'. It is your
6 | # responsibility to validate the behavior of the routines and its accuracy
7 | # using the code provided. Consult the GNU General Public license for further
8 | # details (see GNU General Public License).
9 | # http://www.gnu.org/licenses/gpl.html
10 | # =============================================================================
11 |
12 | # THIS IS REQUIRED, replace the quoted values with the correct information.
13 | APIKEY=""
14 | USERNAME=""
15 | REGION=""
16 |
17 |
18 | # Auth URL for Rackspace Cloud.
19 | AUTHURL="identity.api.rackspacecloud.com/v2.0"
20 |
21 |
22 | # THIS IS REQUIRED - Space Separated list of places or objects you want backed up.
23 | # Example: BACKUP_LIST="/home/kevin /etc/something /some/other/dir"
24 | BACKUP_LIST=""
25 |
26 |
27 | # THIS IS OPTIONAL - Turbolift Arguments, see `turbolift -h` for more information.
28 | OPTIONAL_ARGS=""
29 |
30 |
31 | # THIS IS OPTIONAL - Turbolift Additional Arguments, see `turbolift upload -h` for more information.
32 | ADDITIONAL_ARGS="--sync"
33 |
34 |
35 | # THIS IS THE PART YOU SHOULD NOT TOUCH UNLESS YOU KNOW WHAT YOU ARE DOING.
36 | # =========================================================================
37 |
38 | # Set Turbolift
39 | TURBOLIFT="turbolift -u ${USERNAME} -a ${APIKEY} --os-auth-url ${AUTHURL} --os-region ${REGION} ${OPTIONAL_ARGS}"
40 |
41 | # Backup Action - NOTICE THAT all "/" or "\" will be replaced with "_" in the container name, upon creation.
42 | for BACKUP_DIR in ${BACKUP_LIST}
43 | do
44 | ${TURBOLIFT} upload ${ADDITIONAL_ARGS} -s ${BACKUP_DIR} -c ${HOSTNAME}-$(echo ${BACKUP_DIR} | sed 's/\//\_/g') ${ADDITIONAL_ARGS}
45 | sleep 2
46 | done
47 |
--------------------------------------------------------------------------------
/examples/EXAMPLE_CONFIGFILE.cfg:
--------------------------------------------------------------------------------
1 | # ==============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy using
6 | # the code provided. Consult the GNU General Public license for further details
7 | # (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # ==============================================================================
10 |
11 | # NOTICE: ALL CLI Arguments can be used in this file.
12 |
13 | [Turbolift]
14 | os_user = USERNAME
15 | os_rax_auth = DC
16 | os_apikey = APIKEY
17 |
--------------------------------------------------------------------------------
/examples/EXAMPLE_ENVIRONMENT_FILE.rc:
--------------------------------------------------------------------------------
1 | # COMMON OPENSTACK ENVS TO UNSET
2 | unset OS_USERNAME
3 | unset OS_PASSWORD
4 | unset OS_TENANT
5 | unset OS_TENANT_NAME
6 | unset OS_AUTH_URL
7 | unset OS_REGION_NAME
8 | unset OS_VERSION
9 | unset OS_AUTH_SYSTEM
10 | unset OS_SERVICE_NAME
11 | unset OS_RAX_AUTH
12 | unset OS_NO_CACHE
13 | unset OS_AUTH_STRATEGY
14 |
15 | # COMMON TURBOLIFT ENVS TO UNSET
16 | unset TURBO_ERROR_RETRY
17 | unset TURBO_CONCURRENCY
18 | unset TURBO_QUIET
19 | unset TURBO_VERBOSE
20 | unset TURBO_DEBUG
21 | unset TURBO_INTERNAL
22 |
23 | # COMMON TURBOLIFT ENVS, THESE ARE THE BASIC REQUIREMENTS
24 | # =======================================================
25 | export OS_USERNAME=YOU_USERNAME
26 | export OS_API_KEY=SOME_RANDOM_SET_OF_THINGS
27 | export OS_RAX_AUTH=THE_NAME_OF_THE_TARGET_REGION
28 |
29 |
30 | # NOT REQUIRED FOR AUTH
31 | #export OS_PASSWORD=USED_FOR_PASSWORD_AUTH
32 | #export OS_TENANT=OPENSTACK_TENANT_NAME
33 | #export OS_TOKEN=USED_FOR_TOKEN_AUTH
34 | #export OS_REGION_NAME=REGION_NAME
35 | #export OS_AUTH_URL=AUTH_URL_SET_IF_NEEDED
36 |
37 | # NOT REQUIRED OPTIONS
38 | #export TURBO_ERROR_RETRY=INT
39 | #export TURBO_CONCURRENCY=INT
40 | #export TURBO_QUIET=True|False
41 | #export TURBO_VERBOSE=True|False
42 | #export TURBO_DEBUG=True|False
43 | #export TURBO_INTERNAL=True|False
--------------------------------------------------------------------------------
/examples/EXAMPLE_MYSQL_BACKUP_SCRIPT.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # =============================================================================
3 | # Copyright [2015] [Kevin Carter]
4 | # License Information :
5 | # This software has no warranty, it is provided 'as is'. It is your
6 | # responsibility to validate the behavior of the routines and its accuracy
7 | # using the code provided. Consult the GNU General Public license for further
8 | # details (see GNU General Public License).
9 | # http://www.gnu.org/licenses/gpl.html
10 | # =============================================================================
11 |
12 | # Purpose:
13 | # This script will backup all of the databases found in MySQL as individual
14 | # databases. Once the backup is complete a tarball will be created of all
15 | # databases which were found and dumped as ".sql" files. Finally if
16 | # Turbolift is installed and a settings file has been created containing
17 | # your credentials the backed up databases will be saved in a cloudfiles
18 | # container.
19 |
20 | set -e
21 |
22 | # Set .my.cnf variable
23 | MYSQL_CRED_FILE="/root/.my.cnf"
24 |
25 | # Set the database backup directory
26 | BACKUP_LOCATION="/opt/backup/databases"
27 |
28 | # Set the turbolift settings file
29 | TURBOLIFT_CONFIG="/etc/turbolift.cfg"
30 |
31 | export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
32 |
33 | # Make sure mysql CLI clients are found.
34 | if [ ! "$(which mysql)" ];then
35 | echo "mysql client not installed"
36 | exit 1
37 | fi
38 |
39 | # Make sure mysqldump CLI clients are found.
40 | if [ ! "$(which mysqldump)" ];then
41 | echo "mysqldump client not installed"
42 | exit 1
43 | fi
44 |
45 | # Check if the my.cnf file exists
46 | if [ ! -f "${MYSQL_CRED_FILE}" ];then
47 | echo "MySQL .my.cnf file was not found."
48 | exit 1
49 | fi
50 |
51 | # Check for backup directory
52 | if [ ! -d "${BACKUP_LOCATION}" ];then
53 | mkdir -p ${BACKUP_LOCATION}
54 | fi
55 |
56 | # Get value from mysql file
57 | function getcred(){
58 | grep "${1}" ${MYSQL_CRED_FILE} | awk -F'=' '{print $2}' | awk '{$1=$1}{ print }'
59 | }
60 |
61 | # Get a list of all of the databases
62 | function getdatabases(){
63 | mysql --silent \
64 | --skip-column-names \
65 | -u"${MYSQL_USERNAME}" \
66 | -p"${MYSQL_PASSWORD}" \
67 | -e "show databases;" | grep -v "performance_schema"
68 | }
69 |
70 | MYSQL_USERNAME=$(getcred "user")
71 | MYSQL_PASSWORD=$(getcred "password")
72 | MYSQL_DATABASES=$(getdatabases)
73 |
74 | # Backup the databases separately
75 | for db in ${MYSQL_DATABASES};do
76 | mysqldump --events \
77 | --skip-lock-tables \
78 | -u"${MYSQL_USERNAME}" \
79 | -p"${MYSQL_PASSWORD}" \
80 | ${db} > ${BACKUP_LOCATION}/${db}.sql
81 | done
82 |
83 | # Compress all of the databases
84 | tar -czf /tmp/database-tarball.tgz ${BACKUP_LOCATION} > /dev/null 2>&1
85 | if [ -f "/tmp/database-tarball.tgz" ];then
86 | mv /tmp/database-tarball.tgz ${BACKUP_LOCATION}/database-tarball.tgz
87 | fi
88 |
89 | # Backup the databases which were just backed up
90 | if [ "$(which turbolift)" ];then
91 | if [ -f "${TURBOLIFT_CONFIG}" ];then
92 | turbolift --quiet \
93 | --system-config ${TURBOLIFT_CONFIG} \
94 | upload \
95 | -c backup-databases \
96 | -s "${BACKUP_LOCATION}"
97 | fi
98 | fi
99 |
100 |
101 |
--------------------------------------------------------------------------------
/examples/Example_Library_Usage/create_container.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import os
12 |
13 |
14 | HOME = os.getenv('HOME')
15 |
16 |
17 | # Set some default args
18 | import turbolift
19 | args = turbolift.ARGS = {
20 | 'os_user': 'YOURUSERNAME', # Username
21 | 'os_apikey': 'YOURAPIKEY', # API-Key
22 | 'os_rax_auth': 'YOURREGION', # RAX Region, must be UPPERCASE
23 | 'error_retry': 5, # Number of failure retries
24 | 'quiet': True # Make the application not print stdout
25 | }
26 |
27 |
28 | # Load our Logger
29 | from turbolift.logger import logger
30 | log_method = logger.load_in(
31 | log_level='info',
32 | log_file='turbolift_library',
33 | log_location=HOME
34 | )
35 |
36 |
37 | # Load our constants
38 | turbolift.load_constants(log_method, args)
39 |
40 |
41 | # Authenticate against the swift API
42 | from turbolift.authentication import auth
43 | authentication = auth.authenticate()
44 |
45 |
46 | # Package up the Payload
47 | import turbolift.utils.http_utils as http
48 | payload = http.prep_payload(
49 | auth=auth,
50 | container=args.get('container'),
51 | source=args.get('source'),
52 | args=args
53 | )
54 |
55 |
56 | # Load all of our available cloud actions
57 | from turbolift.clouderator import actions
58 | cf_actions = actions.CloudActions(payload=payload)
59 |
60 |
61 | # Create a Container if it does not already exist
62 | # =============================================================================
63 | kwargs = {
64 | 'url': payload['url'], # Defines the Upload URL
65 | 'container': payload['c_name'] # Sets the container
66 | }
67 |
68 | # Create the container if needed
69 | create_container = cf_actions.container_create(**kwargs)
70 | print('Container Created: "%s"' % create_container)
71 |
--------------------------------------------------------------------------------
/examples/Example_Library_Usage/delete_objects.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import os
12 |
13 |
14 | HOME = os.getenv('HOME')
15 |
16 |
17 | # Set some default args
18 | import turbolift
19 | args = turbolift.ARGS = {
20 | 'os_user': 'YOURUSERNAME', # Username
21 | 'os_apikey': 'YOURAPIKEY', # API-Key
22 | 'os_rax_auth': 'YOURREGION', # RAX Region, must be UPPERCASE
23 | 'error_retry': 5, # Number of failure retries
24 | 'container': 'test9000', # Name of the container
25 | 'quiet': True, # Make the application not print stdout
26 | 'batch_size': 30000 # The number of jobs to do per cycle
27 | }
28 |
29 |
30 | # Load our Logger
31 | from turbolift.logger import logger
32 | log_method = logger.load_in(
33 | log_level='info',
34 | log_file='turbolift_library',
35 | log_location=HOME
36 | )
37 |
38 |
39 | # Load our constants
40 | turbolift.load_constants(log_method, args)
41 |
42 |
43 | # Authenticate against the swift API
44 | from turbolift.authentication import auth
45 | authentication = auth.authenticate()
46 |
47 |
48 | # Package up the Payload
49 | import turbolift.utils.http_utils as http
50 | payload = http.prep_payload(
51 | auth=auth,
52 | container=args.get('container'),
53 | source=args.get('source'),
54 | args=args
55 | )
56 |
57 |
58 | # Load all of our available cloud actions
59 | from turbolift.clouderator import actions
60 | cf_actions = actions.CloudActions(payload=payload)
61 |
62 |
63 | # Delete file(s)
64 | # =============================================================================
65 | import turbolift.utils.multi_utils as multi
66 |
67 | kwargs = {
68 | 'url': payload['url'], # Defines the Upload URL
69 | 'container': payload['c_name'] # Sets the container
70 | }
71 |
72 | # Return a list of all objects that we will delete
73 | objects, list_count, last_obj = cf_actions.object_lister(**kwargs)
74 |
75 | # Get a list of all of the object names
76 | object_names = [obj['name'] for obj in objects]
77 |
78 | # Set the delete job
79 | kwargs['cf_job'] = cf_actions.object_deleter
80 |
81 | # Perform the upload job
82 | multi.job_processer(
83 | num_jobs=list_count,
84 | objects=object_names,
85 | job_action=multi.doerator,
86 | concur=50,
87 | kwargs=kwargs
88 | )
89 |
--------------------------------------------------------------------------------
/examples/Example_Library_Usage/list_containers.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import os
12 | import json
13 |
14 |
15 | HOME = os.getenv('HOME')
16 |
17 |
18 | # Set some default args
19 | import turbolift
20 | args = turbolift.ARGS = {
21 | 'os_user': 'YOURUSERNAME', # Username
22 | 'os_apikey': 'YOURAPIKEY', # API-Key
23 | 'os_rax_auth': 'YOURREGION', # RAX Region, must be UPPERCASE
24 | 'error_retry': 5, # Number of failure retries
25 | 'quiet': True # Make the application not print stdout
26 | }
27 |
28 |
29 | # Load our Logger
30 | from turbolift.logger import logger
31 | log_method = logger.load_in(
32 | log_level='info',
33 | log_file='turbolift_library',
34 | log_location=HOME
35 | )
36 |
37 |
38 | # Load our constants
39 | turbolift.load_constants(log_method, args)
40 |
41 |
42 | # Authenticate against the swift API
43 | from turbolift.authentication import auth
44 | authentication = auth.authenticate()
45 |
46 |
47 | # Package up the Payload
48 | import turbolift.utils.http_utils as http
49 | payload = http.prep_payload(
50 | auth=auth,
51 | container=args.get('container'),
52 | source=args.get('source'),
53 | args=args
54 | )
55 |
56 |
57 | # Load all of our available cloud actions
58 | from turbolift.clouderator import actions
59 | cf_actions = actions.CloudActions(payload=payload)
60 |
61 |
62 | # List Containers
63 | # =============================================================================
64 | kwargs = {
65 | 'url': payload['url']
66 | }
67 | containers, list_count, last_container = cf_actions.container_lister(**kwargs)
68 | print(json.dumps(containers, indent=2))
69 | print('number of containers: [ %s ]' % list_count)
70 | print('Last container in query: [ %s ]' % last_container)
71 |
--------------------------------------------------------------------------------
/examples/Example_Library_Usage/list_objects.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import os
12 | import json
13 |
14 |
15 | HOME = os.getenv('HOME')
16 |
17 |
18 | # Set some default args
19 | import turbolift
20 | args = turbolift.ARGS = {
21 | 'os_user': 'YOURUSERNAME', # Username
22 | 'os_apikey': 'YOURAPIKEY', # API-Key
23 | 'os_rax_auth': 'YOURREGION', # RAX Region, must be UPPERCASE
24 | 'error_retry': 5, # Number of failure retries
25 | 'quiet': True, # Make the application not print stdout
26 | 'container': 'test9000' # Name of the container
27 | }
28 |
29 |
30 | # Load our Logger
31 | from turbolift.logger import logger
32 | log_method = logger.load_in(
33 | log_level='info',
34 | log_file='turbolift_library',
35 | log_location=HOME
36 | )
37 |
38 |
39 | # Load our constants
40 | turbolift.load_constants(log_method, args)
41 |
42 |
43 | # Authenticate against the swift API
44 | from turbolift.authentication import auth
45 | authentication = auth.authenticate()
46 |
47 |
48 | # Package up the Payload
49 | import turbolift.utils.http_utils as http
50 | payload = http.prep_payload(
51 | auth=auth,
52 | container=args.get('container'),
53 | source=args.get('source'),
54 | args=args
55 | )
56 |
57 |
58 | # Load all of our available cloud actions
59 | from turbolift.clouderator import actions
60 | cf_actions = actions.CloudActions(payload=payload)
61 |
62 |
63 | # List Objects
64 | # =============================================================================
65 | kwargs = {
66 | 'url': payload['url'], # Defines the Upload URL
67 | 'container': payload['c_name'] # Sets the container
68 | }
69 |
70 | # Return a list of all objects that we will delete
71 | objects, list_count, last_obj = cf_actions.object_lister(**kwargs)
72 | print(json.dumps(objects, indent=2))
73 | print('number of containers: [ %s ]' % list_count)
74 | print('Last object in query: [ %s ]' % last_obj)
75 |
--------------------------------------------------------------------------------
/examples/Example_Library_Usage/upload_files.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 | import os
11 |
12 | HOME = os.getenv('HOME')
13 |
14 |
15 | # Set some default args
16 | import turbolift
17 | args = turbolift.ARGS = {
18 | 'os_user': 'YOURUSERNAME', # Username
19 | 'os_apikey': 'YOURAPIKEY', # API-Key
20 | 'os_rax_auth': 'YOURREGION', # RAX Region, must be UPPERCASE
21 | 'error_retry': 5, # Number of failure retries
22 | 'source': '/tmp/files', # local source for files to be uploaded
23 | 'container': 'test9000', # Name of the container
24 | 'quiet': True, # Make the application not print stdout
25 | 'batch_size': 30000 # The number of jobs to do per cycle
26 | }
27 |
28 |
29 | # Load our Logger
30 | from turbolift.logger import logger
31 | log_method = logger.load_in(
32 | log_level='info',
33 | log_file='turbolift_library',
34 | log_location=HOME
35 | )
36 |
37 |
38 | # Load our constants
39 | turbolift.load_constants(log_method, args)
40 |
41 |
42 | # Authenticate against the swift API
43 | from turbolift.authentication import auth
44 | authentication = auth.authenticate()
45 |
46 |
47 | # Package up the Payload
48 | import turbolift.utils.http_utils as http
49 | payload = http.prep_payload(
50 | auth=auth,
51 | container=args.get('container'),
52 | source=args.get('source'),
53 | args=args
54 | )
55 |
56 |
57 | # Load all of our available cloud actions
58 | from turbolift.clouderator import actions
59 | cf_actions = actions.CloudActions(payload=payload)
60 |
61 |
62 | # Upload file(s)
63 | # =============================================================================
64 | import turbolift.utils.multi_utils as multi
65 | from turbolift import methods
66 |
67 | f_indexed = methods.get_local_files() # Index all of the local files
68 | num_files = len(f_indexed) # counts the indexed files
69 |
70 | kwargs = {
71 | 'url': payload['url'], # Defines the Upload URL
72 | 'container': payload['c_name'], # Sets the container
73 | 'source': payload['source'], # Defines the local source to upload
74 | 'cf_job': cf_actions.object_putter # sets the job
75 | }
76 |
77 | # Perform the upload job
78 | multi.job_processer(
79 | num_jobs=num_files,
80 | objects=f_indexed,
81 | job_action=multi.doerator,
82 | concur=25,
83 | kwargs=kwargs
84 | )
85 |
--------------------------------------------------------------------------------
/examples/SYNC_SFTP-CDN_SCRIPT.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright (C) 2013 Alexandru Iacob
4 | #
5 | # This program is free software; you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation; either version 2 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License along
16 | # with this program; if not, write to the Free Software Foundation, Inc.,
17 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 | ######################################################################################################
19 | set -o nounset
20 | set -o pipefail # if you fail on this line, get a newer version of BASH.
21 | ######################################################################################################
22 | # IMPORTANT !!!
23 | # check if we are the only running instance
24 | #
25 | PDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
26 | LOCK_FILE=`basename $0`.lock
27 |
28 | if [ -f "${LOCK_FILE}" ]; then
29 | # The file exists so read the PID
30 | # to see if it is still running
31 | MYPID=`head -n 1 "${LOCK_FILE}"`
32 |
33 | TEST_RUNNING=`ps -p ${MYPID} | grep ${MYPID}`
34 |
35 | if [ -z "${TEST_RUNNING}" ]; then
36 | # The process is not running
37 | # Echo current PID into lock file
38 | # echo "Not running"
39 | echo $$ > "${LOCK_FILE}"
40 | else
41 | echo "`basename $0` is already running [${MYPID}]"
42 | exit 0
43 | fi
44 | else
45 | echo $$ > "${LOCK_FILE}"
46 | fi
47 | # make sure the LOCK_FILE is removed when we exit
48 | trap "rm -f ${LOCK_FILE}" INT TERM EXIT
49 |
50 | ######################################################################################################
51 | # Text color variables
52 | bold=$(tput bold) # Bold
53 | red=${bold}$(tput setaf 1) # Red
54 | blue=${bold}$(tput setaf 4) # Blue
55 | green=${bold}$(tput setaf 2) # Green
56 | txtreset=$(tput sgr0) # Reset
57 | ######################################################################################################
58 | # Checking availability of turbolift
59 | which turbolift &> /dev/null
60 |
61 | [ $? -ne 0 ] && \
62 | echo "" && \
63 | echo "${red}Turbolift utility is not available ... Install it${txtreset}" && \
64 | echo "" && \
65 | echo "${green}Prerequisites :${txtreset}" && \
66 | echo "For all the things to work right please make sure you have python-dev" && \
67 | echo "All systems require the python-setuptools package." && \
68 | echo "Python => 2.6 but < 3.0" && \
69 | echo "A File or some Files you want uploaded" && \
70 | echo "" && \
71 | echo "${green}Installation :${txtreset}" && \
72 | echo "git clone git://github.com/cloudnull/turbolift.git" && \
73 | echo "cd turbolift" && \
74 | echo "python setup.py install" && \
75 | echo "" && \
76 | echo "${red}Script terminated.${txtreset}" && \
77 | exit 1
78 | ######################################################################################################
79 | # GLOBALS
80 | SCRIPT_SOURCE="${BASH_SOURCE[0]}"
81 | SCRIPT_DIR="$( cd -P "$( dirname "$SCRIPT_SOURCE" )" && pwd )"
82 | SCRIPT_NAME="${0##*/}"
83 | shopt -s globstar
84 | _now=$(date +"%Y-%m-%d_%T")
85 |
86 | # we will clean the obsolete files from the CDN container at specified time
87 | # Store some timestamps for comparison.
88 | declare -i _elapsed=$(date +%s)
89 | # change below according to your needs
90 | declare -i _clean_time=$(date -d "03:30:00 Saturday" +%s)
91 |
92 | declare -r LOG_DIR="/var/log/cdn-sync"
93 | declare -r log_file="$LOG_DIR/CDN-sync_$_now"
94 | declare -r CDN_log_file="$LOG_DIR/CDN-log"
95 | declare -r log_removed="$LOG_DIR/CDN-remove_$_now"
96 |
97 | # Some default values
98 | CDN_ID="" # add your ID
99 | CDN_KEY="" # add your API KEY
100 | # Rackspace currently has five compute regions which may be used:
101 | # dfw -> Dallas/Forth Worth
102 | # ord -> Chicago
103 | # syd -> Sydney
104 | # lon -> London
105 | # iad -> Northern Virginia
106 | # Note: Currently the LON region is only avaiable with a UK account, and UK accounts cannot access other regions (check with Rackspace)
107 | CDN_REGION="" # specify region
108 | CDN_CONTAINER="" # specify container name
109 | SFTP_CONTAINER="" # change this
110 | SFTP_FILES="$LOG_DIR/sftp-files"
111 | ######################################################################################################
112 | # Turbolift requires root privileges
113 | ROOT_UID=0 # Root has $UID 0.
114 | E_NOTROOT=101 # Not root user error.
115 |
116 | function check_if_root (){ # is root running the script?
117 |
118 | if [ "$UID" -ne "$ROOT_UID" ]
119 | then
120 | echo ""
121 | echo "$(tput bold)${red}Ooops! Must be root to run this script.${txtreset}"
122 | echo ""
123 | #clear
124 | exit $E_NOTROOT
125 | fi
126 | }
127 | ######################################################################################################
128 | # Prepare LOG ENV
129 | function make_log_env(){
130 | echo ""
131 | echo "Checking for LOG ENVIRONMENT in $(tput bold)${green}$LOG_DIR${txtreset}"
132 | if [ ! -d "$LOG_DIR" ]; then
133 | echo "$(tput bold)${red}LOG environment not present...${txtreset}" && \
134 | echo "${green}Creating log environment..."
135 | if [ `mkdir -p $LOG_DIR` ]; then
136 | echo "ERROR: $* (status $?)" 1>&2
137 | exit 1
138 | else
139 | # success
140 | echo "$(tput bold)${green}Success.${txtreset} Log environment created in ${green}$LOG_DIR${txtreset}"
141 | echo ""
142 | echo "Moving on...."
143 | echo ""
144 | fi
145 | else
146 | # success
147 | echo "$(tput bold)${green}OK.${txtreset} Log environment present in $(tput bold)${green}$LOG_DIR${txtreset}"
148 | echo ""
149 | echo "Moving on...."
150 | echo ""
151 | fi
152 | }
153 | ######################################################################################################
154 | function cdn_sync(){
155 |
156 | # UPLOAD new files first
157 | turbolift -u $CDN_ID -a $CDN_KEY --os-rax-auth $CDN_REGION --verbose --colorized upload --sync -s $SFTP_CONTAINER -c $CDN_CONTAINER
158 |
159 | # LIST the files on CDN and save them
160 | turbolift -u $CDN_ID -a $CDN_KEY --os-rax-auth $CDN_REGION list -c $CDN_CONTAINER > $log_file
161 | cat >> $CDN_log_file <> $CDN_log_file # keep the original CDN-log
168 |
169 | # LIST the current files present on SFTP
170 | # CDN -> we canot have containers inside containers.
171 | # BUT, users have the habit to upload full directories to SFTP, so we need to parse them.
172 | # on CDN, the files will have the full PATH as name.
173 | # we need to remove the first X chars from 'find' output where X -> lenght of SFTP_CONTAINER
174 | exclude_str=${#SFTP_CONTAINER}
175 |
176 | # now we have the lenght of SFTP_CONTAINER.
177 | # we need to +1 - this will include an extra char for the trailing slash
178 | ((exclude_str++))
179 |
180 | # now generate the LOG file for SFTP side;
181 | find $SFTP_CONTAINER -type f | sed "s/^.\{$exclude_str\}//g" > $SFTP_FILES
182 |
183 | # format CDN file list
184 | tail -n +6 $log_file | head -n -3 > log_file-new && mv log_file-new $log_file
185 | sed -e 's/|\(.*\)|/\1/' $log_file > CDN-new && mv CDN-new $log_file
186 | awk -F'|' '{print $2}' $log_file > CDN-new && mv CDN-new $log_file
187 |
188 | # keep the files that are ONLY on CDN and NOT on SFTP in a separate list.
189 | # this files will be REMOVED
190 | fgrep -vf $SFTP_FILES $log_file > $log_removed
191 | }
192 | ######################################################################################################
193 | # Clean the obsolete files from the CDN container
194 | # this function will ONLY run only at specific time.
195 | # Check lines 63-66 to change the values
196 | function remove_obsolete_files(){
197 | if [[ $_clean_time -lt $_elapsed ]]; then
198 | echo "Cleaning up CDN Container ... "
199 | while read line
200 | do
201 | deleted_file=$line
202 | echo "Removing obsolete file - $deleted_file"
203 | turbolift -u $CDN_ID -a $CDN_KEY --os-rax-auth $CDN_REGION --verbose --colorized delete --container $CDN_CONTAINER --object $deleted_file
204 | done < $log_removed
205 | fi
206 | }
207 | ######################################################################################################
208 | # Clean-up. Unset variables
209 | function unset_vars(){
210 | unset CDN_ID
211 | unset CDN_KEY
212 | unset CDN_REGION
213 | unset CDN_CONTAINER
214 | unset SFTP_CONTAINER
215 | unset SFTP_FILES
216 | unset _elapsed
217 | }
218 | ######################################################################################################
219 | # Remove OLD log-files
220 | function clean_logs(){
221 | # run rm only once at the end instead of each time a file is found.
222 | echo "" && \
223 | echo "${green}Cleaning $1...${txtreset}Removing files older than 3 days..." && \
224 | echo ""
225 | if [ `find $1 -type f -mtime +3 -exec rm '{}' '+'` ]; then
226 | echo "ERROR: $* (status $?)" 1>&2
227 | exit 1
228 | else
229 | echo "Done."
230 | fi
231 | }
232 | ######################################################################################################
233 | main() {
234 |
235 | check_if_root
236 | make_log_env
237 | cdn_sync
238 |
239 | # Remove obsolete files from the CDN container - ONLY if the time is right :)
240 | remove_obsolete_files
241 |
242 | # Clean up
243 | clean_logs "$LOG_DIR"
244 | unset_vars
245 |
246 | # remove lock
247 | rm -f ${LOCK_FILE}
248 | exit 0
249 | }
250 | main "$@"
251 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | prettytable>=0.7.0
2 | requests>=2.2.0
3 | cloudlib>=0.5.0
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # =============================================================================
3 | # Copyright [2015] [Kevin Carter]
4 | # License Information :
5 | # This software has no warranty, it is provided 'as is'. It is your
6 | # responsibility to validate the behavior of the routines and its accuracy
7 | # using the code provided. Consult the GNU General Public license for further
8 | # details (see GNU General Public License).
9 | # http://www.gnu.org/licenses/gpl.html
10 | # =============================================================================
11 | import setuptools
12 | import sys
13 |
14 | import turbolift
15 |
16 | with open('requirements.txt') as f:
17 | required = f.read().splitlines()
18 |
19 | if sys.version_info < (2, 6, 0):
20 | sys.stderr.write("Turbolift Presently requires Python 2.6.0 or greater \n")
21 | raise SystemExit(
22 | '\nUpgrade python because you version of it is VERY deprecated\n'
23 | )
24 | elif sys.version_info < (2, 7, 0):
25 | required.append('argparse')
26 |
27 | with open('README', 'rb') as r_file:
28 | LDINFO = r_file.read()
29 |
30 | setuptools.setup(
31 | name=turbolift.__appname__,
32 | version=turbolift.__version__,
33 | author=turbolift.__author__,
34 | author_email=turbolift.__email__,
35 | description=turbolift.__description__,
36 | long_description=LDINFO,
37 | license='GNU General Public License v3 or later (GPLv3+)',
38 | packages=[
39 | 'turbolift',
40 | 'turbolift.authentication',
41 | 'turbolift.clouderator',
42 | 'turbolift.methods'
43 | ],
44 | url=turbolift.__url__,
45 | install_requires=required,
46 | classifiers=[
47 | 'Development Status :: 5 - Production/Stable',
48 | 'Intended Audience :: Information Technology',
49 | 'Intended Audience :: System Administrators',
50 | 'Intended Audience :: Developers',
51 | 'Operating System :: OS Independent',
52 | 'License :: OSI Approved :: GNU General Public License v3 or later'
53 | ' (GPLv3+)',
54 | 'Programming Language :: Python :: 2.6',
55 | 'Programming Language :: Python :: 2.7',
56 | 'Topic :: Utilities',
57 | 'Topic :: Software Development :: Libraries :: Python Modules'],
58 | entry_points={
59 | "console_scripts": [
60 | "turbolift = turbolift.executable:execute"
61 | ]
62 | }
63 | )
64 |
--------------------------------------------------------------------------------
/test-requirements.txt:
--------------------------------------------------------------------------------
1 | hacking>=0.8.0,<0.9
2 |
3 | # mock object framework
4 | mock>=1.0
5 |
6 | unittest2
7 | discover
8 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | minversion = 1.6
3 | skipsdist = True
4 | envlist = py26,py27,pep8
5 |
6 | [testenv]
7 | usedevelop = True
8 | commands = discover turbolift/tests
9 | deps = -r{toxinidir}/requirements.txt
10 | -r{toxinidir}/test-requirements.txt
11 |
12 | [testenv:pep8]
13 | commands = flake8 --ignore=H302 --exclude=turbolift/tests turbolift
14 |
--------------------------------------------------------------------------------
/turbolift/authentication/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cloudnull/turbolift/da33034e88959226529ce762e2895e6f6356c448/turbolift/authentication/__init__.py
--------------------------------------------------------------------------------
/turbolift/authentication/auth.py:
--------------------------------------------------------------------------------
1 | """Perform Openstack Authentication."""
2 |
3 | import json
4 |
5 | from turbolift import exceptions
6 | from turbolift.authentication import utils
7 |
8 | from cloudlib import logger
9 |
10 |
11 | LOG = logger.getLogger('turbolift')
12 |
13 |
14 | def authenticate(job_args):
15 | """Authentication For Openstack API.
16 |
17 | Pulls the full Openstack Service Catalog Credentials are the Users API
18 | Username and Key/Password.
19 |
20 | Set a DC Endpoint and Authentication URL for the OpenStack environment
21 | """
22 |
23 | # Load any authentication plugins as needed
24 | job_args = utils.check_auth_plugin(job_args)
25 |
26 | # Set the auth version
27 | auth_version = utils.get_authversion(job_args=job_args)
28 |
29 | # Define the base headers that are used in all authentications
30 | auth_headers = {
31 | 'Content-Type': 'application/json',
32 | 'Accept': 'application/json'
33 | }
34 |
35 | auth_headers.update(job_args['base_headers'])
36 |
37 | if auth_version == 'v1.0':
38 | auth = utils.V1Authentication(job_args=job_args)
39 | auth_headers.update(auth.get_headers())
40 | LOG.debug('Request Headers: [ %s ]', auth_headers)
41 |
42 | auth_url = job_args['os_auth_url']
43 | LOG.debug('Parsed Auth URL: [ %s ]', auth_url)
44 |
45 | auth_kwargs = {
46 | 'url': auth_url,
47 | 'headers': auth_headers
48 | }
49 | else:
50 | auth = utils.OSAuthentication(job_args=job_args)
51 | auth_url = auth.parse_region()
52 | LOG.debug('Parsed Auth URL: [ %s ]', auth_url)
53 |
54 | auth_json = auth.parse_reqtype()
55 | LOG.debug('Request Headers: [ %s ]', auth_headers)
56 |
57 | auth_body = json.dumps(auth_json)
58 | LOG.debug('Request JSON: [ %s ]', auth_body)
59 |
60 | auth_kwargs = {
61 | 'url': auth_url,
62 | 'headers': auth_headers,
63 | 'body': auth_body
64 | }
65 |
66 | auth_resp = auth.auth_request(**auth_kwargs)
67 | if auth_resp.status_code >= 300:
68 | raise exceptions.AuthenticationProblem(
69 | 'Authentication Failure, Status: [ %s ] Reason: [ %s ]',
70 | auth_resp.status_code,
71 | auth_resp.reason
72 | )
73 | else:
74 | return auth.parse_auth_response(auth_resp)
75 |
--------------------------------------------------------------------------------
/turbolift/authentication/utils.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import traceback
12 | try:
13 | import urlparse
14 | except ImportError:
15 | import urllib.parse as urlparse
16 |
17 | from cloudlib import logger
18 | from cloudlib import http
19 |
20 | import turbolift
21 | from turbolift import exceptions
22 | from turbolift import utils as baseutils
23 |
24 |
25 | LOG = logger.getLogger('turbolift')
26 | AUTH_VERSION_MAP = {
27 | 'v1.0': ['V1', 'v1', 'v1.0', 'V1.0', '1', '1.0', '1.1'],
28 | 'v2.0': ['V2', 'v2', 'v2.0', 'V2.0', '2', '2.0'],
29 | 'v3.0': ['V3', 'v3', 'v3.0', 'V3.0', '3', '3.0']
30 | }
31 |
32 |
33 | def check_auth_plugin(job_args):
34 | _plugins = job_args.get('auth_plugins')
35 | for name, value in turbolift.auth_plugins(auth_plugins=_plugins).items():
36 | auth_plugin = job_args.get(name)
37 | if auth_plugin:
38 | value.pop('args', None)
39 | job_args.update(value)
40 | job_args['os_auth_url'] = value.get('os_auth_url')
41 |
42 | if baseutils.check_basestring(item=auth_plugin):
43 | job_args['os_region'] = auth_plugin % {
44 | 'region': auth_plugin
45 | }
46 |
47 | LOG.debug('Auth Plugin Loaded: [ %s ]', name)
48 | return job_args
49 | else:
50 | return job_args
51 |
52 |
53 | def get_authversion(job_args):
54 | """Get or infer the auth version.
55 |
56 | Based on the information found in the *AUTH_VERSION_MAP* the authentication
57 | version will be set to a correct value as determined by the
58 | **os_auth_version** parameter as found in the `job_args`.
59 |
60 | :param job_args: ``dict``
61 | :returns: ``str``
62 | """
63 |
64 | _version = job_args.get('os_auth_version')
65 | for version, variants in AUTH_VERSION_MAP.items():
66 | if _version in variants:
67 | authversion = job_args['os_auth_version'] = version
68 | return authversion
69 | else:
70 | raise exceptions.AuthenticationProblem(
71 | "Auth Version must be one of %s.",
72 | list(AUTH_VERSION_MAP.keys())
73 | )
74 |
75 |
76 | def get_service_url(region, endpoint_list, lookup):
77 | """Lookup a service URL from the *endpoint_list*.
78 |
79 | :param region: ``str``
80 | :param endpoint_list: ``list``
81 | :param lookup: ``str``
82 | :return: ``object``
83 | """
84 |
85 | for endpoint in endpoint_list:
86 | region_get = endpoint.get('region', '')
87 | if region.lower() == region_get.lower():
88 | return http.parse_url(url=endpoint.get(lookup))
89 | else:
90 | raise exceptions.AuthenticationProblem(
91 | 'Region "%s" was not found in your Service Catalog.',
92 | region
93 | )
94 |
95 |
96 | class V1Authentication(object):
97 | def __init__(self, job_args):
98 | self.job_args = job_args
99 | self.req = http.MakeRequest()
100 |
101 | def auth_request(self, url, headers):
102 | return self.req.get(url, headers)
103 |
104 | def get_headers(self):
105 | """Setup headers for authentication request."""
106 |
107 | try:
108 | return {
109 | 'X-Auth-User': self.job_args['os_user'],
110 | 'X-Auth-Key': self.job_args['os_apikey']
111 | }
112 | except KeyError as exp:
113 | raise exceptions.AuthenticationProblem(
114 | 'Missing Credentials. Error: %s',
115 | exp
116 | )
117 |
118 | @staticmethod
119 | def parse_auth_response(auth_response):
120 | """Parse the auth response and return the tenant, token, and username.
121 |
122 | :param auth_response: the full object returned from an auth call
123 | :returns: ``dict``
124 | """
125 |
126 | auth_dict = dict()
127 | LOG.debug('Authentication Headers %s', auth_response.headers)
128 | try:
129 | auth_dict['os_token'] = auth_response.headers['x-auth-token']
130 | auth_dict['storage_url'] = urlparse.urlparse(
131 | auth_response.headers['x-storage-url']
132 | )
133 | except KeyError as exp:
134 | raise exceptions.AuthenticationProblem(
135 | 'No token was found in the authentication response. Please'
136 | ' check your auth URL, your credentials, and your set auth'
137 | ' version. Auth Headers: [ %s ] Error: [ %s ]',
138 | auth_response.headers,
139 | exp
140 | )
141 | else:
142 | return auth_dict
143 |
144 |
145 | class OSAuthentication(object):
146 | def __init__(self, job_args):
147 | self.job_args = job_args
148 | self.req = http.MakeRequest()
149 |
150 | def auth_request(self, url, headers, body):
151 | """Perform auth request for token."""
152 |
153 | return self.req.post(url, headers, body=body)
154 |
155 | def parse_reqtype(self):
156 | """Return the authentication body."""
157 |
158 | if self.job_args['os_auth_version'] == 'v1.0':
159 | return dict()
160 | else:
161 | setup = {
162 | 'username': self.job_args.get('os_user')
163 | }
164 |
165 | # Check if any prefix items are set. A prefix should be a
166 | # dictionary with keys matching the os_* credential type.
167 | prefixes = self.job_args.get('os_prefix')
168 |
169 | if self.job_args.get('os_token') is not None:
170 | auth_body = {
171 | 'auth': {
172 | 'token': {
173 | 'id': self.job_args.get('os_token')
174 | }
175 | }
176 | }
177 | if not self.job_args.get('os_tenant'):
178 | raise exceptions.AuthenticationProblem(
179 | 'To use token auth you must specify the tenant id. Set'
180 | ' the tenant ID with [ --os-tenant ]'
181 | )
182 | elif self.job_args.get('os_password') is not None:
183 | setup['password'] = self.job_args.get('os_password')
184 | if prefixes:
185 | prefix = prefixes.get('os_password')
186 | if not prefix:
187 | raise NotImplementedError(
188 | 'the `password` method is not implemented for this'
189 | ' auth plugin'
190 | )
191 | else:
192 | prefix = 'passwordCredentials'
193 | auth_body = {
194 | 'auth': {
195 | prefix: setup
196 | }
197 | }
198 | elif self.job_args.get('os_apikey') is not None:
199 | setup['apiKey'] = self.job_args.get('os_apikey')
200 | if prefixes:
201 | prefix = prefixes.get('os_apikey')
202 | if not prefix:
203 | raise NotImplementedError(
204 | 'the `apikey` method is not implemented for this'
205 | ' auth plugin'
206 | )
207 | else:
208 | prefix = 'apiKeyCredentials'
209 | auth_body = {
210 | 'auth': {
211 | prefix: setup
212 | }
213 | }
214 | else:
215 | raise exceptions.AuthenticationProblem(
216 | 'No Password, APIKey, or Token Specified'
217 | )
218 |
219 | if self.job_args.get('os_tenant'):
220 | auth = auth_body['auth']
221 | auth['tenantName'] = self.job_args.get('os_tenant')
222 |
223 | LOG.debug('AUTH Request body: [ %s ]', auth_body)
224 | return auth_body
225 |
226 | @staticmethod
227 | def _service_endpoints(service_catalog, types_list):
228 | for entry in service_catalog:
229 | for type_name in types_list:
230 | if entry.get('type') == type_name:
231 | return entry.get('endpoints')
232 | else:
233 | return list()
234 |
235 | def parse_auth_response(self, auth_response):
236 | """Parse the auth response and return the tenant, token, and username.
237 |
238 | :param auth_response: the full object returned from an auth call
239 | :returns: ``dict``
240 | """
241 |
242 | auth_dict = dict()
243 | auth_response = auth_response.json()
244 | LOG.debug('Authentication Response Body [ %s ]', auth_response)
245 |
246 | access = auth_response.get('access')
247 | access_token = access.get('token')
248 | access_tenant = access_token.get('tenant')
249 | access_user = access.get('user')
250 |
251 | auth_dict['os_token'] = access_token.get('id')
252 | auth_dict['os_tenant'] = access_tenant.get('name')
253 | auth_dict['os_user'] = access_user.get('name')
254 |
255 | if not auth_dict['os_token']:
256 | raise exceptions.AuthenticationProblem(
257 | 'When attempting to grab the tenant or user nothing was'
258 | ' found. No Token Found to Parse. Here is the DATA: [ %s ]'
259 | ' Stack Trace [ %s ]',
260 | auth_response,
261 | traceback.format_exc()
262 | )
263 |
264 | region = self.job_args.get('os_region')
265 | print(region)
266 | if not region:
267 | raise exceptions.SystemProblem('No Region Set')
268 |
269 | service_catalog = access.pop('serviceCatalog')
270 |
271 | # Get the storage URL
272 | object_endpoints = self._service_endpoints(
273 | service_catalog=service_catalog,
274 | types_list=turbolift.__srv_types__
275 | )
276 |
277 | # In the legacy internal flag is set override the os_endpoint_type
278 | # TODO(cloudnull) Remove this in future releases
279 | if 'internal' in self.job_args and self.job_args['internal']:
280 | LOG.warn(
281 | 'The use of the ``--internal`` flag has been deprecated and'
282 | ' will be removed in future releases. Please use the'
283 | ' ``--os-endpoint-type`` flag and set the type name'
284 | ' instead. In the case of using snet (service net) this is'
285 | ' generally noted as "internalURL". Example setting:'
286 | ' ``--os-endpoint-type internalURL``'
287 | )
288 | self.job_args['os_endpoint_type'] = 'internalURL'
289 |
290 | auth_dict['storage_url'] = get_service_url(
291 | region=region,
292 | endpoint_list=object_endpoints,
293 | lookup=self.job_args['os_endpoint_type']
294 | )
295 |
296 | # Get the CDN URL
297 | cdn_endpoints = self._service_endpoints(
298 | service_catalog=service_catalog, types_list=turbolift.__cdn_types__
299 | )
300 |
301 | if cdn_endpoints:
302 | auth_dict['cdn_storage_url'] = get_service_url(
303 | region=region,
304 | endpoint_list=cdn_endpoints,
305 | lookup=self.job_args['cdn_endpoint_type']
306 | )
307 |
308 | return auth_dict
309 |
310 | def parse_region(self):
311 | """Pull region/auth url information from context."""
312 |
313 | try:
314 | auth_url = self.job_args['os_auth_url']
315 | if 'tokens' not in auth_url:
316 | if not auth_url.endswith('/'):
317 | auth_url = '%s/' % auth_url
318 | auth_url = urlparse.urljoin(auth_url, 'tokens')
319 | return auth_url
320 | except KeyError:
321 | raise exceptions.AuthenticationProblem(
322 | 'You Are required to specify an Auth URL, Region or Plugin'
323 | )
324 |
--------------------------------------------------------------------------------
/turbolift/clouderator/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cloudnull/turbolift/da33034e88959226529ce762e2895e6f6356c448/turbolift/clouderator/__init__.py
--------------------------------------------------------------------------------
/turbolift/clouderator/actions.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import grp
12 | import hashlib
13 | import io
14 | import os
15 | import pwd
16 |
17 | try:
18 | import urlparse
19 | except ImportError:
20 | import urllib.parse as urlparse
21 |
22 | import cloudlib
23 | from cloudlib import http
24 | from cloudlib import logger
25 | from cloudlib import shell
26 |
27 | from turbolift import exceptions
28 | from turbolift.authentication import auth
29 | from turbolift.clouderator import utils as cloud_utils
30 |
31 |
32 | LOG = logger.getLogger('turbolift')
33 |
34 |
35 | class CloudActions(object):
36 | def __init__(self, job_args):
37 | """
38 |
39 | :param job_args:
40 | """
41 | self.job_args = job_args
42 | self.http = http.MakeRequest()
43 | self.shell = shell.ShellCommands(
44 | log_name='turbolift',
45 | debug=self.job_args.get('debug')
46 | )
47 |
48 | def _return_base_data(self, url, container, container_object=None,
49 | container_headers=None, object_headers=None):
50 | """Return headers and a parsed url.
51 |
52 | :param url:
53 | :param container:
54 | :param container_object:
55 | :param container_headers:
56 | :return: ``tuple``
57 | """
58 | headers = self.job_args['base_headers']
59 | headers.update({'X-Auth-Token': self.job_args['os_token']})
60 |
61 | _container_uri = url.geturl().rstrip('/')
62 |
63 | if container:
64 | _container_uri = '%s/%s' % (
65 | _container_uri, cloud_utils.quoter(container)
66 | )
67 |
68 | if container_object:
69 | _container_uri = '%s/%s' % (
70 | _container_uri, cloud_utils.quoter(container_object)
71 | )
72 |
73 | if object_headers:
74 | headers.update(object_headers)
75 |
76 | if container_headers:
77 | headers.update(container_headers)
78 |
79 | return headers, urlparse.urlparse(_container_uri)
80 |
81 | def _sync_check(self, uri, headers, local_object=None, file_object=None):
82 | resp = self._header_getter(
83 | uri=uri,
84 | headers=headers
85 | )
86 |
87 | if resp.status_code != 200:
88 | return True
89 |
90 | try:
91 | self.shell.md5_checker(
92 | md5sum=resp.headers.get('etag'),
93 | local_file=local_object,
94 | file_object=file_object
95 | )
96 | except cloudlib.MD5CheckMismatch:
97 | return True
98 | else:
99 | return False
100 |
101 | @cloud_utils.retry(Exception)
102 | def _chunk_putter(self, uri, open_file, headers=None):
103 | """Make many PUT request for a single chunked object.
104 |
105 | Objects that are processed by this method have a SHA256 hash appended
106 | to the name as well as a count for object indexing which starts at 0.
107 |
108 | To make a PUT request pass, ``url``
109 |
110 | :param uri: ``str``
111 | :param open_file: ``object``
112 | :param headers: ``dict``
113 | """
114 | count = 0
115 | dynamic_hash = hashlib.sha256(self.job_args.get('container'))
116 | dynamic_hash = dynamic_hash.hexdigest()
117 | while True:
118 | # Read in a chunk of an open file
119 | file_object = open_file.read(self.job_args.get('chunk_size'))
120 | if not file_object:
121 | break
122 |
123 | # When a chuck is present store it as BytesIO
124 | with io.BytesIO(file_object) as file_object:
125 | # store the parsed URI for the chunk
126 | chunk_uri = urlparse.urlparse(
127 | '%s.%s.%s' % (
128 | uri.geturl(),
129 | dynamic_hash,
130 | count
131 | )
132 | )
133 |
134 | # Increment the count as soon as it is used
135 | count += 1
136 |
137 | # Check if the read chunk already exists
138 | sync = self._sync_check(
139 | uri=chunk_uri,
140 | headers=headers,
141 | file_object=file_object
142 | )
143 | if not sync:
144 | continue
145 |
146 | # PUT the chunk
147 | _resp = self.http.put(
148 | url=chunk_uri,
149 | body=file_object,
150 | headers=headers
151 | )
152 | self._resp_exception(resp=_resp)
153 | LOG.debug(_resp.__dict__)
154 |
155 | @cloud_utils.retry(Exception)
156 | def _putter(self, uri, headers, local_object=None):
157 | """Place object into the container.
158 |
159 | :param uri:
160 | :param headers:
161 | :param local_object:
162 | """
163 |
164 | if not local_object:
165 | return self.http.put(url=uri, headers=headers)
166 |
167 | with open(local_object, 'rb') as f_open:
168 | large_object_size = self.job_args.get('large_object_size')
169 | if not large_object_size:
170 | large_object_size = 5153960756
171 |
172 | if os.path.getsize(local_object) > large_object_size:
173 | # Remove the manifest entry while working with chunks
174 | manifest = headers.pop('X-Object-Manifest')
175 | # Feed the open file through the chunk process
176 | self._chunk_putter(
177 | uri=uri,
178 | open_file=f_open,
179 | headers=headers
180 | )
181 | # Upload the 0 byte object with the manifest path
182 | headers.update({'X-Object-Manifest': manifest})
183 | return self.http.put(url=uri, headers=headers)
184 | else:
185 | if self.job_args.get('sync'):
186 | sync = self._sync_check(
187 | uri=uri,
188 | headers=headers,
189 | local_object=local_object
190 | )
191 | if not sync:
192 | return None
193 |
194 | return self.http.put(
195 | url=uri, body=f_open, headers=headers
196 | )
197 |
198 | @cloud_utils.retry(Exception)
199 | def _getter(self, uri, headers, local_object):
200 | """Perform HEAD request on a specified object in the container.
201 |
202 | :param uri: ``str``
203 | :param headers: ``dict``
204 | """
205 |
206 | if self.job_args.get('sync'):
207 | sync = self._sync_check(
208 | uri=uri,
209 | headers=headers,
210 | local_object=local_object
211 | )
212 | if not sync:
213 | return None
214 |
215 | # perform Object HEAD request
216 | resp = self.http.get(url=uri, headers=headers)
217 | self._resp_exception(resp=resp)
218 |
219 | # Open our source file and write it
220 | chunk_size = self.job_args['download_chunk_size']
221 | with open(local_object, 'wb') as f_name:
222 | for chunk in resp.iter_content(chunk_size=chunk_size):
223 | if chunk:
224 | f_name.write(chunk)
225 | f_name.flush()
226 |
227 | if self.job_args.get('restore_perms'):
228 | if 'X-Object-Meta-perms' in resp.headers:
229 | os.chmod(
230 | local_object,
231 | int(resp.headers['x-object-meta-perms'], 8)
232 | )
233 |
234 | chown_file = {'uid': -1, 'gid': -1}
235 | if 'X-Object-Meta-owner' in resp.headers:
236 | chown_file['uid'] = pwd.getpwnam(
237 | resp.headers['X-Object-Meta-owner']
238 | ).pw_uid
239 | if 'X-Object-Meta-group' in resp.headers:
240 | chown_file['gid'] = grp.getgrnam(
241 | resp.headers['X-Object-Meta-group']
242 | ).gr_gid
243 | os.chown(local_object, *chown_file.values())
244 |
245 | return resp
246 |
247 | @cloud_utils.retry(Exception)
248 | def _deleter(self, uri, headers):
249 | """Perform HEAD request on a specified object in the container.
250 |
251 | :param uri: ``str``
252 | :param headers: ``dict``
253 | """
254 |
255 | # perform Object HEAD request
256 | resp = self.http.delete(url=uri, headers=headers)
257 | self._resp_exception(resp=resp)
258 | return resp
259 |
260 | @cloud_utils.retry(Exception)
261 | def _header_getter(self, uri, headers):
262 | """Perform HEAD request on a specified object in the container.
263 |
264 | :param uri: ``str``
265 | :param headers: ``dict``
266 | """
267 |
268 | # perform Object HEAD request
269 | resp = self.http.head(url=uri, headers=headers)
270 | self._resp_exception(resp=resp)
271 | return resp
272 |
273 | @cloud_utils.retry(Exception)
274 | def _header_poster(self, uri, headers):
275 | """POST Headers on a specified object in the container.
276 |
277 | :param uri: ``str``
278 | :param headers: ``dict``
279 | """
280 |
281 | resp = self.http.post(url=uri, body=None, headers=headers)
282 | self._resp_exception(resp=resp)
283 | return resp
284 |
285 | @staticmethod
286 | def _last_marker(base_path, last_object):
287 | """Set Marker.
288 |
289 | :param base_path:
290 | :param last_object:
291 | :return str:
292 | """
293 |
294 | return '%s&marker=%s' % (base_path, last_object)
295 |
296 | def _obj_index(self, uri, base_path, marked_path, headers, spr=False):
297 | """Return an index of objects from within the container.
298 |
299 | :param uri:
300 | :param base_path:
301 | :param marked_path:
302 | :param headers:
303 | :param spr: "single page return" Limit the returned data to one page
304 | :type spr: ``bol``
305 | :return:
306 | """
307 | object_list = list()
308 | l_obj = None
309 | container_uri = uri.geturl()
310 |
311 | while True:
312 | marked_uri = urlparse.urljoin(container_uri, marked_path)
313 | resp = self.http.get(url=marked_uri, headers=headers)
314 | self._resp_exception(resp=resp)
315 | return_list = resp.json()
316 | if spr:
317 | return return_list
318 |
319 | time_offset = self.job_args.get('time_offset')
320 | for obj in return_list:
321 | if time_offset:
322 | # Get the last_modified data from the Object.
323 | time_delta = cloud_utils.TimeDelta(
324 | job_args=self.job_args,
325 | last_modified=time_offset
326 | )
327 | if time_delta:
328 | object_list.append(obj)
329 | else:
330 | object_list.append(obj)
331 |
332 | if object_list:
333 | last_obj_in_list = object_list[-1].get('name')
334 | else:
335 | last_obj_in_list = None
336 |
337 | if l_obj == last_obj_in_list:
338 | return object_list
339 | else:
340 | l_obj = last_obj_in_list
341 | marked_path = self._last_marker(
342 | base_path=base_path,
343 | last_object=l_obj
344 | )
345 |
346 | def _list_getter(self, uri, headers, last_obj=None, spr=False):
347 | """Get a list of all objects in a container.
348 |
349 | :param uri:
350 | :param headers:
351 | :return list:
352 | :param spr: "single page return" Limit the returned data to one page
353 | :type spr: ``bol``
354 | """
355 |
356 | # Quote the file path.
357 | base_path = marked_path = ('%s?limit=10000&format=json' % uri.path)
358 |
359 | if last_obj:
360 | marked_path = self._last_marker(
361 | base_path=base_path,
362 | last_object=cloud_utils.quoter(last_obj)
363 | )
364 |
365 | file_list = self._obj_index(
366 | uri=uri,
367 | base_path=base_path,
368 | marked_path=marked_path,
369 | headers=headers,
370 | spr=spr
371 | )
372 |
373 | LOG.debug(
374 | 'Found [ %d ] entries(s) at [ %s ]',
375 | len(file_list),
376 | uri.geturl()
377 | )
378 |
379 | if spr:
380 | return file_list
381 | else:
382 | return cloud_utils.unique_list_dicts(
383 | dlist=file_list, key='name'
384 | )
385 |
386 | def _resp_exception(self, resp):
387 | """If we encounter an exception in our upload.
388 |
389 | we will look at how we can attempt to resolve the exception.
390 |
391 | :param resp:
392 | """
393 |
394 | message = [
395 | 'Url: [ %s ] Reason: [ %s ] Request: [ %s ] Status Code: [ %s ]. ',
396 | resp.url,
397 | resp.reason,
398 | resp.request,
399 | resp.status_code
400 | ]
401 |
402 | # Check to make sure we have all the bits needed
403 | if not hasattr(resp, 'status_code'):
404 | message[0] += 'No Status to check. Turbolift will retry...'
405 | raise exceptions.SystemProblem(message)
406 | elif resp is None:
407 | message[0] += 'No response information. Turbolift will retry...'
408 | raise exceptions.SystemProblem(message)
409 | elif resp.status_code == 401:
410 | message[0] += (
411 | 'Turbolift experienced an Authentication issue. Turbolift'
412 | ' will retry...'
413 | )
414 | self.job_args.update(auth.authenticate(self.job_args))
415 | raise exceptions.SystemProblem(message)
416 | elif resp.status_code == 404:
417 | message[0] += 'Item not found.'
418 | LOG.debug(*message)
419 | elif resp.status_code == 409:
420 | message[0] += (
421 | 'Request Conflict. Turbolift is abandoning this...'
422 | )
423 | elif resp.status_code == 413:
424 | return_headers = resp.headers
425 | retry_after = return_headers.get('retry_after', 10)
426 | cloud_utils.stupid_hack(wait=retry_after)
427 | message[0] += (
428 | 'The System encountered an API limitation and will'
429 | ' continue in [ %s ] Seconds' % retry_after
430 | )
431 | raise exceptions.SystemProblem(message)
432 | elif resp.status_code == 502:
433 | message[0] += (
434 | 'Failure making Connection. Turbolift will retry...'
435 | )
436 | raise exceptions.SystemProblem(message)
437 | elif resp.status_code == 503:
438 | cloud_utils.stupid_hack(wait=10)
439 | message[0] += 'SWIFT-API FAILURE'
440 | raise exceptions.SystemProblem(message)
441 | elif resp.status_code == 504:
442 | cloud_utils.stupid_hack(wait=10)
443 | message[0] += 'Gateway Failure.'
444 | raise exceptions.SystemProblem(message)
445 | elif resp.status_code >= 300:
446 | message[0] += 'General exception.'
447 | raise exceptions.SystemProblem(message)
448 | else:
449 | LOG.debug(*message)
450 |
451 | @cloud_utils.retry(exceptions.SystemProblem)
452 | def list_items(self, url, container=None, last_obj=None, spr=False):
453 | """Builds a long list of objects found in a container.
454 |
455 | NOTE: This could be millions of Objects.
456 |
457 | :param url:
458 | :param container:
459 | :param last_obj:
460 | :param spr: "single page return" Limit the returned data to one page
461 | :type spr: ``bol``
462 | :return None | list:
463 | """
464 |
465 | headers, container_uri = self._return_base_data(
466 | url=url,
467 | container=container
468 | )
469 |
470 | if container:
471 | resp = self._header_getter(uri=container_uri, headers=headers)
472 | if resp.status_code == 404:
473 | LOG.info('Container [ %s ] not found.', container)
474 | return [resp]
475 |
476 | return self._list_getter(
477 | uri=container_uri,
478 | headers=headers,
479 | last_obj=last_obj,
480 | spr=spr
481 | )
482 |
483 | @cloud_utils.retry(exceptions.SystemProblem)
484 | def show_details(self, url, container, container_object=None):
485 | """Return Details on an object or container.
486 |
487 | :param url:
488 | :param container:
489 | :param container_object:
490 | """
491 |
492 | headers, container_uri = self._return_base_data(
493 | url=url,
494 | container=container,
495 | container_object=container_object
496 | )
497 |
498 | return self._header_getter(
499 | uri=container_uri,
500 | headers=headers
501 | )
502 |
503 | @cloud_utils.retry(exceptions.SystemProblem)
504 | def update_object(self, url, container, container_object, object_headers,
505 | container_headers):
506 | """Update an existing object in a swift container.
507 |
508 | This method will place new headers on an existing object or container.
509 |
510 | :param url:
511 | :param container:
512 | :param container_object:
513 | """
514 |
515 | headers, container_uri = self._return_base_data(
516 | url=url,
517 | container=container,
518 | container_object=container_object,
519 | container_headers=container_headers,
520 | object_headers=object_headers,
521 | )
522 |
523 | return self._header_poster(
524 | uri=container_uri,
525 | headers=headers
526 | )
527 |
528 | @cloud_utils.retry(exceptions.SystemProblem)
529 | def container_cdn_command(self, url, container, container_object,
530 | cdn_headers):
531 | """Command your CDN enabled Container.
532 |
533 | :param url:
534 | :param container:
535 | """
536 |
537 | headers, container_uri = self._return_base_data(
538 | url=url,
539 | container=container,
540 | container_object=container_object,
541 | object_headers=cdn_headers
542 | )
543 |
544 | if self.job_args.get('purge'):
545 | return self._deleter(
546 | uri=container_uri,
547 | headers=headers
548 | )
549 | else:
550 | return self._header_poster(
551 | uri=container_uri,
552 | headers=headers
553 | )
554 |
555 | @cloud_utils.retry(exceptions.SystemProblem)
556 | def put_container(self, url, container, container_headers=None):
557 | """Create a container if it is not Found.
558 |
559 | :param url:
560 | :param container:
561 | """
562 |
563 | headers, container_uri = self._return_base_data(
564 | url=url,
565 | container=container,
566 | container_headers=container_headers
567 | )
568 |
569 | resp = self._header_getter(
570 | uri=container_uri,
571 | headers=headers
572 | )
573 | if resp.status_code == 404:
574 | return self._putter(uri=container_uri, headers=headers)
575 | else:
576 | return resp
577 |
578 | @cloud_utils.retry(exceptions.SystemProblem)
579 | def put_object(self, url, container, container_object, local_object,
580 | object_headers, meta=None):
581 | """This is the Sync method which uploads files to the swift repository
582 |
583 | if they are not already found. If a file "name" is found locally and
584 | in the swift repository an MD5 comparison is done between the two
585 | files. If the MD5 is miss-matched the local file is uploaded to the
586 | repository. If custom meta data is specified, and the object exists the
587 | method will put the metadata onto the object.
588 |
589 | :param url:
590 | :param container:
591 | :param container_object:
592 | """
593 |
594 | headers, container_uri = self._return_base_data(
595 | url=url,
596 | container=container,
597 | container_object=container_object,
598 | container_headers=object_headers,
599 | object_headers=meta
600 | )
601 |
602 | return self._putter(
603 | uri=container_uri,
604 | headers=headers,
605 | local_object=local_object
606 | )
607 |
608 | @cloud_utils.retry(exceptions.SystemProblem)
609 | def get_items(self, url, container, container_object, local_object):
610 | """Get an objects from a container.
611 |
612 | :param url:
613 | :param container:
614 | """
615 |
616 | headers, container_uri = self._return_base_data(
617 | url=url,
618 | container=container,
619 | container_object=container_object
620 | )
621 |
622 | return self._getter(
623 | uri=container_uri,
624 | headers=headers,
625 | local_object=local_object
626 | )
627 |
628 | @cloud_utils.retry(exceptions.SystemProblem)
629 | def get_headers(self, url, container, container_object=None):
630 | headers, container_uri = self._return_base_data(
631 | url=url,
632 | container=container,
633 | container_object=container_object
634 | )
635 |
636 | return self._header_getter(
637 | uri=container_uri,
638 | headers=headers
639 | )
640 |
641 | @cloud_utils.retry(exceptions.SystemProblem)
642 | def delete_items(self, url, container, container_object=None):
643 | """Deletes an objects in a container.
644 |
645 | :param url:
646 | :param container:
647 | """
648 |
649 | headers, container_uri = self._return_base_data(
650 | url=url,
651 | container=container,
652 | container_object=container_object
653 | )
654 |
655 | return self._deleter(uri=container_uri, headers=headers)
656 |
--------------------------------------------------------------------------------
/turbolift/clouderator/utils.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import datetime
12 | import functools
13 | import random
14 | import time
15 | import urllib
16 |
17 |
18 | def retry(ExceptionToCheck, tries=3, delay=1, backoff=1):
19 | """Retry calling the decorated function using an exponential backoff.
20 |
21 | http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
22 | original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
23 |
24 | :param ExceptionToCheck: the exception to check. may be a tuple of
25 | exceptions to check
26 | :type ExceptionToCheck: Exception or tuple
27 | :param tries: number of times to try (not retry) before giving up
28 | :type tries: int
29 | :param delay: initial delay between retries in seconds
30 | :type delay: int
31 | :param backoff: backoff multiplier e.g. value of 2 will double the delay
32 | each retry
33 | :type backoff: int
34 | """
35 | def deco_retry(f):
36 | @functools.wraps(f)
37 | def f_retry(*args, **kwargs):
38 | mtries, mdelay = tries, delay
39 | while mtries > 1:
40 | try:
41 | return f(*args, **kwargs)
42 | except ExceptionToCheck:
43 | time.sleep(mdelay)
44 | mtries -= 1
45 | mdelay *= backoff
46 | return f(*args, **kwargs)
47 | return f_retry # true decorator
48 | return deco_retry
49 |
50 |
51 | def stupid_hack(most=10, wait=None):
52 | """Return a random time between 1 - 10 Seconds."""
53 |
54 | # Stupid Hack For Public Cloud so it is not overwhelmed with API requests.
55 | if wait is not None:
56 | time.sleep(wait)
57 | else:
58 | time.sleep(random.randrange(1, most))
59 |
60 |
61 | def time_stamp():
62 | """Setup time functions
63 |
64 | :returns: ``tuple``
65 | """
66 |
67 | # Time constants
68 | fmt = '%Y-%m-%dT%H:%M:%S.%f'
69 | date = datetime.datetime
70 | date_delta = datetime.timedelta
71 | now = datetime.datetime.utcnow()
72 |
73 | return fmt, date, date_delta, now
74 |
75 |
76 | def unique_list_dicts(dlist, key):
77 | """Return a list of dictionaries which are sorted for only unique entries.
78 |
79 | :param dlist:
80 | :param key:
81 | :return list:
82 | """
83 |
84 | return list(dict((val[key], val) for val in dlist).values())
85 |
86 |
87 | class TimeDelta(object):
88 | def __init__(self, job_args, last_modified, compare_time=None):
89 | """Check to see if a date delta exists based on filter for an object.
90 |
91 | :param job_args:
92 | :param last_modified:
93 | :param compare_time:
94 | :returns: ``bol``
95 | """
96 |
97 | self.job_args = job_args
98 | self.last_modified = last_modified
99 | self.compare_time = compare_time
100 |
101 | @staticmethod
102 | def hours(delta, factor):
103 | return delta(hours=factor)
104 |
105 | @staticmethod
106 | def days(delta, factor):
107 | return delta(days=factor)
108 |
109 | @staticmethod
110 | def weeks(delta, factor):
111 | return delta(weeks=factor)
112 |
113 | def get_delta(self):
114 | fmt, date, delta, now = time_stamp()
115 |
116 | # Set time objects
117 | odate = date.strptime(self.last_modified, fmt)
118 |
119 | if self.compare_time:
120 | # Time Options
121 | time_factor = self.job_args.get('time_factor', 1)
122 | offset = self.job_args.get('time_offset')
123 | offset_method = getattr(self, offset)
124 |
125 | if (odate + offset_method(delta=delta, factor=time_factor)) > now:
126 | return False
127 | else:
128 | return True
129 | else:
130 | if date.strptime(self.compare_time, fmt) > odate:
131 | return True
132 | else:
133 | return False
134 |
135 |
136 | def quoter(obj):
137 | """Return a Quoted URL.
138 |
139 | The quote function will return a URL encoded string. If there is an
140 | exception in the job which results in a "KeyError" the original
141 | string will be returned as it will be assumed to already be URL
142 | encoded.
143 |
144 | :param obj: ``basestring``
145 | :return: ``str``
146 | """
147 |
148 | try:
149 | try:
150 | return urllib.quote(obj)
151 | except AttributeError:
152 | return urllib.parse.quote(obj)
153 | except KeyError:
154 | return obj
155 |
156 |
--------------------------------------------------------------------------------
/turbolift/exceptions.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 | import os
11 | import signal
12 |
13 | from cloudlib import logger
14 | from turbolift import utils
15 |
16 |
17 | LOG = logger.getLogger('turbolift')
18 |
19 |
20 | class _BaseException(Exception):
21 | def __init__(self, *args):
22 | if len(args) > 1:
23 | format_message = args[0]
24 | try:
25 | message = format_message % tuple(args[1:])
26 | except TypeError as exp:
27 | message = (
28 | 'The exception message was not formatting correctly.'
29 | ' Error: [ %s ]. This was the data passed: "%s"'
30 | % (exp, args)
31 | )
32 | else:
33 | message = args[0]
34 |
35 | super(_BaseException, self).__init__(message)
36 | LOG.error(message)
37 |
38 |
39 | class NoCommandProvided(_BaseException):
40 | """No command was provided Exception."""
41 |
42 | pass
43 |
44 |
45 | class NoSource(_BaseException):
46 | """No Source Exception."""
47 |
48 | pass
49 |
50 |
51 | class AuthenticationProblem(_BaseException):
52 | """Authentication Problem Exception."""
53 |
54 | pass
55 |
56 |
57 | class SystemProblem(_BaseException):
58 | """System Problem Exception."""
59 |
60 | pass
61 |
62 |
63 | class DirectoryFailure(_BaseException):
64 | """Directory Failure Exception."""
65 |
66 | pass
67 |
68 |
69 | class RetryError(_BaseException):
70 | """Retry Error Exception."""
71 |
72 | pass
73 |
74 |
75 | class NoFileProvided(_BaseException):
76 | """No File Provided Exception."""
77 |
78 | pass
79 |
80 |
81 | class NoTenantIdFound(_BaseException):
82 | """No Tenant ID was found."""
83 |
84 | pass
85 |
86 |
87 | def emergency_kill():
88 | """Exit process.
89 |
90 | :return kill pid:
91 | """
92 |
93 | os.kill(os.getpid(), signal.SIGKILL)
94 |
95 |
96 | def emergency_exit(msg):
97 | """Exit process.
98 |
99 | :param msg:
100 | :return exit.status:
101 | """
102 |
103 | raise SystemExit(msg)
104 |
--------------------------------------------------------------------------------
/turbolift/executable.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # =============================================================================
3 | # Copyright [2015] [Kevin Carter]
4 | # License Information :
5 | # This software has no warranty, it is provided 'as is'. It is your
6 | # responsibility to validate the behavior of the routines and its accuracy
7 | # using the code provided. Consult the GNU General Public license for further
8 | # details (see GNU General Public License).
9 | # http://www.gnu.org/licenses/gpl.html
10 | # =============================================================================
11 |
12 | import sys
13 |
14 | from cloudlib import arguments
15 | from cloudlib import logger
16 |
17 | import turbolift
18 | from turbolift import worker
19 |
20 |
21 | def execute():
22 | """This is the run section of the application Turbolift."""
23 |
24 | if len(sys.argv) <= 1:
25 | raise SystemExit(
26 | 'No Arguments provided. use [--help] for more information.'
27 | )
28 |
29 | # Capture user arguments
30 | _args = arguments.ArgumentParserator(
31 | arguments_dict=turbolift.ARGUMENTS,
32 | env_name='TURBO',
33 | epilog=turbolift.VINFO,
34 | title='Turbolift',
35 | detail='Multiprocessing Swift CLI tool.',
36 | description='Manage Swift easily and fast.'
37 | )
38 | user_args = _args.arg_parser()
39 | user_args['run_indicator'] = True
40 | debug_log = False
41 | stream_logs = True
42 |
43 | # Load system logging
44 | if user_args.get('debug'):
45 | debug_log = True
46 | user_args['run_indicator'] = False
47 |
48 | # Load system logging
49 | if user_args.get('quiet'):
50 | stream_logs = False
51 | user_args['run_indicator'] = False
52 |
53 | _logging = logger.LogSetup(
54 | debug_logging=debug_log,
55 | colorized_messages=user_args.get('colorized', False)
56 | )
57 | _logging.default_logger(name='turbolift', enable_stream=stream_logs)
58 | job = worker.Worker(job_args=user_args)
59 | job.run_manager()
60 |
61 |
62 | if __name__ == "__main__":
63 | execute()
64 |
--------------------------------------------------------------------------------
/turbolift/methods/__init__.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import collections
12 | import datetime
13 | import grp
14 | import multiprocessing
15 | import os
16 | import pwd
17 | import re
18 | try:
19 | import Queue
20 | except ImportError:
21 | import queue as Queue
22 | import tarfile
23 |
24 | import prettytable
25 |
26 | from cloudlib import indicator
27 | from cloudlib import logger
28 | from cloudlib import shell
29 | from cloudlib import utils as cloud_utils
30 |
31 | from turbolift.clouderator import actions
32 | from turbolift import exceptions
33 | from turbolift import utils
34 |
35 |
36 | LOG = logger.getLogger('turbolift')
37 |
38 |
39 | class BaseMethod(object):
40 | def __init__(self, job_args):
41 | self.job_args = job_args
42 | # Define the size at which objects are considered large.
43 | self.large_object_size = self.job_args.get('large_object_size')
44 |
45 | self.max_jobs = self.job_args.get('max_jobs')
46 | if not self.max_jobs:
47 | self.max_jobs = 25000
48 |
49 | self.job = actions.CloudActions(job_args=self.job_args)
50 | self.run_indicator = self.job_args.get('run_indicator', True)
51 | self.indicator_options = {'run': self.run_indicator}
52 |
53 | self.shell = shell.ShellCommands(
54 | log_name='turbolift',
55 | debug=self.job_args['debug']
56 | )
57 |
58 | self.excludes = self.job_args.get('exclude')
59 | if not self.excludes:
60 | self.excludes = list()
61 |
62 | def _cdn(self):
63 | """Retrieve a long list of all files in a container.
64 |
65 | :return final_list, list_count, last_obj:
66 | """
67 |
68 | headers = dict()
69 |
70 | cdn_enabled = self.job_args.get('cdn_enabled')
71 | if cdn_enabled:
72 | headers['x-cdn-enabled'] = True
73 |
74 | cdn_disabled = self.job_args.get('cdn_disabled')
75 | if cdn_disabled:
76 | headers['x-cdn-enabled'] = False
77 |
78 | cdn_logs_enabled = self.job_args.get('cdn_logs_enabled')
79 | if cdn_logs_enabled:
80 | headers['x-log-retention'] = True
81 |
82 | cdn_logs_disabled = self.job_args.get('cdn_logs_disabled')
83 | if cdn_logs_disabled:
84 | headers['x-log-retention'] = False
85 |
86 | cnd_web_listing_enabled = self.job_args.get('cdn_web_enabled')
87 | if cnd_web_listing_enabled:
88 | headers['x-container-meta-web-listings'] = True
89 |
90 | cnd_web_listing_disabled = self.job_args.get('cdn_web_disabled')
91 | if cnd_web_listing_disabled:
92 | headers['x-container-meta-web-listings'] = False
93 |
94 | cdn_web_error_content = self.job_args.get('cdn_web_error_content')
95 | if cdn_web_error_content:
96 | headers['x-container-meta-web-error'] = cdn_web_error_content
97 |
98 | cdn_web_dir_type = self.job_args.get('cdn_web_dir_type')
99 | if cdn_web_error_content:
100 | headers['x-container-meta-web-directory-type'] = cdn_web_dir_type
101 |
102 | cdn_web_css_object = self.job_args.get('cdn_web_css_object')
103 | if cdn_web_css_object:
104 | headers['x-container-meta-web-listings-css'] = cdn_web_css_object
105 |
106 | cdn_web_index_object = self.job_args.get('cdn_web_index_object')
107 | if cdn_web_css_object:
108 | headers['X-Container-Meta-Web-Index'] = cdn_web_index_object
109 |
110 | headers['x-ttl'] = self.job_args.get('cdn_ttl')
111 |
112 | return self.job.container_cdn_command(
113 | url=self.job_args['cdn_storage_url'],
114 | container=self.job_args['container'],
115 | container_object=self.job_args['object'],
116 | cdn_headers=headers
117 | )
118 |
119 | def mkdir(self, path):
120 | self.shell.mkdir_p(path=path)
121 |
122 | def _delete(self, container_object=None):
123 | item = self.job.delete_items(
124 | url=self.job_args['storage_url'],
125 | container=self.job_args['container'],
126 | container_object=container_object
127 | )
128 | if item:
129 | LOG.debug(item.__dict__)
130 |
131 | def _get(self, container_object, local_object):
132 | self.job.get_items(
133 | url=self.job_args['storage_url'],
134 | container=self.job_args['container'],
135 | container_object=container_object,
136 | local_object=local_object
137 | )
138 |
139 | def remove_dirs(self, directory):
140 | """Delete a directory recursively.
141 |
142 | :param directory: $PATH to directory.
143 | :type directory: ``str``
144 | """
145 |
146 | LOG.info('Removing directory [ %s ]', directory)
147 | local_files = self._drectory_local_files(directory=directory)
148 | for file_name in local_files:
149 | try:
150 | os.remove(file_name['local_object'])
151 | except OSError as exp:
152 | LOG.error(str(exp))
153 |
154 | # Build a list of all local directories
155 | directories = sorted(
156 | [i for i, _, _ in os.walk(directory)],
157 | reverse=True
158 | )
159 |
160 | # Remove directories
161 | for directory_path in directories:
162 | try:
163 | os.removedirs(directory_path)
164 | except OSError as exp:
165 | if exp.errno != 2:
166 | LOG.error(str(exp))
167 | pass
168 |
169 | def _drectory_local_files(self, directory):
170 | directory = os.path.realpath(
171 | os.path.expanduser(
172 | directory
173 | )
174 | )
175 | if os.path.isdir(directory):
176 | object_items = self._walk_directories(directory)
177 | return object_items
178 | else:
179 | return self._return_deque()
180 |
181 | def _encapsulate_object(self, full_path, split_path):
182 | if self.job_args.get('preserve_path'):
183 | container_object = full_path
184 | else:
185 | container_object = full_path.split(split_path)[-1]
186 | container_object = container_object.lstrip(os.sep)
187 |
188 | object_item = {
189 | 'container_object': container_object,
190 | 'local_object': full_path
191 | }
192 |
193 | container_name = self.job_args.get('container')
194 | meta = object_item['meta'] = dict()
195 |
196 | if os.path.islink(full_path):
197 | link_path = os.path.realpath(
198 | os.path.expanduser(
199 | os.readlink(full_path)
200 | )
201 | )
202 | # When an object is a symylink the local object should be set to
203 | # None. This will ensure the system does not upload the "followed"
204 | # contents of the link.
205 | object_item['local_object'] = None
206 | link_object = link_path.split(split_path)[-1]
207 | meta['X-Object-Meta-symlink'] = link_path
208 | if link_path != link_object:
209 | meta['X-Object-Manifest'] = '%s%s%s' % (
210 | container_name,
211 | os.sep,
212 | link_object.lstrip(os.sep)
213 | )
214 | elif os.path.getsize(full_path) > self.large_object_size:
215 | manifest_path = full_path.split(split_path)[-1]
216 | meta['X-Object-Manifest'] = '%s%s%s' % (
217 | container_name,
218 | os.sep,
219 | manifest_path.lstrip(os.sep)
220 | )
221 |
222 | if self.job_args.get('save_perms'):
223 | obj = os.stat(full_path)
224 | meta['X-Object-Meta-perms'] = oct(obj.st_mode)[-4:]
225 | meta['X-Object-Meta-owner'] = pwd.getpwuid(obj.st_uid).pw_name
226 | meta['X-Object-Meta-group'] = grp.getgrgid(obj.st_gid).gr_name
227 |
228 | return object_item
229 |
230 | def _list_contents(self, last_obj=None, single_page_return=False):
231 | """Retrieve a long list of all files in a container.
232 |
233 | :return final_list, list_count, last_obj:
234 | """
235 | if self.job_args.get('cdn_containers'):
236 | if not self.job_args.get('fields'):
237 | self.job_args['fields'] = [
238 | 'name',
239 | 'cdn_enabled',
240 | 'log_retention',
241 | 'ttl'
242 | ]
243 | url = self.job_args['cdn_storage_url']
244 | else:
245 | url = self.job_args['storage_url']
246 |
247 | objects_list = self.job.list_items(
248 | url=url,
249 | container=self.job_args['container'],
250 | last_obj=last_obj,
251 | spr=single_page_return
252 | )
253 |
254 | pattern_match = self.job_args.get('pattern_match')
255 | if pattern_match:
256 | self.match_filter(
257 | idx_list=objects_list,
258 | pattern=pattern_match,
259 | dict_type=True
260 | )
261 |
262 | LOG.debug('List of objects: "%s"', objects_list)
263 | return objects_list
264 |
265 | def _multi_processor(self, func, items):
266 | base_queue = multiprocessing.Queue(maxsize=self.max_jobs)
267 | concurrency = self.job_args.get('concurrency')
268 | item_count = len(items)
269 | if concurrency > item_count:
270 | concurrency = item_count
271 |
272 | # Yield a queue of objects with a max input as set by `max_jobs`
273 | for queue in self._queue_generator(items, base_queue):
274 | self.indicator_options['msg'] = 'Processing workload...'
275 | self.indicator_options['work_q'] = queue
276 | with indicator.Spinner(**self.indicator_options):
277 | concurrent_jobs = [
278 | multiprocessing.Process(
279 | target=self._process_func,
280 | args=(func, queue,)
281 | ) for _ in range(concurrency)
282 | ]
283 |
284 | # Create an empty list to join later.
285 | join_jobs = list()
286 | try:
287 | for job in concurrent_jobs:
288 | join_jobs.append(job)
289 | job.start()
290 |
291 | # Join finished jobs
292 | for job in join_jobs:
293 | job.join()
294 | except KeyboardInterrupt:
295 | for job in join_jobs:
296 | job.terminate()
297 | else:
298 | exceptions.emergency_kill()
299 |
300 | def _named_local_files(self, object_names):
301 | object_items = self._return_deque()
302 | for object_name in object_names:
303 | full_path = os.path.realpath(
304 | os.path.expanduser(
305 | object_name
306 | )
307 | )
308 |
309 | if os.path.isfile(full_path) and full_path not in self.excludes:
310 | object_item = self._encapsulate_object(
311 | full_path=full_path,
312 | split_path=os.path.dirname(full_path)
313 | )
314 | if object_item:
315 | object_items.append(object_item)
316 | else:
317 | return object_items
318 |
319 | @staticmethod
320 | def _process_func(func, queue):
321 | while True:
322 | try:
323 | func(**queue.get(timeout=.5))
324 | except Queue.Empty:
325 | break
326 |
327 | def _queue_generator(self, items, queue):
328 | while items:
329 | item_count = len(items)
330 |
331 | if not item_count <= self.max_jobs:
332 | item_count = self.max_jobs
333 |
334 | for _ in range(item_count):
335 | try:
336 | queue.put(items.pop())
337 | except IndexError:
338 | pass
339 |
340 | yield queue
341 |
342 | def _return_container_objects(self):
343 | """Return a list of objects to delete.
344 |
345 | The return tuple will indicate if it was a userd efined list of objects
346 | as True of False.
347 | The list of objects is a list of dictionaries with the key being
348 | "container_object".
349 |
350 | :returns: tuple (``bol``, ``list``)
351 | """
352 |
353 | container_objects = self.job_args.get('object')
354 | if container_objects:
355 | return True, [{'container_object': i} for i in container_objects]
356 |
357 | container_objects = self.job_args.get('objects_file')
358 | if container_objects:
359 | container_objects = os.path.expanduser(container_objects)
360 | if os.path.isfile(container_objects):
361 | with open(container_objects) as f:
362 | return True, [
363 | {'container_object': i.rstrip('\n')}
364 | for i in f.readlines()
365 | ]
366 |
367 | container_objects = self._list_contents()
368 | pattern_match = self.job_args.get('pattern_match')
369 | if pattern_match:
370 | container_objects = self.match_filter(
371 | idx_list=container_objects,
372 | pattern=pattern_match,
373 | dict_type=True,
374 | dict_key='name'
375 | )
376 |
377 | # Reformat list for processing
378 | if container_objects and isinstance(container_objects[0], dict):
379 | return False, self._return_deque([
380 | {'container_object': i['name']} for i in container_objects
381 | ])
382 | else:
383 | return False, self._return_deque()
384 |
385 | @staticmethod
386 | def _return_deque(deque=None, item=None):
387 | if not deque:
388 | deque = collections.deque()
389 |
390 | if isinstance(item, list) or isinstance(item, collections.deque):
391 | deque.extend(item)
392 | elif utils.check_basestring(item=item):
393 | deque.append(item)
394 |
395 | return deque
396 |
397 | def _show(self, container, container_objects):
398 | if self.job_args.get('cdn_info'):
399 | if container_objects:
400 | raise exceptions.SystemProblem(
401 | 'You can not get CDN information on an object in your'
402 | ' container.'
403 | )
404 | url = self.job_args['cdn_storage_url']
405 | else:
406 | url = self.job_args['storage_url']
407 |
408 | if container_objects:
409 | returned_objects = self._return_deque()
410 | for container_object in container_objects:
411 | returned_objects.append(
412 | self.job.show_details(
413 | url=url,
414 | container=container,
415 | container_object=container_object
416 | )
417 | )
418 | else:
419 | return returned_objects
420 | else:
421 | return [
422 | self.job.show_details(
423 | url=url,
424 | container=container
425 | )
426 | ]
427 |
428 | def _update(self, container, container_objects):
429 | if not container_objects:
430 | container_objects = self._return_deque()
431 |
432 | returned_objects = list()
433 | for container_object in container_objects:
434 | returned_objects.append(
435 | self.job.update_object(
436 | url=self.job_args['storage_url'],
437 | container=container,
438 | container_object=container_object,
439 | container_headers=self.job_args.get('container_headers'),
440 | object_headers=self.job_args.get('object_headers')
441 | )
442 | )
443 | else:
444 | return returned_objects
445 |
446 | def _upload(self, meta, container_object, local_object):
447 | if local_object is not None and os.path.exists(local_object) is False:
448 | return
449 |
450 | item = self.job.put_object(
451 | url=self.job_args['storage_url'],
452 | container=self.job_args.get('container'),
453 | container_object=container_object,
454 | local_object=local_object,
455 | object_headers=self.job_args.get('object_headers'),
456 | meta=meta
457 | )
458 | if item:
459 | LOG.debug(item.__dict__)
460 |
461 | def _put_container(self):
462 | item = self.job.put_container(
463 | url=self.job_args['storage_url'],
464 | container=self.job_args.get('container')
465 | )
466 | if item:
467 | LOG.debug(item.__dict__)
468 |
469 | def _walk_directories(self, path):
470 | local_files = self._return_deque()
471 |
472 | if not os.path.isdir(path):
473 | path = os.path.dirname(path)
474 |
475 | for root_dir, _, file_names in os.walk(path):
476 | for file_name in file_names:
477 | full_path = os.path.join(root_dir, file_name)
478 | if full_path not in self.excludes:
479 | object_item = self._encapsulate_object(
480 | full_path=full_path,
481 | split_path=path
482 | )
483 | if object_item:
484 | local_files.append(object_item)
485 | else:
486 | pattern_match = self.job_args.get('pattern_match')
487 | if pattern_match:
488 | local_files = self.match_filter(
489 | idx_list=local_files,
490 | pattern=pattern_match,
491 | dict_type=True,
492 | dict_key='container_object'
493 | )
494 |
495 | return local_files
496 |
497 | def _index_fs(self):
498 | """Returns a deque object full of local file system items.
499 |
500 | :returns: ``deque``
501 | """
502 |
503 | indexed_objects = self._return_deque()
504 |
505 | directory = self.job_args.get('directory')
506 | if directory:
507 | indexed_objects = self._return_deque(
508 | deque=indexed_objects,
509 | item=self._drectory_local_files(
510 | directory=directory
511 | )
512 | )
513 |
514 | object_names = self.job_args.get('object')
515 | if object_names:
516 | indexed_objects = self._return_deque(
517 | deque=indexed_objects,
518 | item=self._named_local_files(
519 | object_names=object_names
520 | )
521 | )
522 |
523 | return indexed_objects
524 |
525 | def _compressor(self, file_list):
526 | # Set the name of the archive.
527 | tar_name = self.job_args.get('tar_name')
528 | tar_name = os.path.realpath(os.path.expanduser(tar_name))
529 | if not os.path.isdir(os.path.dirname(tar_name)):
530 | raise exceptions.DirectoryFailure(
531 | 'The path to save the archive file does not exist.'
532 | ' PATH: [ %s ]',
533 | tar_name
534 | )
535 |
536 | if not tar_name.endswith('.tgz'):
537 | tar_name = '%s.tgz' % tar_name
538 |
539 | if self.job_args.get('add_timestamp'):
540 | # Set date and time
541 | date_format = '%a%b%d.%H.%M.%S.%Y'
542 | today = datetime.datetime.today()
543 | timestamp = today.strftime(date_format)
544 | _tar_name = os.path.basename(tar_name)
545 | tar_name = os.path.join(
546 | os.path.dirname(tar_name), '%s-%s' % (timestamp, _tar_name)
547 | )
548 |
549 | # Begin creating the Archive.
550 | verify = self.job_args.get('verify')
551 | verify_list = self._return_deque()
552 | with tarfile.open(tar_name, 'w:gz') as tar:
553 | while file_list:
554 | try:
555 | local_object = file_list.pop()['local_object']
556 | if verify:
557 | verify_list.append(local_object)
558 | tar.add(local_object)
559 | except IndexError:
560 | break
561 |
562 | if verify:
563 | with tarfile.open(tar_name, 'r') as tar:
564 | verified_items = self._return_deque()
565 | for member_info in tar.getmembers():
566 | verified_items.append(member_info.name)
567 |
568 | if len(verified_items) != len(verify_list):
569 | raise exceptions.SystemProblem(
570 | 'ARCHIVE NOT VERIFIED: Archive and File List do not'
571 | ' Match.'
572 | )
573 |
574 | return {
575 | 'meta': dict(),
576 | 'local_object': tar_name,
577 | 'container_object': os.path.basename(tar_name)
578 | }
579 |
580 | def match_filter(self, idx_list, pattern, dict_type=False,
581 | dict_key='name'):
582 | """Return Matched items in indexed files.
583 |
584 | :param idx_list:
585 | :return list
586 | """
587 |
588 | if dict_type is False:
589 | return self._return_deque([
590 | obj for obj in idx_list
591 | if re.search(pattern, obj)
592 | ])
593 | elif dict_type is True:
594 | return self._return_deque([
595 | obj for obj in idx_list
596 | if re.search(pattern, obj.get(dict_key))
597 | ])
598 | else:
599 | return self._return_deque()
600 |
601 | def print_horiz_table(self, data):
602 | """Print a horizontal pretty table from data."""
603 |
604 | # Build list of returned objects
605 | return_objects = list()
606 | fields = self.job_args.get('fields')
607 | if not fields:
608 | fields = set()
609 | for item_dict in data:
610 | for field_item in item_dict.keys():
611 | fields.add(field_item)
612 | fields = sorted(fields)
613 |
614 | for obj in data:
615 | item_struct = dict()
616 | for item in fields:
617 | item_struct[item] = obj.get(item)
618 | else:
619 | return_objects.append(item_struct)
620 |
621 | table = prettytable.PrettyTable(fields)
622 | for obj in return_objects:
623 | table.add_row([obj.get(i) for i in fields])
624 |
625 | for tbl in table.align.keys():
626 | table.align[tbl] = 'l'
627 |
628 | sort_key = self.job_args.get('sort_by')
629 | if sort_key:
630 | table.sortby = sort_key
631 |
632 | self.printer(table)
633 |
634 | def print_virt_table(self, data):
635 | """Print a vertical pretty table from data."""
636 |
637 | table = prettytable.PrettyTable()
638 | keys = sorted(data.keys())
639 | table.add_column('Keys', keys)
640 | table.add_column('Values', [data.get(i) for i in keys])
641 | for tbl in table.align.keys():
642 | table.align[tbl] = 'l'
643 |
644 | self.printer(table)
645 |
646 | def printer(self, message, color_level='info'):
647 | """Print Messages and Log it.
648 |
649 | :param message: item to print to screen
650 | """
651 |
652 | if self.job_args.get('colorized'):
653 | print(cloud_utils.return_colorized(msg=message, color=color_level))
654 | else:
655 | print(message)
656 |
657 | def start(self):
658 | """This method must be overridden."""
659 | pass
660 |
--------------------------------------------------------------------------------
/turbolift/methods/archive.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import os
12 |
13 | from cloudlib import logger
14 | from cloudlib import indicator
15 |
16 | from turbolift import methods
17 |
18 |
19 | LOG = logger.getLogger('turbolift')
20 |
21 |
22 | class ArchiveRunMethod(methods.BaseMethod):
23 | """Setup and run the list Method."""
24 |
25 | def __init__(self, job_args):
26 | super(ArchiveRunMethod, self).__init__(job_args)
27 |
28 | def start(self):
29 | LOG.info('Archiving...')
30 | with indicator.Spinner(**self.indicator_options):
31 | archive = self._compressor(file_list=self._index_fs())
32 |
33 | LOG.info('Ensuring Container...')
34 | with indicator.Spinner(**self.indicator_options):
35 | self._put_container()
36 |
37 | LOG.info('Uploading Archive...')
38 | upload_objects = self._return_deque()
39 | archive_item = self._encapsulate_object(
40 | full_path=archive['local_object'],
41 | split_path=os.path.dirname(archive['local_object'])
42 | )
43 | upload_objects.append(archive_item)
44 |
45 | self._multi_processor(self._upload, items=upload_objects)
46 |
47 | if not self.job_args.get('no_cleanup'):
48 | os.remove(archive['local_object'])
49 |
--------------------------------------------------------------------------------
/turbolift/methods/cdn_command.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | from cloudlib import logger
12 | from cloudlib import indicator
13 |
14 | from turbolift import methods
15 |
16 |
17 | LOG = logger.getLogger('turbolift')
18 |
19 |
20 | class CdnRunMethod(methods.BaseMethod):
21 | """Setup and run the cdn Method."""
22 |
23 | def __init__(self, job_args):
24 | super(CdnRunMethod, self).__init__(job_args)
25 |
26 | def start(self):
27 | """Return a list of objects from the API for a container."""
28 | LOG.info('Interacting with the CDN...')
29 | with indicator.Spinner(run=self.run_indicator):
30 | cdn_item = self._cdn()
31 |
32 | self.print_virt_table(cdn_item.headers)
33 |
--------------------------------------------------------------------------------
/turbolift/methods/clone.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import os
12 | import tempfile
13 |
14 | from cloudlib import logger
15 | from cloudlib import indicator
16 |
17 | from turbolift.authentication import auth
18 | from turbolift import methods
19 | from turbolift import utils
20 | import turbolift
21 |
22 | LOG = logger.getLogger('turbolift')
23 |
24 |
25 | class CloneRunMethod(methods.BaseMethod):
26 | """Setup and run the clone method."""
27 |
28 | def __init__(self, job_args):
29 | super(CloneRunMethod, self).__init__(job_args)
30 | # TODO(cloudnull) Remove this in future releases
31 | source_container = self.job_args.get('source_container')
32 | if source_container:
33 | LOG.warn(
34 | 'The use of the ``--source-container`` flag has been'
35 | ' deprecated and will be removed in future releases. Please'
36 | ' use the ``--container`` flag instead.'
37 | )
38 | self.job_args['container'] = self.job_args['source_container']
39 |
40 | self.target_args = self.job_args.copy()
41 | self.target_process = None
42 |
43 | def _target_auth(self):
44 | self.target_args['container'] = self.job_args['target_container']
45 | self.target_args['os_region'] = self.job_args['target_region']
46 |
47 | # Set the target auth url
48 | target_auth_url = self.job_args.get('target_auth_url')
49 | if target_auth_url:
50 | self.target_args['os_auth_url'] = target_auth_url
51 |
52 | # Set the target user
53 | target_user = self.job_args.get('target_user')
54 | if target_user:
55 | self.target_args['os_user'] = target_user
56 |
57 | # Set the target password
58 | target_password = self.job_args.get('target_password')
59 | if target_password:
60 | self.target_args['os_password'] = target_password
61 |
62 | # Set the target apikey
63 | target_apikey = self.job_args.get('target_apikey')
64 | if target_apikey:
65 | self.target_args['os_apikey'] = target_apikey
66 |
67 | # Disable any active auth plugins, This is done because all information
68 | # that may be needed from the plugin is already loaded.
69 | auth_plugin_list = turbolift.auth_plugins(
70 | auth_plugins=self.job_args.get('auth_plugins')
71 | )
72 | for item in auth_plugin_list.keys():
73 | self.target_args[item] = None
74 |
75 | # Authenticate to the target region
76 | LOG.info('Authenticating against the target')
77 | self.target_args.update(
78 | auth.authenticate(
79 | job_args=self.target_args
80 | )
81 | )
82 |
83 | def _clone(self, container_object, object_headers):
84 | local_temp_object = os.path.join(
85 | self.job_args['clone_workspace'],
86 | container_object
87 | )
88 | try:
89 | self.job.get_items(
90 | url=self.job_args['storage_url'],
91 | container=self.job_args['container'],
92 | container_object=container_object,
93 | local_object=local_temp_object
94 | )
95 | self.job.put_object(
96 | url=self.target_args['storage_url'],
97 | container=self.target_args['container'],
98 | container_object=container_object,
99 | local_object=local_temp_object,
100 | object_headers=object_headers
101 | )
102 | finally:
103 | if os.path.isfile(local_temp_object):
104 | os.remove(local_temp_object)
105 |
106 | def _check_clone(self, *args, **kwargs):
107 | resp = self.job.show_details(
108 | url=self.target_args['storage_url'],
109 | container=self.target_args['container'],
110 | container_object=kwargs['name']
111 | )
112 |
113 | check_hashes = resp.headers.get('etag') == kwargs['hash']
114 | if resp.status_code == 404 or not check_hashes:
115 | self._clone(
116 | container_object=kwargs['name'],
117 | object_headers=resp.headers
118 | )
119 | else:
120 | LOG.debug(
121 | 'Nothing cloned. Object "%s" is the same in both regions,'
122 | ' [ %s ] and [ %s ]',
123 | kwargs['name'],
124 | self.target_args['os_region'],
125 | self.job_args['os_region']
126 | )
127 |
128 | def _clone_worker(self, objects_list):
129 | log_msg = self.indicator_options['msg'] = 'Ensuring Target Container'
130 | LOG.info(log_msg)
131 | with indicator.Spinner(**self.indicator_options):
132 | self.job.put_container(
133 | url=self.target_args['storage_url'],
134 | container=self.target_args['container']
135 | )
136 |
137 | log_msg = self.indicator_options['msg'] = 'Creating workspace'
138 | LOG.info(log_msg)
139 | with indicator.Spinner(**self.indicator_options):
140 | workspace = self.job_args['clone_workspace'] = tempfile.mkdtemp(
141 | suffix='_clone',
142 | prefix='turbolift_',
143 | dir=self.job_args.get('workspace')
144 | )
145 | working_dirs = set(
146 | [os.path.dirname(i['name']) for i in objects_list]
147 | )
148 | for item in working_dirs:
149 | self.mkdir(
150 | path=os.path.join(
151 | self.job_args['clone_workspace'],
152 | item
153 | )
154 | )
155 |
156 | LOG.info('Running Clone')
157 | try:
158 | self._multi_processor(self._check_clone, items=objects_list)
159 | finally:
160 | self.remove_dirs(workspace)
161 |
162 | def start(self):
163 | """Clone objects from one container to another.
164 |
165 | This method was built to clone a container between data-centers while
166 | using the same credentials. The method assumes that an authentication
167 | token will be valid within the two data centers.
168 | """
169 |
170 | LOG.info('Clone warm up...')
171 | # Create the target args
172 | self._target_auth()
173 |
174 | last_list_obj = None
175 | while True:
176 | self.indicator_options['msg'] = 'Gathering object list'
177 | with indicator.Spinner(**self.indicator_options):
178 | objects_list = self._list_contents(
179 | single_page_return=True,
180 | last_obj=last_list_obj
181 | )
182 | if not objects_list:
183 | return
184 |
185 | last_obj = utils.byte_encode(objects_list[-1].get('name'))
186 | LOG.info(
187 | 'Last object [ %s ] Last object in the list [ %s ]',
188 | last_obj,
189 | last_list_obj
190 | )
191 | if last_list_obj == last_obj:
192 | return
193 | else:
194 | last_list_obj = last_obj
195 | self._clone_worker(objects_list=objects_list)
196 |
--------------------------------------------------------------------------------
/turbolift/methods/delete_items.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | from cloudlib import logger
12 | from cloudlib import indicator
13 |
14 | from turbolift import methods
15 |
16 | LOG = logger.getLogger('turbolift')
17 |
18 |
19 | class DeleteRunMethod(methods.BaseMethod):
20 | """Setup and run the list Method."""
21 |
22 | def __init__(self, job_args):
23 | super(DeleteRunMethod, self).__init__(job_args)
24 |
25 | def start(self):
26 | LOG.warn('Deleting...')
27 | # Perform the delete twice
28 | user_defined, _objects = self._return_container_objects()
29 | while _objects:
30 | self._multi_processor(
31 | self._delete,
32 | items=_objects
33 | )
34 | if not user_defined:
35 | user_defined, _objects = self._return_container_objects()
36 | LOG.warn(
37 | 'Rerunning the delete to Verify the objects have been'
38 | ' deleted.'
39 | )
40 |
41 | # Delete the container unless instructed to save it
42 | if not self.job_args.get('save_container') or not user_defined:
43 | self._delete()
44 |
--------------------------------------------------------------------------------
/turbolift/methods/download.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import collections
12 | import os
13 |
14 | from cloudlib import logger
15 | from cloudlib import indicator
16 |
17 | from turbolift import methods
18 |
19 |
20 | LOG = logger.getLogger('turbolift')
21 |
22 |
23 | class DownloadRunMethod(methods.BaseMethod):
24 | """Setup and run the Download Method."""
25 |
26 | def __init__(self, job_args):
27 | super(DownloadRunMethod, self).__init__(job_args)
28 | self.download_items = collections.defaultdict(list)
29 |
30 | def _index_objects(self, objects_list):
31 | LOG.info('Indexing dowload objects...')
32 |
33 | if not self.job_args['directory'].endswith(os.sep):
34 | self.job_args['directory'] = '%s%s' % (
35 | self.job_args['directory'], os.sep
36 | )
37 |
38 | with indicator.Spinner(**self.indicator_options):
39 | for item in objects_list:
40 | normalized_name = item['name'].lstrip(os.sep)
41 | directory = os.path.join(
42 | self.job_args['directory'].rstrip(os.sep),
43 | os.path.dirname(normalized_name)
44 | )
45 |
46 | self.download_items[directory].append(
47 | {
48 | 'container_object': item.get('name'),
49 | 'local_object': '%s%s' % (
50 | self.job_args['directory'],
51 | normalized_name
52 | )
53 | }
54 | )
55 |
56 | def _make_directory_structure(self):
57 | LOG.info('Creating local directory structure...')
58 | with indicator.Spinner(**self.indicator_options):
59 | for item in self.download_items.keys():
60 | self.mkdir(item)
61 |
62 | def start(self):
63 | """Return a list of objects from the API for a container."""
64 | LOG.info('Listing options...')
65 | with indicator.Spinner(**self.indicator_options):
66 | objects_list = self._list_contents()
67 | if not objects_list:
68 | return
69 |
70 | # Index items
71 | self._index_objects(objects_list=objects_list)
72 | # Create the underlying structure
73 | self._make_directory_structure()
74 |
75 | # Download everything
76 | LOG.debug('Download Items: %s', self.download_items)
77 | self._multi_processor(
78 | self._get,
79 | items=[i for i in self.download_items.values() for i in i]
80 | )
81 |
--------------------------------------------------------------------------------
/turbolift/methods/list_items.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | import hashlib
12 |
13 | from cloudlib import logger
14 | from cloudlib import indicator
15 |
16 | from turbolift import methods
17 |
18 |
19 | LOG = logger.getLogger('turbolift')
20 |
21 |
22 | class ListRunMethod(methods.BaseMethod):
23 | """Setup and run the list Method."""
24 |
25 | def __init__(self, job_args):
26 | super(ListRunMethod, self).__init__(job_args)
27 |
28 | def start(self):
29 | """Return a list of objects from the API for a container."""
30 | LOG.info('Listing options...')
31 | with indicator.Spinner(**self.indicator_options):
32 | objects_list = self._list_contents()
33 | if not objects_list:
34 | return
35 |
36 | if isinstance(objects_list[0], dict):
37 | filter_dlo = self.job_args.get('filter_dlo')
38 | if filter_dlo:
39 | dynamic_hash = hashlib.sha256(
40 | self.job_args.get('container')
41 | )
42 | dynamic_hash = dynamic_hash.hexdigest()
43 | objects_list = [
44 | i for i in objects_list
45 | if dynamic_hash not in i.get('name')
46 | ]
47 | string_filter = self.job_args.get('filter')
48 | if string_filter:
49 | objects_list = [
50 | i for i in objects_list
51 | if string_filter in i.get('name')
52 | ]
53 | self.print_horiz_table(objects_list)
54 | else:
55 | self.print_virt_table(objects_list[0].headers)
56 |
--------------------------------------------------------------------------------
/turbolift/methods/show_items.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | from cloudlib import logger
12 | from cloudlib import indicator
13 |
14 | from turbolift import methods
15 |
16 |
17 | LOG = logger.getLogger('turbolift')
18 |
19 |
20 | class ShowRunMethod(methods.BaseMethod):
21 | """Setup and run the list Method."""
22 |
23 | def __init__(self, job_args):
24 | super(ShowRunMethod, self).__init__(job_args)
25 |
26 | def start(self):
27 | LOG.info('Grabbing details...')
28 | with indicator.Spinner(**self.indicator_options):
29 | items = self._show(
30 | container=self.job_args['container'],
31 | container_objects=self.job_args.get('object')
32 | )
33 |
34 | for item in items:
35 | self.print_virt_table(item.headers)
36 |
--------------------------------------------------------------------------------
/turbolift/methods/update_items.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | from cloudlib import logger
12 | from cloudlib import indicator
13 |
14 | from turbolift import methods
15 |
16 |
17 | LOG = logger.getLogger('turbolift')
18 |
19 |
20 | class UpdateRunMethod(methods.BaseMethod):
21 | """Setup and run the list Method."""
22 |
23 | def __init__(self, job_args):
24 | super(UpdateRunMethod, self).__init__(job_args)
25 |
26 | def start(self):
27 | LOG.info('Updating...')
28 | with indicator.Spinner(**self.indicator_options):
29 | items = self._update(
30 | container=self.job_args['container'],
31 | container_objects=self.job_args.get('object')
32 | )
33 |
34 | for item in items:
35 | self.print_virt_table(item.headers)
36 |
--------------------------------------------------------------------------------
/turbolift/methods/upload_items.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | from cloudlib import logger
12 | from cloudlib import indicator
13 |
14 | from turbolift import exceptions
15 | from turbolift import methods
16 |
17 |
18 | LOG = logger.getLogger('turbolift')
19 |
20 |
21 | class UploadRunMethod(methods.BaseMethod):
22 | """Setup and run the list Method."""
23 |
24 | def __init__(self, job_args):
25 | super(UploadRunMethod, self).__init__(job_args)
26 |
27 | def start(self):
28 | LOG.info('Indexing File System...')
29 | with indicator.Spinner(**self.indicator_options):
30 | upload_objects = self._index_fs()
31 |
32 | if not upload_objects:
33 | raise exceptions.DirectoryFailure(
34 | 'No objects found to process. Check your command.'
35 | )
36 |
37 | LOG.info('Ensuring Container...')
38 | with indicator.Spinner(**self.indicator_options):
39 | self._put_container()
40 |
41 | self._multi_processor(self._upload, items=upload_objects)
42 |
--------------------------------------------------------------------------------
/turbolift/utils.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 |
12 | def check_basestring(item):
13 | """Return ``bol`` on string check item.
14 |
15 | :param item: Item to check if its a string
16 | :type item: ``str``
17 | :returns: ``bol``
18 | """
19 | try:
20 | return isinstance(item, (basestring, unicode))
21 | except NameError:
22 | return isinstance(item, str)
23 |
24 |
25 | def byte_encode(string):
26 | try:
27 | return string.encode('utf-8')
28 | except AttributeError:
29 | return string
30 |
--------------------------------------------------------------------------------
/turbolift/worker.py:
--------------------------------------------------------------------------------
1 | # =============================================================================
2 | # Copyright [2015] [Kevin Carter]
3 | # License Information :
4 | # This software has no warranty, it is provided 'as is'. It is your
5 | # responsibility to validate the behavior of the routines and its accuracy
6 | # using the code provided. Consult the GNU General Public license for further
7 | # details (see GNU General Public License).
8 | # http://www.gnu.org/licenses/gpl.html
9 | # =============================================================================
10 |
11 | from cloudlib import logger
12 | from cloudlib import indicator
13 |
14 | from turbolift.authentication import auth
15 | from turbolift import exceptions
16 |
17 |
18 | LOG = logger.getLogger('turbolift')
19 |
20 |
21 | class Worker(object):
22 | def __init__(self, job_args):
23 | self.job_args = job_args
24 | self.job_map = {
25 | 'archive': 'turbolift.methods.archive:ArchiveRunMethod',
26 | 'cdn': 'turbolift.methods.cdn_command:CdnRunMethod',
27 | 'clone': 'turbolift.methods.clone:CloneRunMethod',
28 | 'delete': 'turbolift.methods.delete_items:DeleteRunMethod',
29 | 'download': 'turbolift.methods.download:DownloadRunMethod',
30 | 'list': 'turbolift.methods.list_items:ListRunMethod',
31 | 'show': 'turbolift.methods.show_items:ShowRunMethod',
32 | 'update': 'turbolift.methods.update_items:UpdateRunMethod',
33 | 'upload': 'turbolift.methods.upload_items:UploadRunMethod',
34 | }
35 |
36 | @staticmethod
37 | def _get_method(method):
38 | """Return an imported object.
39 |
40 | :param method: ``str`` DOT notation for import with Colin used to
41 | separate the class used for the job.
42 | :returns: ``object`` Loaded class object from imported method.
43 | """
44 |
45 | # Split the class out from the job
46 | module = method.split(':')
47 |
48 | # Set the import module
49 | _module_import = module[0]
50 |
51 | # Set the class name to use
52 | class_name = module[-1]
53 |
54 | # import the module
55 | module_import = __import__(_module_import, fromlist=[class_name])
56 |
57 | # Return the attributes for the imported module and class
58 | return getattr(module_import, class_name)
59 |
60 | @staticmethod
61 | def _str_headers(header):
62 | """Return a dict from a 'KEY=VALUE' string.
63 |
64 | :param header: ``str``
65 | :returns: ``dict``
66 | """
67 |
68 | return dict(header.spit('='))
69 |
70 | @staticmethod
71 | def _list_headers(headers):
72 | """Return a dict from a list of KEY=VALUE strings.
73 |
74 | :param headers: ``list``
75 | :returns: ``dict``
76 | """
77 |
78 | return dict([_kv.split('=') for _kv in headers])
79 |
80 | def run_manager(self, job_override=None):
81 | """The run manager.
82 |
83 | The run manager is responsible for loading the plugin required based on
84 | what the user has inputted using the parsed_command value as found in
85 | the job_args dict. If the user provides a *job_override* the method
86 | will attempt to import the module and class as provided by the user.
87 |
88 | Before the method attempts to run any job the run manager will first
89 | authenticate to the the cloud provider.
90 |
91 | :param job_override: ``str`` DOT notation for import with Colin used to
92 | separate the class used for the job.
93 | """
94 |
95 | for arg_name, arg_value in self.job_args.items():
96 | if arg_name.endswith('_headers'):
97 | if isinstance(arg_value, list):
98 | self.job_args[arg_name] = self._list_headers(
99 | headers=arg_value
100 | )
101 | elif not arg_name:
102 | self.job_args[arg_name] = self._str_headers(
103 | header=arg_value
104 | )
105 | else:
106 | self.job_args[arg_name] = dict()
107 |
108 | # Set base header for the user-agent
109 | self.job_args['base_headers']['User-Agent'] = 'turbolift'
110 |
111 | LOG.info('Authenticating')
112 | indicator_options = {'run': self.job_args.get('run_indicator', True)}
113 | with indicator.Spinner(**indicator_options):
114 | LOG.debug('Authenticate against the Service API')
115 | self.job_args.update(auth.authenticate(job_args=self.job_args))
116 |
117 | if job_override:
118 | action = self._get_method(method=job_override)
119 | else:
120 | parsed_command = self.job_args.get('parsed_command')
121 | if not parsed_command:
122 | raise exceptions.NoCommandProvided(
123 | 'Please provide a command. Basic commands are: %s',
124 | list(self.job_map.keys())
125 | )
126 | else:
127 | action = self._get_method(method=self.job_map[parsed_command])
128 |
129 | run = action(job_args=self.job_args)
130 | run.start()
131 |
--------------------------------------------------------------------------------