sshkit icon indicating copy to clipboard operation
sshkit copied to clipboard

High level API

Open seenmyfate opened this issue 14 years ago • 8 comments

This is a summary of what I've had in mind for this:

End user can proceed with:

    > deploy my_app production master

    > setup my_app staging develop

So lib/deploy/production.rb

    require 'deploy/rails' # standard deploy included in gem
    require 'deploy/my_data_centre' # my own gem extensions

    module Deploy
      class Production
        include Deploy::Rails
        include MyDataCentre::Roles
        include Deploy::Notifier::Twitter
      end
    end

Rails users could get a version of the file above with:

    rails g install deploy

Which would generate:

    require 'deploy/rails'
    # comments/instructions here
    module Deploy
      class Production
        include Deploy::Rails
      end
    end

Allowing either rake task or executable to call

    configuration = Deploy::Configuration.new(parse_config)
    Deploy::Production.new(configuration).deploy

I would imagine configuration to be used for over-riding default configuration for symlinks, and setting up shared folders.

            {
              :name => 'my_app',
              :shared_directories => ['system', 'config', 'bundle', 'bin'],
              :normal_symlinks => ['config/database.yml', 'bin', 'log'],
              :weird_symlinks =>  {
                'system' => 'public/system',
                'pids'   => 'tmp/pids',
                'bundle' => 'vendor/bundle',
                'cache' => 'tmp/cache',
                'sockets'    => 'tmp/sockets'
              }
            }

But when using defaults, it could be as simple as

    { :name => 'my_app' }

Allowing the code above to become:

    config = Deploy::Configuration.new(:name => 'my_app')
    Deploy::Production.new(config).deploy

Going back to the first bit of code, I imagine the Deploy::Rails module to looks something like this:

    module Deploy
      # class per env
      class Rails
        include Deploy::SCM::Git
        include Deploy::DependencyMangement::Bundler
        include Deploy::AppServer::Unicorn
        include Deploy::Command::Rake

        def deploy
          update
          bundle
          symlink
          migrate
          restart
        end

        # replace 'cold'
        # prompt for yml configuration not in repo
        # or allow 'accept defaults' which can be read from a local file
        def setup
          build_directory_structure
          clone
          symlink
          bundle
          migrate
          cleanup #(fix permissions/ownership, touch assets)
          notify
        end
      end
    end

A rack app version could implement deploy with just update and restart.

You could imagine a scenario where PAAS customers could deploy with a lib/deploy/production.rb file that just contains:

    require 'deploy/engine_yard'

I imagine the roles to be something like this, allowing the module to be shared between applications

module MyDataCentre
  module Roles
    def web
      %w{10.1.1.1 10.1.1.2}
    end

    def app

    end

    def database

    end 
  end
end

All the modules would need to confirm to an interface per type, so switch unicorn for mongrel, or nginx for apache is trivial.

    module Deploy
      class SCM::Git < SCM
        def update

        end

        def clone

        end
      end
    end

    module Deploy
      class Unicorn < AppServer
        def start

        end

        def stop

        end

        def status

        end

        def restart

        end
      end
    end

Or maybe something like this

module Deploy

    class Production
      include SomeComannds
      include Dispatchable

      def deploy
        Dispatcher.new(self).start!
      end
    end

    class Dispatcher
      attr_accessor :state

      def initialize(deploy)
      end

      def start!
        commands.each { command.perform }
      end
    end

    class Command
      #as, on, in
      attr_accessor :identity, :target, :context, :command

     def perform
       #
     end
    end
  end

seenmyfate avatar Mar 11 '12 10:03 seenmyfate

@seenmyfate the modular concept (app server, scm, notifiers, autosymlinked dirs, etc) is exactly what I was trying to implement in my Chicken Soup gem. It was extremely tedious with Cap 2.x but I finally got it working. I'm really glad to see someone else is on the same page there.

I don't think that a high-level Rails module is something that should be included in the base project but rather as an addon to the gem deployrb-rails or whatever.

