chef-deploy 0.2.5

Sign up to get free protection for your applications and to get access to all the features.
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.
@@ -0,0 +1,62 @@
1
+ == chef-deploy
2
+
3
+ A gem that provides resources and providers for deploying ruby web apps from chef recipes
4
+
5
+
6
+ Uses the same directory layout as capistrano and steals the git remote cached deploy strategy
7
+ from cap and adapts it to work without cap and under chef. Not all options are required but they
8
+ are all shown here as an example.
9
+
10
+ require 'chef-deploy'
11
+
12
+ deploy "/data/myrackapp" do
13
+ repo "git://github.com/engineyard/rack-app.git"
14
+ branch "HEAD"
15
+ user "ez"
16
+ role "app_master"
17
+ enable_submodules true
18
+ migrate true
19
+ migration_command "rake db:migrate"
20
+ environment "production"
21
+ shallow_clone true
22
+ revision '0xbeadbeef'
23
+ restart_command "touch tmp/restart.txt" # "monit restart all -g foo", etc.
24
+ action :deploy # or :rollback
25
+ end
26
+
27
+
28
+ Chef-deploy is backwards compatible with capistrano in the fact that it uses the same exact filesystem layout.
29
+ You can deploy with cap on top of a chef-deploy system and visca-versca(sic?).
30
+
31
+ Chef-deploy hooks:
32
+
33
+ If you create a APP_ROOT/deploy directory in your app you can place named hook files in there that will be triggered
34
+ at the appropriate times during the deploy. the hooks are defined as follows:
35
+
36
+ APP_ROOT/
37
+ deploy/
38
+ before_migrate.rb
39
+ before_symlink.rb
40
+ before_restart.rb
41
+ after_restart.rb
42
+
43
+ These scripts will be instance_eval'd in the context of the chef-deploy resource. This means that you will have certain commands and variables available to you in these hooks. For example:
44
+
45
+ run "echo 'release_path: #{release_path}' >> #{shared_path}/logs.log"
46
+ run "echo 'current_path: #{current_path}' >> #{shared_path}/logs.log"
47
+ run "echo 'shared_path: #{shared_path}' >> #{shared_path}/logs.log"
48
+ sudo "echo 'sudo works' >> /root/sudo.log"
49
+
50
+
51
+ You have access to a run command and a sudo command. Both of these will run shell commands, run will run as your normal unix user that the app is deployed as and sudo will run as root for when you need more permissions.
52
+
53
+ You will have variables like in capistrano:
54
+
55
+ release_path: this is the full path to the current release: /data/appname/releases/12345678
56
+ shared_path: this is the path to the shared dir: /data/appname/shared
57
+ current_path: this is the path to the currently symlinked release: /data/appname/current
58
+ node: node is the full chef node object, this will have all of the JSON collected by ohai as well as any custom json you passed into your client run. THis way you can get at *any* data you have available to any of your chef recipes.
59
+
60
+ Using subversion:
61
+
62
+ In your deploy block, simply add: scm 'subversion' (as well as svn_username and svn_password, if needed). Obviously, git-specific options like enable_submodules can be removed as they're not applicable.
@@ -0,0 +1,57 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+ require 'rubygems/specification'
4
+ require 'date'
5
+ require 'spec/rake/spectask'
6
+
7
+ GEM = "chef-deploy"
8
+ GEM_VERSION = "0.2.5"
9
+ AUTHOR = "Ezra Zygmuntowicz"
10
+ EMAIL = "Your Email"
11
+ HOMEPAGE = "http://example.com"
12
+ SUMMARY = "A gem that provides..."
13
+
14
+ spec = Gem::Specification.new do |s|
15
+ s.name = GEM
16
+ s.version = GEM_VERSION
17
+ s.platform = Gem::Platform::RUBY
18
+ s.has_rdoc = true
19
+ s.extra_rdoc_files = ["README.rdoc", "LICENSE", 'TODO']
20
+ s.summary = SUMMARY
21
+ s.description = s.summary
22
+ s.author = AUTHOR
23
+ s.email = EMAIL
24
+ s.homepage = HOMEPAGE
25
+
26
+ # Uncomment this to add a dependency
27
+ # s.add_dependency "foo"
28
+
29
+ s.require_path = 'lib'
30
+ s.autorequire = GEM
31
+ s.files = %w(LICENSE README.rdoc Rakefile TODO) + Dir.glob("{lib,spec}/**/*")
32
+ end
33
+
34
+ task :default => :spec
35
+
36
+ desc "Run specs"
37
+ Spec::Rake::SpecTask.new do |t|
38
+ t.spec_files = FileList['spec/**/*_spec.rb']
39
+ t.spec_opts = %w(-fs --color)
40
+ end
41
+
42
+
43
+ Rake::GemPackageTask.new(spec) do |pkg|
44
+ pkg.gem_spec = spec
45
+ end
46
+
47
+ desc "install the gem locally"
48
+ task :install => [:package] do
49
+ sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
50
+ end
51
+
52
+ desc "create a gemspec file"
53
+ task :make_spec do
54
+ File.open("#{GEM}.gemspec", "w") do |file|
55
+ file.puts spec.to_ruby
56
+ end
57
+ end
data/TODO ADDED
@@ -0,0 +1,4 @@
1
+ TODO:
2
+ Fix LICENSE with your name
3
+ Fix Rakefile with your name and contact info
4
+ Add your code to lib/<%= name %>.rb
@@ -0,0 +1,234 @@
1
+ require File.join(File.dirname(__FILE__), 'chef-deploy/subversion')
2
+ require File.join(File.dirname(__FILE__), 'chef-deploy/git')
3
+ require File.join(File.dirname(__FILE__), 'chef-deploy/cached_deploy')
4
+
5
+ # deploy "/data/#{app}" do
6
+ # repo "git://github.com/engineyard/rack-app.git"
7
+ # branch "HEAD"
8
+ # user "ez"
9
+ # enable_submodules true
10
+ # migrate true
11
+ # migration_command "rake db:migrate"
12
+ # environment "production"
13
+ # shallow_clone true
14
+ # action :deploy # or :rollback
15
+ # restart_command "touch tmp/restart.txt"
16
+ # end
17
+
18
+ class Chef
19
+ class Resource
20
+ class Deploy < Chef::Resource
21
+
22
+ def initialize(name, collection=nil, node=nil)
23
+ super(name, collection, node)
24
+ @resource_name = :deploy
25
+ @deploy_to = name
26
+ @branch = 'HEAD'
27
+ @repository_cache = 'cached-copy'
28
+ @copy_exclude = []
29
+ @revision = nil
30
+ @action = :deploy
31
+ @allowed_actions.push(:deploy)
32
+ @allowed_actions.push(:rollback)
33
+ end
34
+
35
+ def repo(arg=nil)
36
+ set_or_return(
37
+ :repo,
38
+ arg,
39
+ :kind_of => [ String ]
40
+ )
41
+ end
42
+
43
+
44
+ def role(arg=nil)
45
+ set_or_return(
46
+ :role,
47
+ arg,
48
+ :kind_of => [ String ]
49
+ )
50
+ end
51
+
52
+ def restart_command(arg=nil)
53
+ set_or_return(
54
+ :restart_command,
55
+ arg,
56
+ :kind_of => [ String ]
57
+ )
58
+ end
59
+
60
+ def migrate(arg=nil)
61
+ set_or_return(
62
+ :migrate,
63
+ arg,
64
+ :kind_of => [ TrueClass, FalseClass ]
65
+ )
66
+ end
67
+
68
+ def migration_command(arg=nil)
69
+ set_or_return(
70
+ :migration_command,
71
+ arg,
72
+ :kind_of => [ String ]
73
+ )
74
+ end
75
+
76
+ def user(arg=nil)
77
+ set_or_return(
78
+ :user,
79
+ arg,
80
+ :kind_of => [ String ]
81
+ )
82
+ end
83
+
84
+ def group(arg=nil)
85
+ set_or_return(
86
+ :group,
87
+ arg,
88
+ :kind_of => [ String ]
89
+ )
90
+ end
91
+
92
+ def enable_submodules(arg=nil)
93
+ set_or_return(
94
+ :enable_submodules,
95
+ arg,
96
+ :kind_of => [ TrueClass, FalseClass ]
97
+ )
98
+ end
99
+
100
+ def shallow_clone(arg=false)
101
+ set_or_return(
102
+ :shallow_clone,
103
+ arg,
104
+ :kind_of => [ TrueClass, FalseClass ]
105
+ )
106
+ end
107
+
108
+ def repository_cache(arg=nil)
109
+ set_or_return(
110
+ :repository_cache,
111
+ arg,
112
+ :kind_of => [ String ]
113
+ )
114
+ end
115
+
116
+ def copy_exclude(arg=nil)
117
+ set_or_return(
118
+ :copy_exclude,
119
+ arg,
120
+ :kind_of => [ String ]
121
+ )
122
+ end
123
+
124
+ def revision(arg=nil)
125
+ set_or_return(
126
+ :revision,
127
+ arg,
128
+ :kind_of => [ String ]
129
+ )
130
+ end
131
+
132
+ def branch(arg=nil)
133
+ set_or_return(
134
+ :branch,
135
+ arg,
136
+ :kind_of => [ String ]
137
+ )
138
+ end
139
+
140
+ def environment(arg=nil)
141
+ set_or_return(
142
+ :environment,
143
+ arg,
144
+ :kind_of => [ String ]
145
+ )
146
+ end
147
+
148
+ def git_ssh_wrapper(arg=nil)
149
+ set_or_return(
150
+ :git_ssh_wrapper,
151
+ arg,
152
+ :kind_of => [ String ]
153
+ )
154
+ end
155
+
156
+ def scm(arg=nil)
157
+ set_or_return(
158
+ :scm,
159
+ arg,
160
+ :kind_of => [ String ]
161
+ )
162
+ end
163
+
164
+ def svn_username(arg=nil)
165
+ set_or_return(
166
+ :svn_username,
167
+ arg,
168
+ :kind_of => [ String ]
169
+ )
170
+ end
171
+
172
+ def svn_password(arg=nil)
173
+ set_or_return(
174
+ :svn_password,
175
+ arg,
176
+ :kind_of => [ String ]
177
+ )
178
+ end
179
+
180
+ end
181
+ end
182
+
183
+ class Provider
184
+ class Deploy < Chef::Provider
185
+
186
+ def load_current_resource
187
+ FileUtils.mkdir_p "#{@new_resource.name}/shared"
188
+ FileUtils.mkdir_p "#{@new_resource.name}/releases"
189
+ @dep = CachedDeploy.new :user => @new_resource.user,
190
+ :group => @new_resource.group,
191
+ :role => @new_resource.role,
192
+ :branch => (@new_resource.branch || 'HEAD'),
193
+ :restart_command => (@new_resource.restart_command || ""),
194
+ :repository => @new_resource.repo,
195
+ :environment => @new_resource.environment,
196
+ :migration_command => @new_resource.migration_command,
197
+ :migrate => @new_resource.migrate,
198
+ :deploy_to => @new_resource.name,
199
+ :repository_cache => @new_resource.repository_cache,
200
+ :copy_exclude => @new_resource.copy_exclude,
201
+ :revision => (@new_resource.revision || ''),
202
+ :git_enable_submodules => @new_resource.enable_submodules,
203
+ :git_shallow_clone => @new_resource.shallow_clone,
204
+ :svn_username => @new_resource.svn_username,
205
+ :svn_password => @new_resource.svn_password,
206
+ :scm => @new_resource.scm || 'git',
207
+ :node => @node,
208
+ :new_resource => @new_resource,
209
+ :git_ssh_wrapper => @git_ssh_wrapper
210
+ end
211
+
212
+ def action_deploy
213
+ Dir.chdir(@new_resource.name) do
214
+ Chef::Log.level(:debug)
215
+ Chef::Log.info "Running a new deploy\nto: #{@new_resource.name}\nrepo: #{@new_resource.repo}"
216
+ @dep.deploy
217
+ Chef::Log.level(Chef::Config[:log_level])
218
+ end
219
+ end
220
+
221
+ def action_rollback
222
+ Dir.chdir(@new_resource.name) do
223
+ Chef::Log.level(:debug)
224
+ Chef::Log.info "Rolling back deploy\nto: #{@new_resource.name}\nrepo: #{@new_resource.repo}"
225
+ @dep.rollback
226
+ Chef::Log.level(Chef::Config[:log_level])
227
+ end
228
+ end
229
+
230
+ end
231
+ end
232
+ end
233
+
234
+ Chef::Platform.platforms[:default].merge! :deploy => Chef::Provider::Deploy, :gem_package => Chef::Provider::Package::Rubygems
@@ -0,0 +1,277 @@
1
+ # stolen wholesale from capistrano, thanks Jamis!
2
+ require 'yaml'
3
+ class ChefDeployFailure < StandardError
4
+ end
5
+
6
+ class CachedDeploy
7
+ # Executes the SCM command for this strategy and writes the REVISION
8
+ # mark file to each host.
9
+ def deploy
10
+ @configuration[:release_path] = "#{@configuration[:deploy_to]}/releases/#{Time.now.utc.strftime("%Y%m%d%H%M%S")}"
11
+ if @configuration[:revision] == ''
12
+ @configuration[:revision] = source.query_revision(@configuration[:branch]) {|cmd| run_with_result "#{cmd}"}
13
+ end
14
+
15
+ Chef::Log.info "ensuring proper ownership"
16
+ chef_run("chown -R #{user}:#{group} #{@configuration[:deploy_to]}")
17
+
18
+ Chef::Log.info "deploying branch: #{@configuration[:branch]} rev: #{@configuration[:revision]}"
19
+ Chef::Log.info "updating the cached checkout"
20
+ chef_run(update_repository_cache)
21
+ Chef::Log.info "copying the cached version to #{release_path}"
22
+ chef_run(copy_repository_cache)
23
+ install_gems
24
+
25
+ chef_run("chown -R #{user}:#{group} #{@configuration[:deploy_to]}")
26
+
27
+ callback(:before_migrate)
28
+ migrate
29
+ callback(:before_symlink)
30
+ symlink
31
+ callback(:before_restart)
32
+ restart
33
+ callback(:after_restart)
34
+ cleanup
35
+ end
36
+
37
+ def restart
38
+ unless @configuration[:restart_command].empty?
39
+ Chef::Log.info "restarting app: #{latest_release}"
40
+ chef_run("cd #{current_path} && sudo -u #{user} INLINEDIR=/tmp RAILS_ENV=#{@configuration[:environment]} RACK_ENV=#{@configuration[:environment]} MERB_ENV=#{@configuration[:environment]} #{@configuration[:restart_command]}")
41
+ end
42
+ end
43
+
44
+ def check_current_revision_and_noop_if_same(newrev)
45
+ IO.read("#{latest_release}/REVISION").chomp == newrev
46
+ rescue
47
+ false
48
+ end
49
+
50
+ # before_symlink
51
+ # before_restart
52
+ def callback(what)
53
+ if File.exist?("#{latest_release}/deploy/#{what}.rb")
54
+ Dir.chdir(latest_release) do
55
+ Chef::Log.info "running deploy hook: #{latest_release}/deploy/#{what}.rb"
56
+ instance_eval(IO.read("#{latest_release}/deploy/#{what}.rb"))
57
+ end
58
+ end
59
+ end
60
+
61
+ def latest_release
62
+ all_releases.last
63
+ end
64
+
65
+ def previous_release(current=latest_release)
66
+ index = all_releases.index(current)
67
+ all_releases[index-1]
68
+ end
69
+
70
+ def oldest_release
71
+ all_releases.first
72
+ end
73
+
74
+ def all_releases
75
+ `ls #{release_dir}`.split("\n").sort.map{|r| File.join(release_dir, r)}
76
+ end
77
+
78
+ def cleanup
79
+ while all_releases.size >= 5
80
+ FileUtils.rm_rf oldest_release
81
+ end
82
+ end
83
+
84
+ def rollback
85
+ Chef::Log.info "rolling back to previous release"
86
+ symlink(previous_release)
87
+ FileUtils.rm_rf latest_release
88
+ Chef::Log.info "restarting with previous release"
89
+ restart
90
+ end
91
+
92
+ def migrate
93
+ if @configuration[:migrate]
94
+ chef_run "ln -nfs #{shared_path}/config/database.yml #{latest_release}/config/database.yml"
95
+ chef_run "ln -nfs #{shared_path}/log #{latest_release}/log"
96
+ Chef::Log.info "Migrating: cd #{latest_release} && sudo -u #{user} RAILS_ENV=#{@configuration[:environment]} RACK_ENV=#{@configuration[:environment]} MERB_ENV=#{@configuration[:environment]} #{@configuration[:migration_command]}"
97
+ chef_run("chown -R #{user}:#{group} #{latest_release}")
98
+ chef_run("cd #{latest_release} && sudo -u #{user} RAILS_ENV=#{@configuration[:environment]} RACK_ENV=#{@configuration[:environment]} MERB_ENV=#{@configuration[:environment]} #{@configuration[:migration_command]}")
99
+ end
100
+ end
101
+
102
+ def user
103
+ @configuration[:user] || 'nobody'
104
+ end
105
+
106
+ def group
107
+ @configuration[:group] || user
108
+ end
109
+
110
+ def current_path
111
+ "#{@configuration[:deploy_to]}/current"
112
+ end
113
+
114
+ def shared_path
115
+ configuration[:shared_path]
116
+ end
117
+
118
+ def release_dir
119
+ "#{@configuration[:deploy_to]}/releases"
120
+ end
121
+
122
+ def release_path
123
+ @configuration[:release_path]
124
+ end
125
+
126
+ def node
127
+ @configuration[:node]
128
+ end
129
+
130
+ def symlink(release_to_link=latest_release)
131
+ Chef::Log.info "symlinking and finishing deploy"
132
+ symlink = false
133
+ begin
134
+ chef_run [ "chmod -R g+w #{release_to_link}",
135
+ "rm -rf #{release_to_link}/log #{release_to_link}/public/system #{release_to_link}/tmp/pids",
136
+ "mkdir -p #{release_to_link}/tmp",
137
+ "ln -nfs #{shared_path}/log #{release_to_link}/log",
138
+ "mkdir -p #{release_to_link}/public",
139
+ "mkdir -p #{release_to_link}/config",
140
+ "ln -nfs #{shared_path}/system #{release_to_link}/public/system",
141
+ "ln -nfs #{shared_path}/pids #{release_to_link}/tmp/pids",
142
+ "ln -nfs #{shared_path}/config/database.yml #{release_to_link}/config/database.yml",
143
+ "chown -R #{user}:#{group} #{release_to_link}"
144
+ ].join(" && ")
145
+
146
+ symlink = true
147
+ chef_run "rm -f #{current_path} && ln -nfs #{release_to_link} #{current_path} && chown -R #{user}:#{group} #{current_path}"
148
+ rescue => e
149
+ chef_run "rm -f #{current_path} && ln -nfs #{previous_release(release_to_link)} #{current_path} && chown -R #{user}:#{group} #{current_path}" if symlink
150
+ chef_run "rm -rf #{release_to_link}"
151
+ raise e
152
+ end
153
+ end
154
+
155
+ def run_with_result(cmd)
156
+ res = `#{cmd} 2>&1`
157
+ raise(ChefDeployFailure, res) unless $? == 0
158
+ res
159
+ end
160
+
161
+ def chef_run(cmd)
162
+ Chef::Mixin::Command.run_command(:command => cmd)
163
+ end
164
+
165
+ def run(cmd)
166
+ Chef::Mixin::Command.run_command(:command => cmd, :user => user)
167
+ end
168
+
169
+ def sudo(cmd)
170
+ Chef::Mixin::Command.run_command(:command => cmd)
171
+ end
172
+
173
+ # :repository_cache
174
+ # :shared_path
175
+ # :repository
176
+ # :release_path
177
+ # :copy_exclude
178
+ # :revision
179
+ # :user
180
+ # :group
181
+ def initialize(opts={})
182
+ @configuration = opts
183
+ @configuration[:shared_path] = "#{@configuration[:deploy_to]}/shared"
184
+ end
185
+
186
+ def configuration
187
+ @configuration
188
+ end
189
+
190
+ def source
191
+ @source ||= case configuration[:scm]
192
+ when 'git'
193
+ Git.new configuration
194
+ when 'svn'
195
+ Subversion.new configuration
196
+ end
197
+ end
198
+
199
+ private
200
+
201
+ def install_gems
202
+ if File.exist?("#{latest_release}/gems.yml")
203
+ gems = YAML.load(IO.read("#{latest_release}/gems.yml"))
204
+ resources = []
205
+ gems.each do |g|
206
+ next if has_gem?(g[:name], g[:version])
207
+ r = Chef::Resource::GemPackage.new(g[:name], nil, @configuration[:node])
208
+ r.version g[:version]
209
+ r.source "http://gems.github.com"
210
+ resources << r
211
+ end
212
+ resources.each do |r|
213
+ begin
214
+ r.run_action(:install)
215
+ rescue Chef::Exception::Exec => e
216
+ Chef::Log.info("Error installing gem: #{r.package_name} version: #{r.version}")
217
+ raise e
218
+ end
219
+ end
220
+ end
221
+ end
222
+
223
+ def has_gem?(name, version=nil)
224
+ if !$GEM_LIST_DEPLOY
225
+ gems = {}
226
+ `gem list --local`.each_line do |line|
227
+ gems[$1.to_sym] = $2.split(/, /) if line =~ /^(.*) \(([^\)]*)\)$/
228
+ end
229
+ $GEM_LIST_DEPLOY = gems
230
+ end
231
+ if $GEM_LIST_DEPLOY[name.to_sym]
232
+ if version
233
+ if $GEM_LIST_DEPLOY[name.to_sym].include?(version)
234
+ Chef::Log.info("Gem: #{name}:#{version} already installed, skipping")
235
+ return true
236
+ end
237
+ else
238
+ Chef::Log.info("Gem: #{name} already installed, skipping")
239
+ return true
240
+ end
241
+ end
242
+ false
243
+ end
244
+
245
+ def repository_cache
246
+ File.join(configuration[:shared_path], configuration[:repository_cache] || "cached-copy")
247
+ end
248
+
249
+ def update_repository_cache
250
+ command = "if [ -d #{repository_cache} ] &&" +
251
+ "git --git-dir #{repository_cache}/.git/ remote -v | grep -q #{configuration[:repository]}; then " +
252
+ "#{source.sync(revision, repository_cache)}; " +
253
+ "else #{source.checkout(revision, repository_cache)}; fi"
254
+ command
255
+ end
256
+
257
+ def copy_repository_cache
258
+ if copy_exclude.empty?
259
+ return "cp -RPp #{repository_cache} #{release_path} && #{mark}"
260
+ else
261
+ exclusions = copy_exclude.map { |e| "--exclude=\"#{e}\"" }.join(' ')
262
+ return "rsync -lrpt #{exclusions} #{repository_cache}/* #{release_path} && #{mark}"
263
+ end
264
+ end
265
+
266
+ def revision
267
+ configuration[:revision]
268
+ end
269
+
270
+ def mark
271
+ "(echo #{revision} > #{release_path}/REVISION)"
272
+ end
273
+
274
+ def copy_exclude
275
+ @copy_exclude ||= Array(configuration.fetch(:copy_exclude, []))
276
+ end
277
+ end
@@ -0,0 +1,151 @@
1
+ # stolen wholesale from capistrano, thanks Jamis!
2
+
3
+ class Git
4
+ # Performs a clone on the remote machine, then checkout on the branch
5
+ # you want to deploy.
6
+
7
+ def initialize(opts={})
8
+ @configuration = opts
9
+ end
10
+
11
+ def configuration
12
+ @configuration
13
+ end
14
+
15
+ def git
16
+ res = configuration[:git_ssh_wrapper] ? "GIT_SSH=#{configuration[:git_ssh_wrapper]} git" : 'git'
17
+ res = "sudo -u #{configuration[:user]} #{res}" if configuration[:user]
18
+ res
19
+ end
20
+
21
+ def respository
22
+ configuration[:repository]
23
+ end
24
+
25
+ def checkout(revision, destination)
26
+ remote = origin
27
+
28
+ args = []
29
+ args << "-o #{remote}" unless remote == 'origin'
30
+ if depth = configuration[:git_shallow_clone]
31
+ args << "--depth #{depth}"
32
+ end
33
+
34
+ execute = []
35
+
36
+ execute << "rm -rf #{destination}"
37
+
38
+ if args.empty?
39
+ execute << "#{git} clone #{verbose} #{configuration[:repository]} #{destination}"
40
+ else
41
+ execute << "#{git} clone #{verbose} #{args.join(' ')} #{configuration[:repository]} #{destination}"
42
+ end
43
+
44
+ # checkout into a local branch rather than a detached HEAD
45
+ execute << "cd #{destination} && #{git} checkout #{verbose} -b deploy #{revision}"
46
+
47
+ if configuration[:git_enable_submodules]
48
+ execute << "#{git} submodule #{verbose} init"
49
+ execute << "#{git} submodule #{verbose} update"
50
+ end
51
+
52
+ execute.join(" && ")
53
+ end
54
+
55
+ # An expensive export. Performs a checkout as above, then
56
+ # removes the repo.
57
+ def export(revision, destination)
58
+ checkout(revision, destination) << " && rm -Rf #{destination}/.git"
59
+ end
60
+
61
+ # Merges the changes to 'head' since the last fetch, for remote_cache
62
+ # deployment strategy
63
+ def sync(revision, destination)
64
+ remote = origin
65
+
66
+ execute = []
67
+ execute << "cd #{destination}"
68
+
69
+ # Use git-config to setup a remote tracking branches. Could use
70
+ # git-remote but it complains when a remote of the same name already
71
+ # exists, git-config will just silenty overwrite the setting every
72
+ # time. This could cause wierd-ness in the remote cache if the url
73
+ # changes between calls, but as long as the repositories are all
74
+ # based from each other it should still work fine.
75
+ if remote != 'origin'
76
+ execute << "#{git} config remote.#{remote}.url #{configuration[:repository]}"
77
+ execute << "#{git} config remote.#{remote}.fetch +refs/heads/*:refs/remotes/#{remote}/*"
78
+ end
79
+
80
+ # since we're in a local branch already, just reset to specified revision rather than merge
81
+ execute << "#{git} fetch #{verbose} #{remote} && #{git} reset #{verbose} --hard #{revision}"
82
+
83
+ if configuration[:git_enable_submodules]
84
+ execute << "#{git} submodule #{verbose} init"
85
+ execute << "#{git} submodule #{verbose} update"
86
+ end
87
+
88
+ execute.join(" && ")
89
+ end
90
+
91
+ # Returns a string of diffs between two revisions
92
+ def diff(from, to=nil)
93
+ from << "..#{to}" if to
94
+ scm :diff, from
95
+ end
96
+
97
+ # Returns a log of changes between the two revisions (inclusive).
98
+ def log(from, to=nil)
99
+ scm :log, "#{from}..#{to}"
100
+ end
101
+
102
+ # Getting the actual commit id, in case we were passed a tag
103
+ # or partial sha or something - it will return the sha if you pass a sha, too
104
+ def query_revision(reference)
105
+ raise ArgumentError, "Deploying remote branches is no longer supported. Specify the remote branch as a local branch for the git repository you're deploying from (ie: '#{reference.gsub('origin/', '')}' rather than '#{reference}')." if reference =~ /^origin\//
106
+ sha_hash = '[0-9a-f]{40}'
107
+ return reference if reference =~ /^#{sha_hash}$/ # it's already a sha
108
+ command = scm('ls-remote', configuration[:repository], reference)
109
+ result = nil
110
+ begin
111
+ result = yield(command)
112
+ rescue ChefDeployFailure => e
113
+ raise obvious_error("Could not access the remote Git repository. If this is a private repository, please verify that the deploy key for your application has been added to your remote Git account.", e)
114
+ end
115
+ unless result =~ /^(#{sha_hash})\s+(\S+)/
116
+ raise "Unable to resolve reference for '#{reference}' on repository '#{configuration[:repository]}'."
117
+ end
118
+ newrev = $1
119
+ newref = $2
120
+ return newrev
121
+ end
122
+
123
+ def scm(*args)
124
+ [git, *args].compact.join(" ")
125
+ end
126
+
127
+ def head
128
+ configuration[:branch] || 'HEAD'
129
+ end
130
+
131
+ def origin
132
+ configuration[:remote] || 'origin'
133
+ end
134
+
135
+ private
136
+
137
+ # If verbose output is requested, return nil, otherwise return the
138
+ # command-line switch for "quiet" ("-q").
139
+ def verbose
140
+ nil#configuration[:scm_verbose] ? nil : "-q"
141
+ end
142
+
143
+ # Build an error string that stands out in a log file
144
+ def obvious_error(message, e)
145
+ "#{stars}\n#{message}\n#{stars}\n#{e.message}#{stars}"
146
+ end
147
+
148
+ def stars
149
+ ("\n"+'*'*80)*2
150
+ end
151
+ end
@@ -0,0 +1,105 @@
1
+ require 'yaml'
2
+
3
+ class Subversion
4
+
5
+ def initialize(opts={})
6
+ @config = opts
7
+ end
8
+
9
+ def config
10
+ @config
11
+ end
12
+
13
+ # Subversion understands 'HEAD' to refer to the latest revision in the
14
+ # repository.
15
+ def head
16
+ "HEAD"
17
+ end
18
+
19
+ def repository
20
+ config[:repository]
21
+ end
22
+
23
+ # Returns the command that will check out the given revision to the
24
+ # given destination.
25
+ def checkout(revision, destination)
26
+ scm :checkout, config[:arguments], verbose, authentication, "-r#{revision}", repository, destination
27
+ end
28
+
29
+ # Returns the command that will do an "svn update" to the given
30
+ # revision, for the working copy at the given destination.
31
+ def sync(revision, destination)
32
+ scm :update, config[:arguments], verbose, authentication, "-r#{revision}", destination
33
+ end
34
+
35
+ # Returns the command that will do an "svn export" of the given revision
36
+ # to the given destination.
37
+ def export(revision, destination)
38
+ scm :export, config[:arguments], verbose, authentication, "-r#{revision}", repository, destination
39
+ end
40
+
41
+ # Returns the command that will do an "svn diff" for the two revisions.
42
+ def diff(from, to=nil)
43
+ scm :diff, repository, authentication, "-r#{from}:#{to || head}"
44
+ end
45
+
46
+ # Returns an "svn log" command for the two revisions.
47
+ def log(from, to=nil)
48
+ scm :log, repository, authentication, "-r#{from}:#{to || head}"
49
+ end
50
+
51
+ # Attempts to translate the given revision identifier to a "real"
52
+ # revision. If the identifier is an integer, it will simply be returned.
53
+ # Otherwise, this will yield a string of the commands it needs to be
54
+ # executed (svn info), and will extract the revision from the response.
55
+ def query_revision(revision)
56
+ return revision if revision =~ /^\d+$/
57
+ command = scm(:info, repository, authentication, "-r#{revision}")
58
+ result = yield(command)
59
+ yaml = YAML.load(result)
60
+ raise "tried to run `#{command}' and got unexpected result #{result.inspect}" unless Hash === yaml
61
+ yaml['Last Changed Rev'] || yaml['Revision']
62
+ end
63
+
64
+ # Increments the given revision number and returns it.
65
+ def next_revision(revision)
66
+ revision.to_i + 1
67
+ end
68
+
69
+
70
+ private
71
+
72
+ # If a username is configured for the SCM, return the command-line
73
+ # switches for that. Note that we don't need to return the password
74
+ # switch, since Capistrano will check for that prompt in the output
75
+ # and will respond appropriately.
76
+ def authentication
77
+ username = config[:svn_username]
78
+ return "" unless username
79
+ result = "--username #{config[:svn_username]} "
80
+ result << "--password #{config[:svn_password]} "
81
+ result
82
+ end
83
+
84
+ # If verbose output is requested, return nil, otherwise return the
85
+ # command-line switch for "quiet" ("-q").
86
+ # FIXME: This is currently flipped logically since it doesn't check
87
+ # for any verbosity configuration flag
88
+ def verbose
89
+ "-q"
90
+ end
91
+
92
+ def svn
93
+ res = "svn"
94
+ res = "sudo -u #{config[:user]} #{res}" if config[:user]
95
+ res
96
+ end
97
+
98
+ def scm(*args)
99
+ [svn, *args].compact.join(" ")
100
+ end
101
+
102
+ def svn_password_prompt
103
+ config[:svn_password]
104
+ end
105
+ end
metadata ADDED
@@ -0,0 +1,64 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: chef-deploy
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.5
5
+ platform: ruby
6
+ authors:
7
+ - Ezra Zygmuntowicz
8
+ autorequire: chef-deploy
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-10-04 00:00:00 -04:00
13
+ default_executable:
14
+ dependencies: []
15
+
16
+ description: A gem that provides...
17
+ email: Your Email
18
+ executables: []
19
+
20
+ extensions: []
21
+
22
+ extra_rdoc_files:
23
+ - README.rdoc
24
+ - LICENSE
25
+ - TODO
26
+ files:
27
+ - LICENSE
28
+ - README.rdoc
29
+ - Rakefile
30
+ - TODO
31
+ - lib/chef-deploy/cached_deploy.rb
32
+ - lib/chef-deploy/git.rb
33
+ - lib/chef-deploy/subversion.rb
34
+ - lib/chef-deploy.rb
35
+ has_rdoc: true
36
+ homepage: http://example.com
37
+ licenses: []
38
+
39
+ post_install_message:
40
+ rdoc_options: []
41
+
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: "0"
49
+ version:
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: "0"
55
+ version:
56
+ requirements: []
57
+
58
+ rubyforge_project:
59
+ rubygems_version: 1.3.4
60
+ signing_key:
61
+ specification_version: 3
62
+ summary: A gem that provides...
63
+ test_files: []
64
+