wt-knife-backup 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 17188ac6cfb0387a7d8d17b54deba43a3b2b2f3c
4
+ data.tar.gz: ceb37ae8a54e192b1f4068007c98b052a4c8a758
5
+ SHA512:
6
+ metadata.gz: 61e7b0afa10e7155bbbc0d4787bd0f029ee4907cd0f84ca112f249a6a288f945c398b1378a08b4541e69758d19b36487db7a633d80ceac7623f22639b45d82d9
7
+ data.tar.gz: 75d8bb4b69e248c27c8a8232732f27c45490e6e1d46485d9ba2e69655f1b94a2e9ffeab857e62a405ef1b9d03a03622920a4ae67c58961a88c672edf5fb25a7a
@@ -0,0 +1,6 @@
1
+ *.gem
2
+ .bundle
3
+ .chef
4
+ Gemfile.lock
5
+ pkg/*
6
+ bin/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in knife-backup.gemspec
4
+ 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 2012 Fletcher Nichol
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.
@@ -0,0 +1,98 @@
1
+ Knife-Backup
2
+ ===
3
+
4
+ [![Join the chat at https://gitter.im/mdxp/knife-backup](https://badges.gitter.im/mdxp/knife-backup.svg)](https://gitter.im/mdxp/knife-backup?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
5
+
6
+ Knife-Backup is a [Knife](http://wiki.opscode.com/display/chef/Knife) plugin that can help you backup and restore a chef server. It is based on the great work of [Steven Danna][stevendanna] and [Joshua Timberman][jtimberman] on the [BackupExport][backup_export] and [BackupRestore][backup_restore] plugins. Currently knife-backup has support for the following objects:
7
+
8
+ * clients
9
+ * users (chef 11 - Open Source)
10
+ * nodes
11
+ * roles
12
+ * environments
13
+ * data bags
14
+ * cookbooks and all their versions.
15
+
16
+ knife-backup will backup all cookbook versions available on the chef server. Cookbooks are normally available in a repository and should be easy to upload like that, but if you are using various cookbook versions in each environment then it might not be so trivial to find and upload them back to the server; downloading them and having them available to upload like that is simple and clean. If you have too many cookbook [versions](http://www.ducea.com/2013/02/26/knife-cleanup/) then you might want to cleanup them first using something like [knife-cleanup][knifecleanup]
17
+
18
+ Users are a bit tricky, knife-backup can't gather the crypted passwords via the chef server so it's forced to reset them to a random string on restore. Be sure to copy them from the restore output or reset them.
19
+
20
+ *Known limitation*: currently it is not possible to overwrite a client object already available on the target server and these will be skipped.
21
+
22
+ ## Installation
23
+
24
+ You will need chef installed and a working knife config; it should work with chef versions newer than 0.10.10
25
+
26
+ ```bash
27
+ gem install knife-backup
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ Currently the available commands are:
33
+
34
+ ```bash
35
+ knife backup export [component component ...] [-D DIR] [options]
36
+ knife backup restore [component component ...] [-D DIR]
37
+
38
+ #Example:
39
+ knife backup export cookbooks roles environments -D ~/my_chef_backup
40
+ ```
41
+ #### Optional Switches for export
42
+
43
+ - `-N`, `--latest` only download the latest version of a cookbook
44
+ - `-I`, `--ignore-permissions` ignore any permission errors during export
45
+
46
+ #### Optional Switches for restore
47
+
48
+ - `-I`, `--ignore-metadata-errors` Ignore json metadata errors when restoring cookbooks
49
+
50
+
51
+ For more information on commands:
52
+
53
+ ```bash
54
+ knife backup SUB-COMMAND --help
55
+ ```
56
+
57
+ Note: you should treat this as beta software; I'm using it with success for my needs and hopefully you will find it useful too.
58
+
59
+ ## Todo/Ideas
60
+
61
+ * Timestamp for the backup folder
62
+ * Track the failed downloads and report them at the end
63
+ * Find out if there is a way to overwrite a client object.
64
+
65
+ ## Development
66
+
67
+ * Source hosted at [GitHub][repo]
68
+ * Report issues/questions/feature requests on [GitHub Issues][issues]
69
+
70
+ Pull requests are very welcome! Ideally create a topic branch for every separate change you make. For example:
71
+
72
+ 1. Fork the repo
73
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
74
+ 3. Commit your changes (`git commit -am 'Added some feature'`)
75
+ 4. Push to the branch (`git push origin my-new-feature`)
76
+ 5. Create new Pull Request
77
+
78
+ ## Authors
79
+
80
+ Created and maintained by [Marius Ducea][mdxp] (<marius.ducea@gmail.com>)
81
+
82
+ Based on the original plugins by [Steven Danna][stevendanna] and [Joshua Timberman][jtimberman]
83
+
84
+ ## License
85
+
86
+ Apache License, Version 2.0 (see [LICENSE][license])
87
+
88
+ [license]: https://github.com/mdxp/knife-backup/blob/master/LICENSE
89
+ [mdxp]: https://github.com/mdxp
90
+ [repo]: https://github.com/mdxp/knife-backup
91
+ [issues]: https://github.com/mdxp/knife-backup/issues
92
+ [knifecleanup]: https://github.com/mdxp/knife-cleanup
93
+ [chefjenkins]: https://github.com/mdxp/chef-jenkins
94
+
95
+ [backup_export]: https://github.com/stevendanna/knife-hacks/blob/master/plugins/backup_export.rb
96
+ [backup_restore]: https://github.com/stevendanna/knife-hacks/blob/master/plugins/backup_restore.rb
97
+ [jtimberman]: https://github.com/jtimberman
98
+ [stevendanna]: https://github.com/stevendanna
@@ -0,0 +1,3 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ task :default => :build
@@ -0,0 +1,191 @@
1
+ #
2
+ # Author:: Marius Ducea (<marius.ducea@gmail.com>)
3
+ # Author:: Steven Danna (steve@opscode.com)
4
+ # Author:: Joshua Timberman (<joshua@opscode.com>)
5
+ # Author:: Adam Jacob (<adam@opscode.com>)
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ #
19
+
20
+ require 'chef/node'
21
+ require 'chef/api_client'
22
+
23
+ if Chef::VERSION =~ /^11\./
24
+ require 'chef/user'
25
+ end
26
+ require 'chef/knife/cookbook_download'
27
+
28
+ module ServerBackup
29
+ class BackupExport < Chef::Knife
30
+
31
+ deps do
32
+ require 'fileutils'
33
+ require 'chef/cookbook_loader'
34
+ end
35
+
36
+ banner "knife backup export [COMPONENT [COMPONENT ...]] [-D DIR] (options)"
37
+
38
+ option :backup_dir,
39
+ :short => "-D DIR",
40
+ :long => "--backup-directory DIR",
41
+ :description => "Store backup data in DIR. DIR will be created if it does not already exist.",
42
+ :default => Chef::Config[:knife][:chef_server_backup_dir] ? Chef::Config[:knife][:chef_server_backup_dir] : File.join(".chef", "chef_server_backup")
43
+
44
+ option :latest,
45
+ :short => "-N",
46
+ :long => "--latest",
47
+ :description => "The version of the cookbook to download",
48
+ :boolean => true
49
+
50
+ option :ignore_perm,
51
+ :short => "-I",
52
+ :long => "--ignore-permissions",
53
+ :description => "Continue in case a permission problem occurs",
54
+ :boolean => true
55
+
56
+ def run
57
+ validate!
58
+ components = name_args.empty? ? COMPONENTS : name_args
59
+ Array(components).each { |component| self.send(component) }
60
+ end
61
+
62
+ private
63
+ COMPONENTS = %w(clients users nodes roles data_bags environments cookbooks)
64
+ LOAD_TRIES = 5
65
+
66
+ def validate!
67
+ bad_names = name_args - COMPONENTS
68
+ unless bad_names.empty?
69
+ ui.error "Component types #{bad_names.join(",")} are not valid."
70
+ exit 1
71
+ end
72
+ end
73
+
74
+ def nodes
75
+ component = "nodes"
76
+ ui.msg "Backing up #{component}"
77
+ dir = File.join(config[:backup_dir], component)
78
+ FileUtils.mkdir_p(dir)
79
+ Chef::Node.list.each do |component_name, url|
80
+ next if component == "environments" && component_name == "_default"
81
+ ui.msg "Backing up #{component} #{component_name}"
82
+ component_obj = Chef::Node.load(component_name).for_json
83
+ unless component_obj
84
+ ui.error "Could not load #{klass} #{component_name}."
85
+ next
86
+ end
87
+ File.open(File.join(dir, "#{component_name}.json"), "w") do |component_file|
88
+ component_file.print(JSON.pretty_generate(component_obj))
89
+ end
90
+ end
91
+ end
92
+
93
+ def clients
94
+ backup_standard("clients", Chef::ApiClient)
95
+ end
96
+
97
+ def users
98
+ if Chef::VERSION =~ /^1[1]\./
99
+ backup_standard("users", Chef::User)
100
+ else
101
+ ui.warn "users export only supported on chef == 11"
102
+ end
103
+ end
104
+
105
+ def roles
106
+ backup_standard("roles", Chef::Role)
107
+ end
108
+
109
+ def environments
110
+ backup_standard("environments", Chef::Environment)
111
+ end
112
+
113
+ def data_bags
114
+ ui.msg "Backing up data bags"
115
+ dir = File.join(config[:backup_dir], "data_bags")
116
+ FileUtils.mkdir_p(dir)
117
+ Chef::DataBag.list.each do |bag_name, url|
118
+ FileUtils.mkdir_p(File.join(dir, bag_name))
119
+ Chef::DataBag.load(bag_name).each do |item_name, url|
120
+ ui.msg "Backing up data bag #{bag_name} item #{item_name}"
121
+ item = Chef::DataBagItem.load(bag_name, item_name)
122
+ File.open(File.join(dir, bag_name, "#{item_name}.json"), "w") do |dbag_file|
123
+ dbag_file.print(JSON.pretty_generate(item.raw_data))
124
+ end
125
+ end
126
+ end
127
+ end
128
+
129
+ def backup_standard(component, klass)
130
+ ui.msg "Backing up #{component}"
131
+ dir = File.join(config[:backup_dir], component)
132
+ FileUtils.mkdir_p(dir)
133
+ klass.list.each do |component_name, url|
134
+ next if component == "environments" && component_name == "_default"
135
+ ui.msg "Backing up #{component} #{component_name}"
136
+ component_obj = load_object(klass, component_name).to_hash
137
+ unless component_obj
138
+ ui.error "Could not load #{klass} #{component_name}."
139
+ next
140
+ end
141
+ File.open(File.join(dir, "#{component_name}.json"), "w") do |component_file|
142
+ component_file.print(JSON.pretty_generate(component_obj))
143
+ end
144
+ end
145
+ end
146
+
147
+ def load_object(klass, name, try = 1)
148
+ klass.load(name)
149
+ rescue NoMethodError
150
+ ui.warn "Problem loading #{klass} #{name}. Try #{try}/#{LOAD_TRIES}"
151
+ if try < LOAD_TRIES
152
+ try += 1
153
+ load_object(klass, name, try)
154
+ end
155
+ rescue Net::HTTPServerException => e
156
+ if config[:ignore_perm]
157
+ ui.warn "Problem loading #{name} #{e.message}."
158
+ ui.warn "Possibly an issue with permissions on the chef server... Skipping"
159
+ else
160
+ raise
161
+ end
162
+ end
163
+
164
+ def cookbooks
165
+ ui.msg "Backing up cookbooks"
166
+ dir = File.join(config[:backup_dir], "cookbooks")
167
+ FileUtils.mkdir_p(dir)
168
+ if config[:latest]
169
+ cookbooks = rest.get_rest("/cookbooks?latest")
170
+ else
171
+ cookbooks = rest.get_rest("/cookbooks?num_versions=all")
172
+ end
173
+ cookbooks.keys.each do |cb|
174
+ ui.msg "Backing up cookbook #{cb}"
175
+ dld = Chef::Knife::CookbookDownload.new
176
+ cookbooks[cb]['versions'].each do |ver|
177
+ dld.name_args = [cb, ver['version']]
178
+ dld.config[:download_directory] = dir
179
+ dld.config[:force] = true
180
+ begin
181
+ dld.run
182
+ rescue
183
+ ui.msg "Failed to download cookbook #{cb} version #{ver['version']}... Skipping"
184
+ FileUtils.rm_r(File.join(dir, cb + "-" + ver['version']))
185
+ end
186
+ end
187
+ end
188
+ end
189
+
190
+ end
191
+ end
@@ -0,0 +1,231 @@
1
+ #
2
+ # Author:: Marius Ducea (<marius.ducea@gmail.com>)
3
+ # Author:: Steven Danna (steve@opscode.com)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+
18
+ class Chef
19
+ class Knife
20
+ class CookbookUpload < Knife
21
+ def check_for_dependencies!(cookbook)
22
+ end
23
+ end
24
+ end
25
+ end
26
+
27
+
28
+ module ServerBackup
29
+ class BackupRestore < Chef::Knife
30
+
31
+ deps do
32
+ require 'chef/knife/core/object_loader'
33
+ require 'chef/cookbook_uploader'
34
+ require 'chef/api_client'
35
+ require 'securerandom'
36
+ require 'json'
37
+ end
38
+
39
+ banner "knife backup restore [COMPONENT [COMPONENT ...]] [-D DIR] (options)"
40
+
41
+ option :backup_dir,
42
+ :short => "-D DIR",
43
+ :long => "--backup-directory DIR",
44
+ :description => "Restore backup data from DIR.",
45
+ :default => Chef::Config[:knife][:chef_server_backup_dir] ? Chef::Config[:knife][:chef_server_backup_dir] : File.join(".chef", "chef_server_backup")
46
+
47
+ option :ignore_metadata_errors,
48
+ :short => "-I",
49
+ :long => "--ignore-metadata-errors",
50
+ :description => "Ignore json metadata errors when restoring cookbooks",
51
+ :boolean => true,
52
+ :default => Chef::Config[:knife][:ignore_metadata_errors] ? Chef::Config[:knife][:ignore_metadata_errors] : false
53
+
54
+ def run
55
+ ui.warn "This will overwrite existing data!"
56
+ ui.warn "Backup is at least 1 day old" if (Time.now - File.atime(config[:backup_dir])) > 86400
57
+ ui.confirm "Do you want to restore backup, possibly overwriting existing data"
58
+ validate!
59
+ components = name_args.empty? ? COMPONENTS : name_args
60
+ Array(components).each { |component| self.send(component) }
61
+ end
62
+
63
+ private
64
+ COMPONENTS = %w(clients users nodes roles data_bags environments cookbooks)
65
+
66
+ def validate!
67
+ bad_names = name_args - COMPONENTS
68
+ unless bad_names.empty?
69
+ ui.error "Component types #{bad_names.join(",")} are not valid."
70
+ exit 1
71
+ end
72
+ end
73
+
74
+ def nodes
75
+ restore_standard("nodes", Chef::Node)
76
+ end
77
+
78
+ def roles
79
+ restore_standard("roles", Chef::Role)
80
+ end
81
+
82
+ def environments
83
+ restore_standard("environments", Chef::Environment)
84
+ end
85
+
86
+ def data_bags
87
+ ui.info "=== Restoring data bags ==="
88
+ loader = Chef::Knife::Core::ObjectLoader.new(Chef::DataBagItem, ui)
89
+ dbags = Dir.glob(File.join(config[:backup_dir], "data_bags", '*'))
90
+ dbags.each do |bag|
91
+ bag_name = File.basename(bag)
92
+ ui.info "Restoring data_bag[#{bag_name}]"
93
+ begin
94
+ rest.post_rest("data", { "name" => bag_name})
95
+ rescue Net::HTTPServerException => e
96
+ handle_error 'data_bag', bag_name, e
97
+ end
98
+ dbag_items = Dir.glob(File.join(bag, "*"))
99
+ dbag_items.each do |item_path|
100
+ item_name = File.basename(item_path, '.json')
101
+ ui.info "Restoring data_bag_item[#{bag_name}::#{item_name}]"
102
+ item = loader.load_from("data_bags", bag_name, item_path)
103
+ dbag = Chef::DataBagItem.new
104
+ dbag.data_bag(bag_name)
105
+ dbag.raw_data = item
106
+ dbag.save
107
+ end
108
+ end
109
+
110
+ end
111
+
112
+ def restore_standard(component, klass)
113
+ loader = Chef::Knife::Core::ObjectLoader.new(klass, ui)
114
+ ui.info "=== Restoring #{component} ==="
115
+ files = Dir.glob(File.join(config[:backup_dir], component, "*.json"))
116
+ files.each do |f|
117
+ ui.info "Restoring #{component} from #{f}"
118
+ updated = loader.load_from(component, f)
119
+ updated.save
120
+ end
121
+ end
122
+
123
+ def clients
124
+ JSON.create_id = "no_thanks"
125
+ ui.info "=== Restoring clients ==="
126
+ clients = Dir.glob(File.join(config[:backup_dir], "clients", "*.json"))
127
+ clients.each do |file|
128
+ ui.info "Restoring clients from #{file}"
129
+ client = JSON.parse(IO.read(file))
130
+ begin
131
+ rest.post_rest("clients", {
132
+ :name => client['name'],
133
+ :public_key => client['public_key'],
134
+ :admin => client['admin'],
135
+ :validator => client['validator']
136
+ })
137
+ rescue Net::HTTPServerException => e
138
+ handle_error 'client', client['name'], e
139
+ end
140
+ end
141
+ end
142
+
143
+ def users
144
+ JSON.create_id = "no_thanks"
145
+ ui.info "=== Restoring users ==="
146
+ users = Dir.glob(File.join(config[:backup_dir], "users", "*.json"))
147
+ if !users.empty? and Chef::VERSION !~ /^11\./
148
+ ui.warn "users restore only supported on chef == 11"
149
+ return
150
+ end
151
+ users.each do |file|
152
+ user = JSON.parse(IO.read(file))
153
+ password = SecureRandom.hex[0..7]
154
+ begin
155
+ rest.post_rest("users", {
156
+ :name => user['name'],
157
+ :public_key => user['public_key'],
158
+ :admin => user['admin'],
159
+ :password => password
160
+ })
161
+ ui.info "Set password for #{user['name']} to #{password}, please update"
162
+ rescue Net::HTTPServerException => e
163
+ handle_error 'user', user['name'], e
164
+ end
165
+ end
166
+ end
167
+
168
+ def cookbooks
169
+ count = 0
170
+ ui.info "=== Restoring cookbooks ==="
171
+ cookbooks = Dir.glob(File.join(config[:backup_dir], "cookbooks", '*'))
172
+ #Make tmp dir
173
+ FileUtils.rm_rf(config[:backup_dir] + "/tmp")
174
+ Dir.mkdir config[:backup_dir] + "/tmp"
175
+ cookbooks.each do |cb|
176
+ full_cb = File.expand_path(cb)
177
+ cb_name = File.basename(cb)
178
+ cookbook = cb_name.reverse.split('-',2).last.reverse
179
+ full_path = File.join(config[:backup_dir] + "/tmp", cookbook)
180
+ begin
181
+ count += 1
182
+ if Chef::Platform.windows?
183
+ Dir.mkdir config[:backup_dir] + "/tmp/#{cb_name}"
184
+ full_path = File.join(config[:backup_dir] + "/tmp/#{cb_name}", cookbook)
185
+ ui.info "Copy cookbook #{full_cb} to #{full_path}"
186
+ FileUtils.copy_entry(full_cb, full_path)
187
+ else
188
+ full_path = File.join(config[:backup_dir] + "/tmp", cookbook)
189
+ File.symlink(full_cb, full_path)
190
+ end
191
+ cbu = Chef::Knife::CookbookUpload.new
192
+ Chef::Knife::CookbookUpload.load_deps
193
+ cbu.name_args = [ cookbook ]
194
+ cbu.config[:cookbook_path] = File.dirname(full_path)
195
+ ui.info "Restoring cookbook #{cbu.name_args}"
196
+ cbu.run
197
+ rescue Net::HTTPServerException => e
198
+ handle_error 'cookbook', cb_name, e
199
+ rescue Chef::Exceptions::JSON::ParseError => e
200
+ handle_error 'cookbook', cb_name, e
201
+ throw e unless config[:ignore_metadata_errors]
202
+ ensure
203
+ if Chef::Platform.windows?
204
+ rm_path = config[:backup_dir] + "/tmp/#{cb_name}"
205
+ ui.info "remove dir #{rm_path}"
206
+ FileUtils.remove_dir(rm_path, force = true)
207
+ else
208
+ File.unlink(full_path)
209
+ end
210
+ end
211
+ end
212
+ ui.info "Uploaded #{count} Cookbooks"
213
+ FileUtils.rm_rf(config[:backup_dir] + "/tmp")
214
+ end
215
+
216
+ def handle_error(type, name, error)
217
+ thing = "#{type}[#{name}]"
218
+ return ui.error "Error parsing JSON for: #{thing}" if error.kind_of?(Chef::Exceptions::JSON::ParseError)
219
+
220
+ case error.response
221
+ when Net::HTTPConflict # 409
222
+ ui.warn "#{thing} already exists; skipping"
223
+ when Net::HTTPClientError # 4xx Catch All
224
+ ui.error "Failed to create #{thing}: #{error.response}; skipping"
225
+ else
226
+ ui.error "Failed to create #{thing}: #{error.response}; skipping"
227
+ end
228
+ end
229
+
230
+ end
231
+ end
@@ -0,0 +1 @@
1
+ require "knife-backup/version"
@@ -0,0 +1,5 @@
1
+ module Knife
2
+ module Backup
3
+ VERSION = "0.0.1"
4
+ end
5
+ end
@@ -0,0 +1,24 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "knife-backup/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "wt-knife-backup"
7
+ s.version = Knife::Backup::VERSION
8
+ s.authors = ["Marius Ducea", "Jon Rowett"]
9
+ s.email = ["marius.ducea@gmail.com", "jon@jonrowett.com"]
10
+ s.homepage = "https://github.com/mdxp/knife-backup"
11
+ s.summary = %q{Worktribe fork of Chef knife plugins to help backup and restore chef servers}
12
+ s.description = s.summary
13
+ s.license = "Apache 2.0"
14
+
15
+ #s.rubyforge_project = "knife-backup"
16
+
17
+ s.files = `git ls-files`.split("\n")
18
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
19
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
20
+ s.require_paths = ["lib"]
21
+
22
+ s.add_dependency "chef", ">= 0.10.10"
23
+
24
+ end
metadata ADDED
@@ -0,0 +1,71 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: wt-knife-backup
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Marius Ducea
8
+ - Jon Rowett
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2017-07-13 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: chef
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - '>='
19
+ - !ruby/object:Gem::Version
20
+ version: 0.10.10
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - '>='
26
+ - !ruby/object:Gem::Version
27
+ version: 0.10.10
28
+ description: Worktribe fork of Chef knife plugins to help backup and restore chef
29
+ servers
30
+ email:
31
+ - marius.ducea@gmail.com
32
+ - jon@jonrowett.com
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - .gitignore
38
+ - Gemfile
39
+ - LICENSE
40
+ - README.md
41
+ - Rakefile
42
+ - lib/chef/knife/backup_export.rb
43
+ - lib/chef/knife/backup_restore.rb
44
+ - lib/knife-backup.rb
45
+ - lib/knife-backup/version.rb
46
+ - wt-knife-backup.gemspec
47
+ homepage: https://github.com/mdxp/knife-backup
48
+ licenses:
49
+ - Apache 2.0
50
+ metadata: {}
51
+ post_install_message:
52
+ rdoc_options: []
53
+ require_paths:
54
+ - lib
55
+ required_ruby_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - '>='
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ required_rubygems_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - '>='
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
65
+ requirements: []
66
+ rubyforge_project:
67
+ rubygems_version: 2.4.8
68
+ signing_key:
69
+ specification_version: 4
70
+ summary: Worktribe fork of Chef knife plugins to help backup and restore chef servers
71
+ test_files: []