I also love your idea about having a high-level library for EngineYard. I did something similar in ChickenSoup for Heroku, where it didn't matter if you were deploying to Heroku or a Unix box, the high level commands did the correct thing. Again, something like that would (in my opinion) be better served as a deployrb-engineyard gem, but I agree with the principal.

I'm not sure how @leehambley feels but I agree with most of the above (as long as the base gem is sufficiently low-level) and that we make sure we don't run into an omniauth problem where we end up needing to extract other gems out at a later date because we thought it would be a good idea to include a bunch of stuff in the base gem.

Here are a couple of my high level feature ideas. The first one, I'm pretty adamant about. The second one, I think would be awesome and should (if we choose to implement it) frame our thinking during the initial development, but would probably require a lot of effort best left to a subsequent version.

Dual Repo Deploy

Most times you have configuration files for production which are not applicable to development and should not be made available to developers (currently in Chicken Soup I'm using symlinking but that is very tedious and prone to keeping them unversioned).

It would be great if we had a way to:

  • clone the repo for the code
  • clone the repo for the configuration files
  • symlink the configuration files to their correct locations
  • finish the deploy

On-Server Deploys

Another thing that I think we should look into is an option to run the deploy on the server. For every project I am currently working on, I do not need to send every command over. In all cases, the server can make the same determinations that my machine can regarding what to do during a deploy.

I feel that having the local developer's machine be the single point of failure during a deploy is a Bad Thing since, out of all the connections, theirs is probably the most prone to disruption. I've been in many situations where my connection has been flakey and a dropped connection would have meant a failed deploy. If we could deploy directly on the server (especially with a zero-downtime app server) a deploy would take 5 seconds and it would never fail due to a dropped connection.

I do not believe that that should be the only option, (and cannot be an option for deploying to something like Heroku) but I believe it would be an incredibly powerful feature for a lot of developers.

Just some food for thought.

jfelchner avatar Mar 15 '12 07:03 jfelchner

( Duplicated from https://github.com/capistrano/capistrano/issues/1 )

@jfelchner I'd love some help, but the plans I had in mind are a little too infant, as v3, for me means a rewrite. Here's some of the ideas I had in mind:

Proper execution of your task independently on multiple hosts.

role :web, %w{10.0.1.1 10.0.1.2}
task :something, [:web] do |role, host|
    log "Running #{roles} #{host}: something task"
end

Which would output:

Running web / 10.0.1.1
Running web / 10.0.1.2

(currently not possible due to the way cap handles forking)

And, moreover something like this:

role :web, %w{10.0.1.1 10.0.1.2}
task :something, [:web] do |role, host|
  in current_working_directory
    if Capistrano::Remote::File.exists? ( 'tmp/unicorn.pid' )
      run "service unicorn start", as: 'root'
    else
      run 'service unicorn restart' as: 'root'
    end
  end
end

(I would assume that the tasks would be namespaced something like Capistrano::Remote::, so one can simply use File, and refer to a remote file, example above for clarity.)

The important thing to note now is that this is possible, but only with shell script, and the task block can't switch per-host, so conditional logic doesn't work for us.

To avoid reimplementing the whole standard library as ::Remote, I would imagine that just the stuff in the ::File class would be more than enough to do almost everything useful.

Something to set the environmental variables for the channel

A single SSH connection can contain multiple channels, any of these channels can have their environmental variables set:

set :default_environment, { path: '/usr/local/bin', rbenv_version: '1.9.3-p125' }
task :something, [:web] do |role, host|
    puts capture('echo $PATH')
end

The important thing would be to notice with that, that we already have a similar feature in 2.x, but the generated command would look like: PATH=/usr/local/bin RBENV_VERSION=1.9.3-p125 echo $PATH, which is ugly. Setting this on the channel would be cleaner, however introduces a slight complication, for more see the underlying Net::SSH implementation documentation.

Some API for changing directory/env variables:*

task :something, [:web] do |role, host|
  in current_working_dir
    as :root do
       run "kill -USR2 $(cat tmp/unicorn.pid)"
    end
  end
end

I see two major bonuses from this, one is that it's very expressive, and the other is that when it fails the error message could easily read: "The attempt to run kill -USR2 $(cat tmp/unicorn.pid) as root failed. (Exit status 1)", I imagine there's a bunch of these that could be done.

Prompt responders

This comes up time and time again, I'd love to be albe to do something like this:

prompt_for_sudo__password = Proc.new do
  # Something here that responds to
  # the request, asking the user, reading
  # a file, or similar
end
task :restart, [:web] do |role, host|
  respond_to /Password/, with: prompt_for_sudo_password
    run "service unicorn restart", as: :root
  end
end

Streaming IO logging/output.

I haven't properly thought this through yet, but MiniTest does this beautifully, they allow an output formatter to register for hooks when a suite, or test starts or finishes. This TestResult object is then passed to a handler, with a load of information about the test, the response status, etc, etc, etc.

This mechanism allows them to have progress output from dots, verbose output, no output, Growl output, etc, etc, etc. I imagine a world where there's capistrano/pride

Better encapsulation for being embeddable

There's a class, undocuemented mostly called Capistrano::CLI, which can be used to run Capistrano from within another program without shelling out, I'd like to build on this. (Then we could, for example allow rake deploy, and avoid filling people's PATH with junk), as well as better facilitating

Better callbacks, and hooks

This speaks to the Streaming IO above, but it would be perfectly possible to have the campfire/irc/email/growl/etc/etc hooks implemented as loggers, which pass everything through that they are not interested in, but record/log the things they are interested in.

No more top-level DSL

Until now in this (rather long) reply, I've been sticking with the existing DSL, but I'd like to throw that away and just use classes, and methods. A significant portion of the Capistrano codebase is dedicated to our DSL, which is Rake-ish, but confusingly incompatible. for example opening a task in Rake to redefine it actually augments the existing implementation in Capistrano that redefines it.

Thor springs to mind, first for this, but there's a couple of outstanding issues with the current release that preclude me betting on it just yet.

My hope would be to do something like this:

module Capistrano
  module Remote

    class DeploySuite
      attr_reader :configuration
      def initialize(configuration)
        configuration = configuration
      end
      def deploy
        check
        start
        update
        finish
        test      
      end

      private

        def check
          on web_servers do |role, host|
             Dir.create releases_directory unless File.exists? releases_directory
          end
        end

    end

    module Servers

      class Unicorn

        def finish
          super
          start_or_restart_unicorn
        end

        private

        def start_or_restart_unicorn
          # Notice method `on` maps almost to `task`
          on web_servers, in: :sequence, wait: 5.seconds do |role, host|
            File.exists?('tmp/unicorn.pid') ? restart_unicorn : start_unicorn
          end
        end

      end

    end

  end
end

class MyDeploy < Capistrano::Remote::DeploySuite

  include Capistrano::Remote::Servers::Unicorn

end

MyDeploy.new(config).deploy

There's a lot to take in there, but that's what I had in mind, and it would be a very convenient and comfortable DSL, and would make the way things work much cleaner, then capistrano would be reduced to a set of very helpful tasks for performing remote operations on groups of machines, plus a logging/streaming API that makes it perfectly suited to actually distribute a bunch of defaults that really make sense.

You'll notice the use of on, that's something I'd be quite excited about, because on _______, in: :sequence, wait: 5.seconds would make a whole range of probles go away, one can imagine a few run-modes that could be useful here.

This alternative API also speaks to me because conditionally one would be able to include a DryRun mixin, which would nullify the other tasks (perhaps by changing the namespace, so that dry-run implementations are actually found.

Take dry-run, and testing seriously

I mentioned it briefly in the previous section, but I'd really like to encourage that people start and test their deployments, and by switching to a pure ruby API, and making things much easier to undersatnd for the average rubyist, we should be able to get to a really, really nice position where you can stub/mock/test-for expectations on your tasks.

The dry-run feature is about as good as it gets right now, but it has it's flaws, it doesn't know what to do with capture, it wouldn't be able to support the conditional statements, and it's a bit of a ghetto.

As for testing, when they would be simple Ruby methods, using Ruby inheritance, etc - they would be much easier to test, and much more robust.

tl;dr

I have some really, really grand plans, and I'd like to start soon, but honestly I simply don't know where to start. I've patched libssh, to make it easier to write a better underlying SSH driver, when the time comes for that, if it comes to it, I believe that our TaskDefinition object in the current code base is almost good enough, and otherwise, I think most things have to be thrown away. (But, it is a major rewrite-right!)

My only pre-conditions are:

  • Build for the best, target 1.9, and don't spare any effort to support 1.8 (I extend that to using the new syntaxes, etc (I'm open to negotiation if someone helps me build))
  • Build with the best, MRI, with Minitest, and Bundler, and co - these tools are what people really expect to see, know how to use, and they're awesome.
  • Integrate with Rails. I'm not a huge rails advocate, but a Railtie so you can do rails g install capistrano would be really, really nice.
  • Have awesome integration tests. (I've spiked a test implementation using DaemonController of something that boots a chrooted sshd in order to test against a real (chrooted) environment, this would allow for some really, really accurate integration tests, and would be a real asset to the project.)

leehambley avatar Mar 15 '12 08:03 leehambley

I'd like to clarify my position, in light of your inputs, how does this sound:

We treat deploy.rb as the toolkit (See my discussion on api on(hosts, &block), in(directory, &block), as(user, &block), with(environment, &block), etc.

We build a suite architecture into deploy.rb too, that is repeatable, (dry-)runnable, testable, and so-forth, and we build good, working out-of-the-box general purpose suites, with railties, and sinatra hooks, and all the rest, and make that Capistrano?

leehambley avatar Mar 15 '12 08:03 leehambley

@leehambley I think that's spot on, this is going to be really cool

seenmyfate avatar Mar 15 '12 18:03 seenmyfate

@seenmyfate Epic -- now we just need to find a way to build this damned thing!

leehambley avatar Mar 15 '12 18:03 leehambley

@jfelchner I see anything beyond the most common suites being external dependencies from the outset. So either a stand-alone gem in the style of deploy-my_suite ( and then require 'deploy/my_suite' ) or in the case of gems that typically include their own deployment tasks require my_gem/deploy/my_task.

seenmyfate avatar Mar 15 '12 18:03 seenmyfate

Some Feedback from me on your points @jfelchner

On server deploys

I think rake is better suited to this, almost all the time - one of the things I want to curb with this is people writing things in Capistrano that really ought to be rake tasks (notifications, cleanups, etc) - they're all rake tasks, and all part of [r,m]aking a working environment.

That's something we very often do wrong in ruby land, that's not to say there won't be a localhost adapter, which just shells out, but it's not a high priority for me, at least (but of course I won't code-out the possibility, based on my feelings that it's a bad idea)

Dual-Repo deploys

Sure, this should be easy for someone to implement ON TOP - we'll provide a similar callback as now "update code" - and make it more possible for the Git subsystem to checkout a repository, plus/minus submodules, in a directory at a particular ref, use it twice and one will have a dual-repo deploy. (i18n, plus code, or config plus code is the classic example)

Rails integration

I'm quite keen on keeping as much rails as possible OUT -- Rails is losing favor fast, and nowhere more so than my company, we deploy a lot of things in Rack, Node and plain HTML…

"Rails support" boils down to a) asset pipeline, b) migrations, c) railtie, d) restarting services -- all those things have an applicable "general" callback point, so there's absolutely no reason not to have a comprehensive suite of useful callbacks in place (even Sinatra uses Unicorn, even datamapper has a update schema concept, caches need to be ~~restarted~~ cleared, etc)

leehambley avatar Mar 15 '12 18:03 leehambley

@leehambley I'm going to start spiking on this tomorrow, will try to get something up here over the weekend.

seenmyfate avatar Mar 15 '12 18:03 seenmyfate