fotonauts-chef-deploy 0.1.0

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,24 @@
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
8
+
9
+ deploy "/data/#{app}" do
10
+ repo "git://github.com/engineyard/rack-app.git"
11
+ branch "HEAD"
12
+ user "ez"
13
+ enable_submodules true
14
+ migrate true
15
+ migration_command "rake db:migrate"
16
+ environment "production"
17
+ shallow_clone true
18
+ revision '0xbeadbeef'
19
+ action :deploy # or :rollback
20
+ end
21
+
22
+
23
+ Currently only supports doing the cached git checkout, rsyncing it into place and doing the symlink dance.
24
+ Does not restart servers or have hooks(yet)
@@ -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.1.0"
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,183 @@
1
+ require File.join(File.dirname(__FILE__), 'chef-deploy/git')
2
+ require File.join(File.dirname(__FILE__), 'chef-deploy/cached_deploy')
3
+
4
+ # deploy "/data/#{app}" do
5
+ # repo "git://github.com/engineyard/rack-app.git"
6
+ # branch "HEAD"
7
+ # user "ez"
8
+ # enable_submodules true
9
+ # migrate true
10
+ # migration_command "rake db:migrate"
11
+ # environment "production"
12
+ # shallow_clone true
13
+ # action :deploy # or :rollback
14
+ # restart_command "touch tmp/restart.txt"
15
+ # end
16
+
17
+ class Chef
18
+ class Resource
19
+ class Deploy < Chef::Resource
20
+
21
+ def initialize(name, collection=nil, node=nil)
22
+ super(name, collection, node)
23
+ @resource_name = :deploy
24
+ @deploy_to = name
25
+ @branch = 'HEAD'
26
+ @repository_cache = 'cached-copy'
27
+ @copy_exclude = []
28
+ @revision = nil
29
+ @action = :deploy
30
+ @allowed_actions.push(:deploy)
31
+ @allowed_actions.push(:rollback)
32
+ end
33
+
34
+ def repo(arg=nil)
35
+ set_or_return(
36
+ :repo,
37
+ arg,
38
+ :kind_of => [ String ]
39
+ )
40
+ end
41
+
42
+
43
+ def role(arg=nil)
44
+ set_or_return(
45
+ :role,
46
+ arg,
47
+ :kind_of => [ String ]
48
+ )
49
+ end
50
+
51
+ def restart_command(arg=nil)
52
+ set_or_return(
53
+ :restart_command,
54
+ arg,
55
+ :kind_of => [ String ]
56
+ )
57
+ end
58
+
59
+ def migrate(arg=nil)
60
+ set_or_return(
61
+ :migrate,
62
+ arg,
63
+ :kind_of => [ TrueClass, FalseClass ]
64
+ )
65
+ end
66
+
67
+ def migration_command(arg=nil)
68
+ set_or_return(
69
+ :migration_command,
70
+ arg,
71
+ :kind_of => [ String ]
72
+ )
73
+ end
74
+
75
+ def user(arg=nil)
76
+ set_or_return(
77
+ :user,
78
+ arg,
79
+ :kind_of => [ String ]
80
+ )
81
+ end
82
+
83
+ def enable_submodules(arg=false)
84
+ set_or_return(
85
+ :enable_submodules,
86
+ arg,
87
+ :kind_of => [ TrueClass, FalseClass ]
88
+ )
89
+ end
90
+
91
+ def shallow_clone(arg=false)
92
+ set_or_return(
93
+ :shallow_clone,
94
+ arg,
95
+ :kind_of => [ TrueClass, FalseClass ]
96
+ )
97
+ end
98
+
99
+ def repository_cache(arg=nil)
100
+ set_or_return(
101
+ :repository_cache,
102
+ arg,
103
+ :kind_of => [ String ]
104
+ )
105
+ end
106
+
107
+ def copy_exclude(arg=nil)
108
+ set_or_return(
109
+ :copy_exclude,
110
+ arg,
111
+ :kind_of => [ String ]
112
+ )
113
+ end
114
+
115
+ def revision(arg=nil)
116
+ set_or_return(
117
+ :revision,
118
+ arg,
119
+ :kind_of => [ String ]
120
+ )
121
+ end
122
+
123
+ def branch(arg=nil)
124
+ set_or_return(
125
+ :branch,
126
+ arg,
127
+ :kind_of => [ String ]
128
+ )
129
+ end
130
+
131
+ def environment(arg=nil)
132
+ set_or_return(
133
+ :environment,
134
+ arg,
135
+ :kind_of => [ String ]
136
+ )
137
+ end
138
+
139
+ end
140
+ end
141
+
142
+ class Provider
143
+ class Deploy < Chef::Provider
144
+
145
+ def load_current_resource
146
+ FileUtils.mkdir_p "#{@new_resource.name}/shared"
147
+ FileUtils.mkdir_p "#{@new_resource.name}/releases"
148
+ @dep = CachedDeploy.new :user => @new_resource.user,
149
+ :role => @new_resource.role,
150
+ :branch => (@new_resource.branch || 'HEAD'),
151
+ :restart_command => @new_resource.restart_command,
152
+ :repository => @new_resource.repo,
153
+ :environment => @new_resource.environment,
154
+ :migration_command => @new_resource.migration_command,
155
+ :migrate => @new_resource.migrate,
156
+ :deploy_to => @new_resource.name,
157
+ :repository_cache => @new_resource.repository_cache,
158
+ :copy_exclude => @new_resource.copy_exclude,
159
+ :revision => (@new_resource.revision || ''),
160
+ :git_enable_submodules => @new_resource.enable_submodules,
161
+ :git_shallow_clone => @new_resource.shallow_clone,
162
+ :node => @node,
163
+ :new_resource => @new_resource
164
+ end
165
+
166
+ def action_deploy
167
+ Chef::Log.level(:debug)
168
+ Chef::Log.info "Running a new deploy\nto: #{@new_resource.name}\nrepo: #{@new_resource.repo}"
169
+ @dep.deploy
170
+ Chef::Log.level(Chef::Config[:log_level])
171
+ end
172
+
173
+ def action_rollback
174
+ Chef::Log.level(:debug)
175
+ Chef::Log.info "Rolling back deploy\nto: #{@new_resource.name}\nrepo: #{@new_resource.repo}"
176
+ @dep.rollback
177
+ Chef::Log.level(Chef::Config[:log_level])
178
+ end
179
+ end
180
+ end
181
+ end
182
+
183
+ Chef::Platform.platforms[:default].merge! :deploy => Chef::Provider::Deploy, :gem_package => Chef::Provider::Package::Rubygems
@@ -0,0 +1,243 @@
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 cmd}
13
+ end
14
+ return if check_current_revision_and_noop_if_same(@configuration[:revision])
15
+ Chef::Log.info "deploying branch: #{@configuration[:branch]} rev: #{@configuration[:revision]}"
16
+ Chef::Log.info "updating the cached checkout"
17
+ run(update_repository_cache)
18
+ Chef::Log.info "copying the cached version to #{configuration[:release_path]}"
19
+ run(copy_repository_cache)
20
+ install_gems
21
+ callback(:before_migrate)
22
+ migrate
23
+ callback(:before_symlink)
24
+ symlink
25
+ callback(:before_restart)
26
+ restart
27
+ callback(:after_restart)
28
+ cleanup
29
+ end
30
+
31
+ def restart
32
+ unless @configuration[:restart_command].empty?
33
+ Chef::Log.info "restarting app: #{latest_release}"
34
+ Chef::Log.info run("cd #{current_path} && #{@configuration[:restart_command]}")
35
+ end
36
+ end
37
+
38
+ def install_gems
39
+ if File.exist?("#{latest_release}/gems.yml")
40
+ gems = YAML.load(IO.read("#{latest_release}/gems.yml"))
41
+ resources = []
42
+ gems.each do |g|
43
+ next if has_gem?(g[:name], g[:version])
44
+ r = Chef::Resource::GemPackage.new(g[:name], nil, @configuration[:node])
45
+ r.version g[:version]
46
+ r.source "http://gems.github.com"
47
+ resources << r
48
+ end
49
+ resources.each do |r|
50
+ begin
51
+ r.run_action(:install)
52
+ rescue Chef::Exception::Exec => e
53
+ Chef::Log.info("Error installing gem: #{r.package_name} version: #{r.version}")
54
+ raise e
55
+ end
56
+ end
57
+ end
58
+ end
59
+
60
+ def has_gem?(name, version=nil)
61
+ if !$GEM_LIST_DEPLOY
62
+ gems = {}
63
+ `gem list --local`.each_line do |line|
64
+ gems[$1.to_sym] = $2.split(/, /) if line =~ /^(.*) \(([^\)]*)\)$/
65
+ end
66
+ $GEM_LIST_DEPLOY = gems
67
+ end
68
+ if $GEM_LIST_DEPLOY[name.to_sym]
69
+ if version
70
+ if $GEM_LIST_DEPLOY[name.to_sym].include?(version)
71
+ Chef::Log.info("Gem: #{name}:#{version} already installed, skipping")
72
+ return true
73
+ end
74
+ else
75
+ Chef::Log.info("Gem: #{name} already installed, skipping")
76
+ return true
77
+ end
78
+ end
79
+ false
80
+ end
81
+
82
+ def check_current_revision_and_noop_if_same(newrev)
83
+ IO.read("#{latest_release}/REVISION").chomp == newrev
84
+ rescue
85
+ false
86
+ end
87
+
88
+ # before_symlink
89
+ # before_restart
90
+ def callback(what)
91
+ if File.exist?("#{latest_release}/deploy/#{what}.rb")
92
+ Chef::Log.info "running deploy hook: #{latest_release}/deploy/#{what}.rb"
93
+ Chef::Log.info run("cd #{latest_release} && sudo -u #{user} ruby deploy/#{what}.rb #{@configuration[:environment]} #{@configuration[:role]}")
94
+ end
95
+ end
96
+
97
+ def latest_release
98
+ all_releases.last
99
+ end
100
+
101
+ def previous_release(current=latest_release)
102
+ index = all_releases.index(current)
103
+ all_releases[index-1]
104
+ end
105
+
106
+ def oldest_release
107
+ all_releases.first
108
+ end
109
+
110
+ def all_releases
111
+ `ls #{release_path}`.split("\n").sort.map{|r| File.join(release_path, r)}
112
+ end
113
+
114
+ def cleanup
115
+ while all_releases.size >= 5
116
+ FileUtils.rm_rf oldest_release
117
+ end
118
+ end
119
+
120
+ def rollback
121
+ Chef::Log.info "rolling back to previous release"
122
+ symlink(previous_release)
123
+ FileUtils.rm_rf latest_release
124
+ Chef::Log.info "restarting with previous release"
125
+ restart
126
+ end
127
+
128
+ def migrate
129
+ if @configuration[:migrate]
130
+ run "ln -nfs #{shared_path}/config/database.yml #{latest_release}/config/database.yml"
131
+ Chef::Log.info "Migrating: cd #{latest_release} && RAILS_ENV=#{@configuration[:environment]} RACK_ENV=#{@configuration[:environment]} MERB_ENV=#{@configuration[:environment]} sudo -u #{user} #{@configuration[:migration_command]}"
132
+ Chef::Log.info run("chown -R #{user}:#{user} #{latest_release}")
133
+ Chef::Log.info run("cd #{latest_release} && RAILS_ENV=#{@configuration[:environment]} RACK_ENV=#{@configuration[:environment]} MERB_ENV=#{@configuration[:environment]} sudo -u #{user} #{@configuration[:migration_command]}")
134
+ end
135
+ end
136
+
137
+ def user
138
+ @configuration[:user] || 'nobody'
139
+ end
140
+
141
+ def current_path
142
+ "#{@configuration[:deploy_to]}/current"
143
+ end
144
+
145
+ def shared_path
146
+ configuration[:shared_path]
147
+ end
148
+
149
+ def release_path
150
+ "#{@configuration[:deploy_to]}/releases"
151
+ end
152
+
153
+ def symlink(release_to_link=latest_release)
154
+ Chef::Log.info "symlinking and finishing deploy"
155
+ symlink = false
156
+ begin
157
+ run [ "chmod -R g+w #{release_to_link}",
158
+ "rm -rf #{release_to_link}/log #{release_to_link}/public/system #{release_to_link}/tmp/pids",
159
+ "mkdir -p #{release_to_link}/tmp",
160
+ "ln -nfs #{shared_path}/log #{release_to_link}/log",
161
+ "mkdir -p #{release_to_link}/public",
162
+ "mkdir -p #{release_to_link}/config",
163
+ "ln -nfs #{shared_path}/system #{release_to_link}/public/system",
164
+ "ln -nfs #{shared_path}/pids #{release_to_link}/tmp/pids",
165
+ "ln -nfs #{shared_path}/config/database.yml #{release_to_link}/config/database.yml",
166
+ "chown -R #{user}:#{user} #{release_to_link}"
167
+ ].join(" && ")
168
+
169
+ symlink = true
170
+ run "rm -f #{current_path} && ln -nfs #{release_to_link} #{current_path} && chown -R #{user}:#{user} #{current_path}"
171
+ rescue => e
172
+ run "rm -f #{current_path} && ln -nfs #{previous_release(release_to_link)} #{current_path} && chown -R #{user}:#{user} #{current_path}" if symlink
173
+ run "rm -rf #{release_to_link}"
174
+ raise e
175
+ end
176
+ end
177
+
178
+ def run(cmd)
179
+ res = `#{cmd}`
180
+ raise(ChefDeployFailure, res) unless $? == 0
181
+ res
182
+ end
183
+
184
+ # :repository_cache
185
+ # :shared_path
186
+ # :repository
187
+ # :release_path
188
+ # :copy_exclude
189
+ # :revision
190
+ # :user
191
+ # :group
192
+ def initialize(opts={})
193
+ @configuration = opts
194
+ @configuration[:shared_path] = "#{@configuration[:deploy_to]}/shared"
195
+ end
196
+
197
+ def configuration
198
+ @configuration
199
+ end
200
+
201
+ def source
202
+ #@source ||= case configuration[:scm]
203
+ #when 'git'
204
+ Git.new configuration
205
+ #when 'svn'
206
+ # Subversion.new configuration
207
+ #end
208
+ end
209
+
210
+ private
211
+
212
+ def repository_cache
213
+ File.join(configuration[:shared_path], configuration[:repository_cache] || "cached-copy")
214
+ end
215
+
216
+ def update_repository_cache
217
+ command = "if [ -d #{repository_cache} ]; then " +
218
+ "#{source.sync(revision, repository_cache)}; " +
219
+ "else #{source.checkout(revision, repository_cache)}; fi"
220
+ command
221
+ end
222
+
223
+ def copy_repository_cache
224
+ if copy_exclude.empty?
225
+ return "cp -RPp #{repository_cache} #{configuration[:release_path]} && #{mark}"
226
+ else
227
+ exclusions = copy_exclude.map { |e| "--exclude=\"#{e}\"" }.join(' ')
228
+ return "rsync -lrpt #{exclusions} #{repository_cache}/* #{configuration[:release_path]} && #{mark}"
229
+ end
230
+ end
231
+
232
+ def revision
233
+ configuration[:revision]
234
+ end
235
+
236
+ def mark
237
+ "(echo #{revision} > #{configuration[:release_path]}/REVISION)"
238
+ end
239
+
240
+ def copy_exclude
241
+ @copy_exclude ||= Array(configuration.fetch(:copy_exclude, []))
242
+ end
243
+ end
@@ -0,0 +1,132 @@
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
+ "git"
17
+ end
18
+
19
+ def respository
20
+ configuration[:repository]
21
+ end
22
+
23
+ def checkout(revision, destination)
24
+ remote = origin
25
+
26
+ args = []
27
+ args << "-o #{remote}" unless remote == 'origin'
28
+ if depth = configuration[:git_shallow_clone]
29
+ args << "--depth #{depth}"
30
+ end
31
+
32
+ execute = []
33
+ if args.empty?
34
+ execute << "#{git} clone #{verbose} #{configuration[:repository]} #{destination}"
35
+ else
36
+ execute << "#{git} clone #{verbose} #{args.join(' ')} #{configuration[:repository]} #{destination}"
37
+ end
38
+
39
+ # checkout into a local branch rather than a detached HEAD
40
+ execute << "cd #{destination} && #{git} checkout #{verbose} -b deploy #{revision}"
41
+
42
+ if configuration[:git_enable_submodules]
43
+ execute << "#{git} submodule #{verbose} init"
44
+ execute << "#{git} submodule #{verbose} update"
45
+ end
46
+
47
+ execute.join(" && ")
48
+ end
49
+
50
+ # An expensive export. Performs a checkout as above, then
51
+ # removes the repo.
52
+ def export(revision, destination)
53
+ checkout(revision, destination) << " && rm -Rf #{destination}/.git"
54
+ end
55
+
56
+ # Merges the changes to 'head' since the last fetch, for remote_cache
57
+ # deployment strategy
58
+ def sync(revision, destination)
59
+ remote = origin
60
+
61
+ execute = []
62
+ execute << "cd #{destination}"
63
+
64
+ # Use git-config to setup a remote tracking branches. Could use
65
+ # git-remote but it complains when a remote of the same name already
66
+ # exists, git-config will just silenty overwrite the setting every
67
+ # time. This could cause wierd-ness in the remote cache if the url
68
+ # changes between calls, but as long as the repositories are all
69
+ # based from each other it should still work fine.
70
+ if remote != 'origin'
71
+ execute << "#{git} config remote.#{remote}.url #{configuration[:repository]}"
72
+ execute << "#{git} config remote.#{remote}.fetch +refs/heads/*:refs/remotes/#{remote}/*"
73
+ end
74
+
75
+ # since we're in a local branch already, just reset to specified revision rather than merge
76
+ execute << "#{git} fetch #{verbose} #{remote} && #{git} reset #{verbose} --hard #{revision}"
77
+
78
+ if configuration[:git_enable_submodules]
79
+ execute << "#{git} submodule #{verbose} init"
80
+ execute << "#{git} submodule #{verbose} update"
81
+ end
82
+
83
+ execute.join(" && ")
84
+ end
85
+
86
+ # Returns a string of diffs between two revisions
87
+ def diff(from, to=nil)
88
+ from << "..#{to}" if to
89
+ scm :diff, from
90
+ end
91
+
92
+ # Returns a log of changes between the two revisions (inclusive).
93
+ def log(from, to=nil)
94
+ scm :log, "#{from}..#{to}"
95
+ end
96
+
97
+ # Getting the actual commit id, in case we were passed a tag
98
+ # or partial sha or something - it will return the sha if you pass a sha, too
99
+ def query_revision(revision)
100
+ 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: '#{revision.gsub('origin/', '')}' rather than '#{revision}')." if revision =~ /^origin\//
101
+ return revision if revision =~ /^[0-9a-f]{40}$/
102
+ command = scm('ls-remote', configuration[:repository], revision)
103
+ result = yield(command)
104
+ rev, ref = result.split(/[\t\n]/)
105
+ newrev = nil
106
+ if ref.sub(/refs\/.*?\//, '').strip == revision
107
+ newrev = rev
108
+ end
109
+ raise "Unable to resolve revision for '#{revision}' on repository '#{configuration[:repository]}'." unless newrev =~ /^[0-9a-f]{40}$/
110
+ return newrev
111
+ end
112
+
113
+ def scm(*args)
114
+ [git, *args].compact.join(" ")
115
+ end
116
+
117
+ def head
118
+ configuration[:branch] || 'HEAD'
119
+ end
120
+
121
+ def origin
122
+ configuration[:remote] || 'origin'
123
+ end
124
+
125
+ private
126
+
127
+ # If verbose output is requested, return nil, otherwise return the
128
+ # command-line switch for "quiet" ("-q").
129
+ def verbose
130
+ nil#configuration[:scm_verbose] ? nil : "-q"
131
+ end
132
+ end
@@ -0,0 +1,98 @@
1
+ require 'capistrano/recipes/deploy/scm/base'
2
+ require 'yaml'
3
+
4
+ class Subversion
5
+
6
+ def initialize(opts={})
7
+ @config = opts
8
+ end
9
+
10
+ def config
11
+ @config
12
+ end
13
+
14
+ # Subversion understands 'HEAD' to refer to the latest revision in the
15
+ # repository.
16
+ def head
17
+ "HEAD"
18
+ end
19
+
20
+ def repository
21
+ config[:repository]
22
+ end
23
+
24
+ # Returns the command that will check out the given revision to the
25
+ # given destination.
26
+ def checkout(revision, destination)
27
+ scm :checkout, config[:arguments], verbose, authentication, "-r#{revision}", repository, destination
28
+ end
29
+
30
+ # Returns the command that will do an "svn update" to the given
31
+ # revision, for the working copy at the given destination.
32
+ def sync(revision, destination)
33
+ scm :update, arguments, verbose, authentication, "-r#{revision}", destination
34
+ end
35
+
36
+ # Returns the command that will do an "svn export" of the given revision
37
+ # to the given destination.
38
+ def export(revision, destination)
39
+ scm :export, arguments, verbose, authentication, "-r#{revision}", repository, destination
40
+ end
41
+
42
+ # Returns the command that will do an "svn diff" for the two revisions.
43
+ def diff(from, to=nil)
44
+ scm :diff, repository, authentication, "-r#{from}:#{to || head}"
45
+ end
46
+
47
+ # Returns an "svn log" command for the two revisions.
48
+ def log(from, to=nil)
49
+ scm :log, repository, authentication, "-r#{from}:#{to || head}"
50
+ end
51
+
52
+ # Attempts to translate the given revision identifier to a "real"
53
+ # revision. If the identifier is an integer, it will simply be returned.
54
+ # Otherwise, this will yield a string of the commands it needs to be
55
+ # executed (svn info), and will extract the revision from the response.
56
+ def query_revision(revision)
57
+ return revision if revision =~ /^\d+$/
58
+ command = scm(:info, repository, authentication, "-r#{revision}")
59
+ result = yield(command)
60
+ yaml = YAML.load(result)
61
+ raise "tried to run `#{command}' and got unexpected result #{result.inspect}" unless Hash === yaml
62
+ yaml['Last Changed Rev'] || yaml['Revision']
63
+ end
64
+
65
+ # Increments the given revision number and returns it.
66
+ def next_revision(revision)
67
+ revision.to_i + 1
68
+ end
69
+
70
+
71
+ private
72
+
73
+ # If a username is configured for the SCM, return the command-line
74
+ # switches for that. Note that we don't need to return the password
75
+ # switch, since Capistrano will check for that prompt in the output
76
+ # and will respond appropriately.
77
+ def authentication
78
+ username = config(:svn_username)
79
+ return "" unless username
80
+ result = "--username #{config(:svn_username)} "
81
+ result << "--password #{config(:svn_password)} "
82
+ result
83
+ end
84
+
85
+ # If verbose output is requested, return nil, otherwise return the
86
+ # command-line switch for "quiet" ("-q").
87
+ def verbose
88
+ "-q"
89
+ end
90
+
91
+ def scm(*args)
92
+ ['svn', *args].compact.join(" ")
93
+ end
94
+
95
+ def svn_password_prompt
96
+ config[:password]
97
+ end
98
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fotonauts-chef-deploy
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ezra Zygmuntowicz
8
+ autorequire: chef-deploy
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-05-12 00:00:00 -07: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
32
+ - lib/chef-deploy/cached_deploy.rb
33
+ - lib/chef-deploy/git.rb
34
+ - lib/chef-deploy/subversion.rb
35
+ - lib/chef-deploy.rb
36
+ has_rdoc: true
37
+ homepage: http://example.com
38
+ post_install_message:
39
+ rdoc_options: []
40
+
41
+ require_paths:
42
+ - lib
43
+ required_ruby_version: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: "0"
48
+ version:
49
+ required_rubygems_version: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: "0"
54
+ version:
55
+ requirements: []
56
+
57
+ rubyforge_project:
58
+ rubygems_version: 1.2.0
59
+ signing_key:
60
+ specification_version: 2
61
+ summary: A gem that provides...
62
+ test_files: []
63
+