knife-mirror 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9e9df5f32eafbd870052b94aaf48203c58bba73d
4
+ data.tar.gz: a806c489d3ca99d77a622dc1248208ffd887ee38
5
+ SHA512:
6
+ metadata.gz: 437b74da06762c2cf1ece6b7dbaa7206177318a74f3c69e11a092e302173a99ac22c1262f5292ee7c536550034676416cdba7fae5066d7246a0743ecc855adcf
7
+ data.tar.gz: 1a42e9dbc1306de3e87ed252a43975e10b730601b2958ec3d14bd7869703c43386cc867bbb69882f37107a9831c17b4feae81e0f382c666b08c2302d716535f0
data/.gitignore ADDED
@@ -0,0 +1,38 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /test/tmp/
9
+ /test/version_tmp/
10
+ /tmp/
11
+
12
+ ## Specific to RubyMotion:
13
+ .dat*
14
+ .repl_history
15
+ build/
16
+
17
+ ## Documentation cache and generated files:
18
+ /.yardoc/
19
+ /_yardoc/
20
+ /doc/
21
+ /rdoc/
22
+
23
+ ## Environment normalisation:
24
+ /.bundle/
25
+ /vendor/bundle
26
+ /lib/bundler/man/
27
+
28
+ # for a library or gem, you might want to ignore these files since the code is
29
+ # intended to run in multiple environments; otherwise, check them in:
30
+ Gemfile.lock
31
+ .ruby-version
32
+ .ruby-gemset
33
+
34
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
35
+ .rvmrc
36
+
37
+ # knife mirror [cookbook] all --keep keeps *.tar.gz files around in current directory
38
+ *.tar.gz
data/.rubocop.yml ADDED
@@ -0,0 +1,14 @@
1
+ Metrics/AbcSize:
2
+ Enabled: false
3
+ Metrics/ClassLength:
4
+ Enabled: false
5
+ Metrics/CyclomaticComplexity:
6
+ Enabled: false
7
+ Metrics/LineLength:
8
+ Max: 240
9
+ Metrics/MethodLength:
10
+ Enabled: false
11
+ Metrics/PerceivedComplexity:
12
+ Enabled: false
13
+ Style/SpecialGlobalVars:
14
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # knife-mirror Change log
2
+
3
+ ## 0.1.0 (2015-09-23)
4
+
5
+ - Initial version (still lots of WIP)
6
+ - mirror single cookbook version(s)
7
+ - mirror single cookbook, all versions
8
+ - mirror all cookbooks, all versions
9
+ - skip on (most) errors
10
+ - specify source and target Supermarkets
11
+ - save failed cookbook versions
12
+ - configurable delay to ease load on Supermarkets
13
+ - disable meta data replication, supermarket does not honor it anyways
14
+ - add some initial docs to readme
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # Knife Mirror plugin
2
+
3
+ This plugin adds additional functionality to the Chef Knife command line tool for mirroring Chef Supermarket content (community &amp; private, cookbooks, tools etc)
4
+
5
+ Still WIP, use at your own risk of course :-)
6
+
7
+ This started out as some simple poc code, as an extra extension/command to knife-supermarket (knife supermarket mirror).
8
+ While that still makes sense, I went for this specific 'knife-mirror' Gem for now.
9
+
10
+ oh, and, this is my first ever Gem, I don't have a clue what I'm doing...
11
+
12
+ ## Currently it does the following
13
+
14
+ - mirror single cookbook version(s)
15
+ - mirror single cookbook, all versions
16
+ - mirror all cookbooks, all versions
17
+ - skip on (most) errors
18
+ - specify source and target Supermarkets
19
+ - save failed cookbook versions
20
+ - configurable delay to ease load on Supermarkets
21
+
22
+ Most is based on working with diffs between source and target so we do not waste too many resources.
23
+
24
+ ## Some notes (ok, a lot)
25
+
26
+ Please Note: currently, ownership for uploaded cookbooks is set to you, the knife user/client.
27
+
28
+ Another Note: the community supermarket contains cookbooks, specifically older/early versions, which do not process correctly in newer/recent (private) supermarkets.
29
+ Not much I can do about that. Most failures have to do with improper platform arrays in metadata.
30
+ Mirroring will simply skip these faulty versions.
31
+
32
+ k, one more Note: please understand we pass cookbook tarballs unaltered! Do not blame this mirror tool for not being able to process some cookbook version(s).
33
+
34
+ Again: we do not unpack any downloaded cookbooks locally, this mirroring works differently from the usual download and share process.
35
+
36
+ Last Note: Had code in place for replicating 'category' and other meta data, however, that causes mirroring to skip a lot of cookbooks since by default:
37
+
38
+ ```
39
+ supermarket=# SELECT * FROM categories;
40
+ id | name | created_at | updated_at | slug
41
+ ----+-------+----------------------------+----------------------------+-------
42
+ 1 | Other | 2015-09-07 15:40:29.854929 | 2015-09-07 15:40:29.854929 | other
43
+ (1 row)
44
+ ```
45
+
46
+ If the requested catagory does not exist, supermarket refuses to accept the cookbook :(
47
+
48
+ So obviously need to revisit that.
49
+
50
+ Last minute: Just noticed during some final tests, before releasing this first version; if you attempt a ```knife mirror cookbook all``` or ```knife mirror all``` to an 'empty' new fresh supermarket, things will fail.
51
+ Please, as a workaround for now, just mirror a recent version for some cookbook first, as in, ```knife mirror apt -t https://supermarket.your.domain.tld```.
52
+ I'll fix this asap, simply need to add some endpoint checking of course, mea culpa.
53
+
54
+ ## Requirements
55
+
56
+ - You need to have Chef Knife working
57
+ - You need an account on the target supermarket of course
58
+ - This Gem, dohh
59
+
60
+ You do not need an account on the source/community supermarket.
61
+
62
+ ## Install
63
+
64
+ ```
65
+ gem install knife-mirror
66
+ ```
67
+
68
+ or obtain this source (git clone or whatever) and
69
+
70
+ ```
71
+ gem build knife-mirror.gemspec; gem install knife-mirror-0.1.0.gem
72
+ ```
73
+
74
+ ## Use
75
+
76
+ For using knife you obviously need a matching key pair.
77
+ You have the private key on your workstation while the pub key is stored on chef server.
78
+ By using oauth2, Supermarket will know your pub key as well, allowing for knife to work with Supermarket as well.
79
+ So, at least sign in once, after which you should be able to knife to the Supermarket.
80
+
81
+ Then things are really simple, while we still work on more advanced stuff:
82
+
83
+ ### Only most recent version for a specific cookbook
84
+
85
+ ```
86
+ knife mirror apt -t https://supermarket.your.domain.tld
87
+ ```
88
+
89
+ ### Specific cookbook version
90
+
91
+ ```
92
+ knife mirror apt 1.2.3 -t https://supermarket.your.domain.tld
93
+ ```
94
+
95
+ ### Specific cookbook, all versions
96
+
97
+ ```
98
+ knife mirror apt all -t https://supermarket.your.domain.tld
99
+ ```
100
+
101
+ ### All cookbooks
102
+
103
+ ```
104
+ knife mirror all -t https://supermarket.your.domain.tld
105
+ ```
106
+
107
+ ### All cookbooks, delay 30 secs, keep failed cookbook versions
108
+
109
+ ```
110
+ knife mirror all -t https://supermarket.your.domain.tld --delay 30 --keep
111
+ ```
112
+
113
+ ### All cookbooks, from one private supermarket to some other private supermarket, keep failed cookbooks in a subdir 'temp'
114
+
115
+ ```
116
+ knife mirror all -m https://supermarketA.your.domain.tld -t https://supermarketB.your.domain.tld --keep -d temp
117
+ ```
118
+
119
+ Obviously the ```--delay``` only makes sense for multiple versions and/or multiple cookbooks.
120
+
121
+ The ```--keep``` will save a tarball: cookbook-version.tar.gz
122
+
123
+ The ```--keep -d temp``` will save tarballs to: temp/cookbook-version.tar.gz (please ensure 'temp' exists)
124
+
125
+ ## Todo
126
+
127
+ Wow, still lots to do, lots of wishes :(
128
+
129
+ - proper replication of deprecation flag (not honored as part of the cookbook meta upload)
130
+ - proper replication of urls (same reason)
131
+ - replicate (and create) categories?
132
+ - process dependencies
133
+ - process replacement in case we're mirroring a deprecated cookbook
134
+ - some automated testing
135
+ - more/better docs?
136
+ - find/work a way to replicate/correct/assign ownership
137
+
138
+ That last item still needs some further research, though I have some very good clues to work out and try.
139
+
140
+ The other items are fairly trivial though I find it a bit frustrating the Supermarket code won't simply honor extra meta data. Currently it only handles 'category'.
141
+ Maybe I'll create a patch against Supermarket and submit a PR, though I'll first run that by Chef to find out if that would make sense.
142
+ Until that time though, things require some extra calls :(
143
+
144
+ ## Rubocop and friends
145
+
146
+ Yes, rubocop still likes complaining about some complexity and linelength. So sue me...
147
+
148
+ Pulling things apart into sep methods and such won't make things more efficient. But I'll look into it some time ;-)
149
+
150
+ For now I was more concerned with making it work and putting it out there. I'm convinced things can be refactored, yes.
151
+
152
+ ## CONTRIBUTING
153
+
154
+ Please file bugs against this project at [Knife mirror issues](https://github.com/gjmoed/knife-mirror/issues).
155
+
156
+ ## LICENSE
157
+
158
+ ```
159
+ Author:: G.J. Moed (<gmoed@kobo.com>)
160
+ Copyright:: Copyright (c) 2015 Rakuten Kobo Inc.
161
+ License:: Apache License, Version 2.0
162
+
163
+ Licensed under the Apache License, Version 2.0 (the "License");
164
+ you may not use this file except in compliance with the License.
165
+ You may obtain a copy of the License at
166
+
167
+ http://www.apache.org/licenses/LICENSE-2.0
168
+
169
+ Unless required by applicable law or agreed to in writing, software
170
+ distributed under the License is distributed on an "AS IS" BASIS,
171
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
172
+ See the License for the specific language governing permissions and
173
+ limitations under the License.
174
+ ```
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler'
2
+ require 'bundler/gem_tasks'
3
+ require 'rake/clean'
4
+ CLEAN.include('pkg')
5
+
6
+ task default: :build
@@ -0,0 +1,20 @@
1
+ # -*- encoding: utf-8 -*-
2
+
3
+ $:.unshift(File.dirname(__FILE__) + '/lib')
4
+ require 'knife-mirror/version'
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = 'knife-mirror'
8
+ s.version = KnifeMirror::VERSION
9
+ s.platform = Gem::Platform::RUBY
10
+ s.summary = 'Knife support for mirroring Chef Supermarket contents'
11
+ s.description = s.summary
12
+ s.authors = ['G.J. Moed']
13
+ s.email = 'gmoed@kobo.com'
14
+ s.files = `git ls-files`.split("\n")
15
+ s.homepage = 'https://github.com/gjmoed/knife-mirror'
16
+ s.licenses = ['Apache-2.0']
17
+ # s.required_ruby_version = '>= 1.9.1'
18
+ s.add_dependency('chef', ['>= 0.10.10'])
19
+ s.require_paths = ['lib']
20
+ end
@@ -0,0 +1,195 @@
1
+ #
2
+ # Author:: G.J. Moed (<gmoed@kobo.com>)
3
+ # Copyright:: Copyright (c) 2015 Rakuten Kobo Inc.
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+ require 'chef/knife'
19
+
20
+ class Chef
21
+ class Knife
22
+ # Extending Chef Knife with our Mirror additions
23
+ class Mirror < Knife
24
+ banner 'knife mirror COOKBOOK [VERSION] (options)'
25
+ category 'mirror'
26
+
27
+ deps do
28
+ require 'chef/cookbook_site_streaming_uploader'
29
+ end
30
+
31
+ option :supermarket_site,
32
+ short: '-m SUPERMARKET_SITE',
33
+ long: '--supermarket-site SUPERMARKET_SITE',
34
+ description: '(Source) Supermarket Site',
35
+ default: 'https://supermarket.chef.io'
36
+
37
+ option :target_site,
38
+ short: '-t TARGET_SUPERMARKET_SITE',
39
+ long: '--target-site TARGET_SUPERMARKET_SITE',
40
+ description: '(Destination/target) Supermarket Site'
41
+
42
+ option :download_directory,
43
+ short: '-d DOWNLOAD_DIRECTORY',
44
+ long: '--dir DOWNLOAD_DIRECTORY',
45
+ description: 'The directory for storing (--keep) cookbooks failing to process',
46
+ default: Dir.pwd
47
+
48
+ option :delay,
49
+ long: '--delay SECONDS',
50
+ description: 'Delay in seconds between per cookbook per version processing, used to throttle downloads and uploads.'
51
+
52
+ option :keep,
53
+ long: '--keep',
54
+ description: 'Sometimes really old cookbooks do allow downloading, but fail processing on newer version supermarkets. Do you want to keep these failed cookbooks after downloading?'
55
+
56
+ option :deps,
57
+ long: '--deps',
58
+ description: 'Also process cookbook(s) dependencies. (TODO/WIP)'
59
+
60
+ option :reps,
61
+ long: '--reps',
62
+ description: 'Also process deprecated cookbook(s) replacement(s). (TODO/WIP)'
63
+
64
+ def run
65
+ $stdout.sync = true # Avoid possible buffering of some progress dots
66
+ if @name_args[0] == 'all'
67
+ # Mirror all cookbooks from SUPERMARKET_SITE to TARGET_SUPERMARKET_SITE
68
+ ui.info('Mirroring all versions for all cookbooks')
69
+ ui.info("Delaying by #{config[:delay]} seconds per version.") if config[:delay]
70
+ print "Fetching cookbook index from #{config[:supermarket_site]} (source)... "
71
+ community_universe = unauthenticated_get_rest("#{config[:supermarket_site]}/universe")
72
+ ui.info('Done!')
73
+ print "Fetching cookbook index from #{config[:target_site]} (target)... "
74
+ private_universe = unauthenticated_get_rest("#{config[:target_site]}/universe")
75
+ ui.info('Done!')
76
+ removed, added = universe_diff(private_universe, community_universe)
77
+ ui.info("We are still missing #{added.size} cookbooks (out of #{community_universe.size}) on our target Supermarket.")
78
+ ui.info("Though we're not doing anything with these just yet, you should know we have #{removed.size} cookbooks which are no longer present on the Supermarket (source).")
79
+ added.sort.each do |cookbook, versions|
80
+ ui.info("Mirroring #{versions.size} version(s) for #{cookbook} cookbook:")
81
+ displayed_before = false
82
+ versions.sort_by { |version, _versionmeta| version.split('.').map(&:to_i) }.each do |version, _versionmeta|
83
+ mirror_cookbook(cookbook, version, displayed_before)
84
+ displayed_before = true # Some things only need displaying once per cookbook and not each version (deprecation)
85
+ sleep(config[:delay].to_i) if config[:delay]
86
+ end
87
+ end
88
+ elsif @name_args[1] == 'all'
89
+ # Mirror all versions for a specific cookbook
90
+ ui.info("Mirroring all versions for #{@name_args[0]}.")
91
+ ui.info("Delaying by #{config[:delay]} seconds per version.") if config[:delay]
92
+ print "Fetching cookbook meta from #{config[:supermarket_site]} (source)... "
93
+ cookbookmeta = get_cookbook_meta
94
+ ui.info('Done!')
95
+ print "Fetching cookbook meta from #{config[:target_site]} (target)... "
96
+ target_cookbookmeta = get_cookbook_meta(@name_args[0], "#{config[:target_site]}/api/v1/cookbooks")
97
+ ui.info('Done!')
98
+ ui.info("Processing remaining #{cookbookmeta['metrics']['downloads']['versions'].size - target_cookbookmeta['metrics']['downloads']['versions'].size} cookbook versions:")
99
+ displayed_before = false
100
+ (cookbookmeta['metrics']['downloads']['versions'].keys - target_cookbookmeta['metrics']['downloads']['versions'].keys).sort_by { |version| version.split('.').map(&:to_i) }.each do |version|
101
+ mirror_cookbook(@name_args[0], version, displayed_before)
102
+ displayed_before = true # Some things only need displaying once per cookbook and not each version (deprecation)
103
+ sleep(config[:delay].to_i) if config[:delay]
104
+ end
105
+ elsif @name_args.length == 2
106
+ # Mirror just one single cookbook, specific version
107
+ ui.info("Mirroring #{@name_args[0]} (#{@name_args[1]}).")
108
+ mirror_cookbook(@name_args[0], @name_args[1])
109
+ else
110
+ # Mirror just one single cookbook, latest version
111
+ ui.info("Mirroring #{@name_args[0]} (latest version).")
112
+ mirror_cookbook
113
+ end
114
+ end
115
+
116
+ private
117
+
118
+ def mirror_cookbook(cookbook = @name_args[0], version = 'latest_version', displayed_before = false, user_id = Chef::Config[:node_name], user_secret_filename = Chef::Config[:client_key])
119
+ cookbookmeta = get_cookbook_meta(cookbook, "#{config[:supermarket_site]}/api/v1/cookbooks")
120
+ ui.warn("This cookbook has been deprecated. It has been replaced by #{File.basename(cookbookmeta['replacement'])}.") if cookbook_deprecated?(cookbookmeta) && !displayed_before
121
+ versionmeta = version == 'latest_version' ? unauthenticated_get_rest(cookbookmeta['latest_version']) : unauthenticated_get_rest("#{config[:supermarket_site]}/api/v1/cookbooks/#{cookbook}/versions/#{version.gsub('.', '_')}")
122
+ print "Processing version #{versionmeta['version']} "
123
+ temp_cookbookfile = unauthenticated_get_rest(versionmeta['file'], true)
124
+ print '.'
125
+ # Need to revisit this, currently Supermarket only support setting the catagory this way :(
126
+ # meta_hash = %w(category external_url source_url issues_url average_rating created_at up_for_adoption foodcritic_failure).map { |param| [param.to_sym, cookbookmeta[param]] }.to_h
127
+ # meta_hash.merge!('deprecated' => true, 'replacement' => "#{config[:target_site]}/api/v1/cookbooks/#{File.basename(cookbookmeta['replacement'])}") if cookbook_deprecated?(cookbookmeta)
128
+ # So for now, we just fix the category :(
129
+ meta_hash = { 'category' => '' }
130
+ begin
131
+ http_resp = Chef::CookbookSiteStreamingUploader.post("#{config[:target_site]}/api/v1/cookbooks", user_id, user_secret_filename, tarball: File.open(temp_cookbookfile.path), cookbook: meta_hash.to_json)
132
+ rescue => e
133
+ ui.error("Error uploading cookbook #{cookbook} (#{versionmeta['version']}) to the Supermarket at #{config[:target_site]}: #{e.message}. Increase log verbosity (-VV) for more information.")
134
+ Chef::Log.debug("\n#{e.backtrace.join("\n")}")
135
+ config[:keep] ? FileUtils.mv(temp_cookbookfile.path, File.join(config[:download_directory], "#{cookbook}-#{versionmeta['version']}.tar.gz")) : FileUtils.rm_rf(temp_cookbookfile.path)
136
+ exit(1) # Hard exit since this usually hints at trouble reaching the supermarket, no sense in allowing this in some loop...
137
+ end
138
+ print '.'
139
+ if http_resp.code.to_i != 201
140
+ res = Chef::JSONCompat.from_json(http_resp.body) unless http_resp.code.to_i == 500
141
+ ui.info('. Failed :(')
142
+ if http_resp.code.to_i != 500 && res['error_messages']
143
+ ui.error "#{res['error_messages'][0]}"
144
+ else
145
+ ui.error 'Unknown error while uploading cookbook'
146
+ ui.error "Server response: #{http_resp.body}"
147
+ end
148
+ config[:keep] ? FileUtils.mv(temp_cookbookfile.path, File.join(config[:download_directory], "#{cookbook}-#{versionmeta['version']}.tar.gz")) : FileUtils.rm_rf(temp_cookbookfile.path)
149
+ ui.info("Saving failed cookbook (#{File.join(config[:download_directory], "#{cookbook}-#{versionmeta['version']}.tar.gz")})") if config[:keep]
150
+ Chef::Log.debug("Removing #{temp_cookbookfile.path}") unless config[:keep]
151
+ return
152
+ end
153
+ ui.info('. Done!')
154
+ end
155
+
156
+ def unauthenticated_get_rest(url, raw = false)
157
+ noauth_rest.sign_on_redirect = false
158
+ noauth_rest.get_rest(url, raw)
159
+ end
160
+
161
+ def get_cookbook_meta(cookbook = @name_args[0], api_url = "#{config[:supermarket_site]}/api/v1/cookbooks")
162
+ unauthenticated_get_rest("#{api_url}/#{cookbook}")
163
+ end
164
+
165
+ def cookbook_deprecated?(cookbookmeta)
166
+ cookbookmeta['deprecated'] == true
167
+ end
168
+
169
+ def universe_diff(source, target)
170
+ return [nil, target.dup] if source.nil?
171
+ return [source.dup, nil] if target.nil?
172
+ if source.is_a?(Hash) && target.is_a?(Hash)
173
+ added = {}
174
+ removed = {}
175
+ source_keys = source.keys
176
+ target_keys = target.keys
177
+ (source_keys - target_keys).each { |key| removed[key] = source[key].dup }
178
+ (target_keys - source_keys).each { |key| added[key] = target[key].dup }
179
+ (source_keys & target_keys).each do |key|
180
+ nested_removed, nested_added = universe_diff(source[key], target[key])
181
+ removed[key] = nested_removed unless skip?(nested_removed)
182
+ added[key] = nested_added unless skip?(nested_added)
183
+ end
184
+ [removed, added]
185
+ elsif source != target
186
+ [source, target]
187
+ end
188
+ end
189
+
190
+ def skip?(obj)
191
+ obj.is_a?(Hash) ? (obj.empty? || %w(location_path download_url).any? { |key| obj.key?(key) }) : obj.nil?
192
+ end
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,5 @@
1
+ # KnifeMirror version
2
+ module KnifeMirror
3
+ VERSION = '0.1.0'
4
+ MAJOR, MINOR, TINY = VERSION.split('.')
5
+ end
metadata ADDED
@@ -0,0 +1,67 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: knife-mirror
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - G.J. Moed
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-09-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: chef
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 0.10.10
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 0.10.10
27
+ description: Knife support for mirroring Chef Supermarket contents
28
+ email: gmoed@kobo.com
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - ".gitignore"
34
+ - ".rubocop.yml"
35
+ - CHANGELOG.md
36
+ - Gemfile
37
+ - LICENSE
38
+ - README.md
39
+ - Rakefile
40
+ - knife-mirror.gemspec
41
+ - lib/chef/knife/mirror.rb
42
+ - lib/knife-mirror/version.rb
43
+ homepage: https://github.com/gjmoed/knife-mirror
44
+ licenses:
45
+ - Apache-2.0
46
+ metadata: {}
47
+ post_install_message:
48
+ rdoc_options: []
49
+ require_paths:
50
+ - lib
51
+ required_ruby_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '0'
56
+ required_rubygems_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ requirements: []
62
+ rubyforge_project:
63
+ rubygems_version: 2.4.5
64
+ signing_key:
65
+ specification_version: 4
66
+ summary: Knife support for mirroring Chef Supermarket contents
67
+ test_files: []