drbssh 0.5.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ .bundle
2
+ .vagrant
3
+ .yardoc
4
+ Gemfile.lock
5
+ doc
6
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source :rubygems
2
+
3
+ # Specify your gem's dependencies in rush.gemspec
4
+ gemspec
data/Guardfile ADDED
@@ -0,0 +1,7 @@
1
+ # -*- mode: ruby; tab-width: 2; indent-tabs-mode: nil -*-
2
+
3
+ guard 'rspec', :version => 2, :cli => '--color' do
4
+ watch(/^spec\/(.*)_spec.rb/)
5
+ watch(/^lib\/(.*)\.rb/) { |m| "spec/#{m[1]}_spec.rb" }
6
+ watch(/^spec\/spec_helper.rb/) { "spec" }
7
+ end
data/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2012 Kenneth Vestergaard
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # `drbssh`
2
+
3
+ A protocol implementation for Distributed Ruby (DRb), supporting SSH-connections.
4
+
5
+ ## Usage
6
+
7
+ ```ruby
8
+ DRb.start_service 'drbssh://'
9
+ remote = DRbObject.new_with_uri("drbssh://remote/")
10
+ remote.eval('1+1')
11
+
12
+ remote = DRbObject.new_with_uri("drbssh://remote/path/to/ruby")
13
+ ```
14
+
15
+ ## Description
16
+
17
+ `drbssh` makes it possible to create DRb-connections via SSH, with support for
18
+ bi-directional communication. In contrast to other DRb protocols, DRbSSH *requires*
19
+ that a local server is started before creating `DRbObject`s.
20
+
21
+ A newly-created `DRbObject` pointing at a remote server will be pointing at an
22
+ instance of `Binding`, representing the top-level of a newly-started Ruby
23
+ interpreter. The only interesting function exposed is `eval`.
24
+
25
+ ## Development
26
+
27
+ Uses a Vagrant VM with an Ubuntu-installation to serve as the remote end-point in tests.
28
+
29
+ ## TODOS
30
+
31
+ * Use Net::SSH if installed/possible?
data/Vagrantfile ADDED
@@ -0,0 +1,38 @@
1
+ # -*- mode: ruby -*-
2
+ # vi: set ft=ruby :
3
+
4
+ Vagrant::Config.run do |config|
5
+ # All Vagrant configuration is done here. The most common configuration
6
+ # options are documented and commented below. For a complete reference,
7
+ # please see the online documentation at vagrantup.com.
8
+
9
+ # Every Vagrant virtual environment requires a box to build off of.
10
+ config.vm.box = "ubuntu-11.10+zfs-64bit"
11
+
12
+ # The url from where the 'config.vm.box' box will be fetched if it
13
+ # doesn't already exist on the user's system.
14
+ # config.vm.box_url = "http://domain.com/path/to/above.box"
15
+
16
+ # Boot with a GUI so you can see the screen. (Default is headless)
17
+ # config.vm.boot_mode = :gui
18
+
19
+ # Assign this VM to a host-only network IP, allowing you to access it
20
+ # via the IP. Host-only networks can talk to the host machine as well as
21
+ # any other machines on the same network, but cannot be accessed (through this
22
+ # network interface) by any external networks.
23
+ # config.vm.network :hostonly, "33.33.33.10"
24
+
25
+ # Assign this VM to a bridged network, allowing you to connect directly to a
26
+ # network using the host's network device. This makes the VM appear as another
27
+ # physical device on your network.
28
+ # config.vm.network :bridged
29
+
30
+ # Forward a port from the guest to the host, which allows for outside
31
+ # computers to access the VM, whereas host only networking does not.
32
+ # config.vm.forward_port 80, 8080
33
+
34
+ # Share an additional folder to the guest VM. The first argument is
35
+ # an identifier, the second is the path on the guest to mount the
36
+ # folder, and the third is the path on the host to the actual folder.
37
+ # config.vm.share_folder "v-data", "/vagrant_data", "../data"
38
+ end
data/drbssh.gemspec ADDED
@@ -0,0 +1,22 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require 'rake'
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "drbssh"
7
+ s.version = "0.5.0"
8
+ s.platform = Gem::Platform::RUBY
9
+ s.authors = %w(kvs)
10
+ s.email = %w(kvs@binarysolutions.dk)
11
+ s.homepage = "https://github.com/kvs/drbssh"
12
+ s.summary = "An SSH protocol driver for DRb"
13
+ s.description = %q{Allows DRb to create and use an SSH-connection.}
14
+
15
+ s.files = `git ls-files`.split("\n")
16
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
+ s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
18
+ s.require_paths = ["lib"]
19
+
20
+ s.add_development_dependency "rspec", ["~> 2.8.0"]
21
+ s.add_development_dependency "guard-rspec"
22
+ end
data/lib/drbssh.rb ADDED
@@ -0,0 +1,262 @@
1
+ # -*- mode: ruby; tab-width: 4; indent-tabs-mode: t -*-
2
+
3
+ require 'drb'
4
+ require 'socket'
5
+
6
+ # DRb protocol handler for using a persistent SSH connection to a remote server. Creates a duplex
7
+ # connection so DRbUndumped objects can contact the initiating machine back through the same link.
8
+ #
9
+ # Contains all needed classes and no external dependencies, since this file will be read and sent
10
+ # to the remote end, to bootstrap its protocol support without requiring anything but Ruby
11
+ # installed.
12
+
13
+ module DRb
14
+
15
+ class DRbSSHProtocol
16
+ def self.server; @server; end
17
+
18
+ # Open a client connection to the server at +uri+, using configuration +config+, and return it.
19
+ def self.open(uri, config)
20
+ raise DRbServerNotFound, "need to run a DRbSSH server first" if @server.nil? or @server.closed?
21
+
22
+ DRb.thread['DRbSSHLocalClient'] || DRbSSHRemoteClient.new(uri, @server)
23
+ end
24
+
25
+ # Open a server listening at +uri+, using configuration +config+, and return it.
26
+ def self.open_server(uri, config)
27
+ @server = nil if !@server.nil? and @server.closed?
28
+
29
+ raise DRbConnError, "server already running with different uri" if !@server.nil? and @server.uri != uri
30
+
31
+ @server ||= DRbSSHServer.new(uri, config)
32
+ end
33
+
34
+ # Parse +uri+ into a [uri, option] pair.
35
+ def self.uri_option(uri, config)
36
+ host, path = split_uri(uri)
37
+ host ||= Socket.gethostname
38
+ [ "drbssh://#{host}/#{path}", nil ]
39
+ end
40
+
41
+ # Split URI into component pairs
42
+ def self.split_uri(uri)
43
+ if uri.match('^drbssh://([^/?]+)?(?:/(.+))?$')
44
+ [ $1, $2 ]
45
+ else
46
+ raise DRbBadScheme,uri unless uri =~ /^drbssh:/
47
+ raise DRbBadURI, "can't parse uri: " + uri
48
+ end
49
+ end
50
+ end
51
+ DRbProtocol.add_protocol(DRbSSHProtocol)
52
+
53
+
54
+ # Base class for the DRbSSH clients.
55
+ class DRbSSHClient
56
+ attr_reader :receiveq
57
+ attr_reader :sendq
58
+ attr_reader :read_fd
59
+ attr_reader :write_fd
60
+
61
+ def initialize(server)
62
+ @receiveq, @sendq = Queue.new, Queue.new
63
+ @write_fd.sync = true
64
+
65
+ server.client_queue.push(self)
66
+ end
67
+
68
+ def send_request(ref, msg_id, arg, b)
69
+ @sendq.push(['req', [ref, msg_id, arg, b]])
70
+ end
71
+
72
+ def recv_reply
73
+ @receiveq.pop
74
+ end
75
+
76
+ def alive?
77
+ !self.read_fd.closed? && !self.write_fd.closed?
78
+ end
79
+ end
80
+
81
+
82
+ # DRbSSH remote client - does the heavy lifting of SSH'ing to a remote server and bootstrapping
83
+ # its Ruby interpreter for DRb communication.
84
+ class DRbSSHRemoteClient < DRbSSHClient
85
+ # Create an SSH-connection to +uri+, and spawn a server, so client has something to talk to
86
+ def initialize(uri, server)
87
+ # child-to-parent, parent-to-child
88
+ ctp_rd, ctp_wr = IO.pipe
89
+ ptc_rd, ptc_wr = IO.pipe
90
+
91
+ host, cmd = DRbSSHProtocol.split_uri(uri)
92
+
93
+ # Read the source-code for this file, and add bits for initialising the remote side.
94
+ # Since DRbSSHServer is doing all the filedescriptor read/writing, we need to start
95
+ # a DRbSSHLocalClient immediately.
96
+ self_code = <<-EOT
97
+ #{File.read(__FILE__)};
98
+ DRb.start_service("#{uri}", binding)
99
+ DRb.thread['DRbSSHLocalClient'] = DRb::DRbSSHLocalClient.new(DRb::DRbSSHProtocol.server)
100
+ DRb.thread.join
101
+ EOT
102
+
103
+ # Fork to create an SSH child-process
104
+ if fork.nil?
105
+ # In child - cleanup filehandles, reopen stdin/stdout, and exec ssh to connect to remote
106
+
107
+ ctp_rd.close
108
+ ptc_wr.close
109
+
110
+ $stdin.reopen(ptc_rd)
111
+ $stdout.reopen(ctp_wr)
112
+
113
+ cmd = ['ruby'] if cmd.nil? or cmd.empty?
114
+
115
+ # exec Ruby on remote end, and read bootstrap code.
116
+ exec("ssh", "-oBatchMode=yes", "-T", host, "exec", *cmd, '-e', "\"eval STDIN.read(#{self_code.bytesize})\"")
117
+ exit
118
+ else
119
+ # In parent - cleanup filehandles, write bootstrap-code, and hand over to superclass.
120
+
121
+ ctp_wr.close
122
+ ptc_rd.close
123
+
124
+ # Bootstrap remote Ruby.
125
+ ptc_wr.write(self_code)
126
+
127
+ @read_fd, @write_fd = ctp_rd, ptc_wr
128
+
129
+ super(server)
130
+ end
131
+ end
132
+
133
+ # Close client.
134
+ def close
135
+ # Closing the filedescriptors should trigger an IOError in the server-thread
136
+ # waiting, which makes it close the client attached.
137
+ self.read_fd.close
138
+ self.write_fd.close
139
+ end
140
+ end
141
+
142
+
143
+ # DRbSSH client used to contact local objects - used on remote side.
144
+ class DRbSSHLocalClient < DRbSSHClient
145
+ # Use stdin/stdout to talk with the local side of an SSH-connection.
146
+ def initialize(server)
147
+ @read_fd, @write_fd = $stdin, $stdout
148
+
149
+ super(server)
150
+ end
151
+
152
+ # Kill Ruby if client is asked to close.
153
+ def close
154
+ Kernel.exit 0
155
+ end
156
+ end
157
+
158
+
159
+ # Common DRb protocol server for DRbSSH. Waits on incoming clients on a thread-safe `Queue`,
160
+ # and spawns a new connection handler for each.
161
+ class DRbSSHServer
162
+ attr_reader :uri
163
+ attr_reader :client_queue
164
+
165
+ # Create new server.
166
+ def initialize(uri, config)
167
+ @uri = uri
168
+ @config = config
169
+ @client_queue = Queue.new
170
+ @clients = []
171
+ end
172
+
173
+ # Wait for clients to register themselves on the client_queue.
174
+ def accept
175
+ client = @client_queue.pop
176
+ @clients << DRbSSHServerConn.new(uri, @config, client)
177
+ @clients.last
178
+ end
179
+
180
+ # Close server by closing all clients.
181
+ def close
182
+ @clients.map(&:close)
183
+ @clients = nil
184
+ end
185
+
186
+ # Server is closed if +close+ has been called earlier.
187
+ def closed?
188
+ @clients.nil?
189
+ end
190
+ end
191
+
192
+
193
+ # DRbSSH protocol server per-connection class. Handles client-to-client communications
194
+ # by utilizing thread-safe Queue's for the input and output, and by adding a small
195
+ # 'rep' or 'req' packet before sending, so we can have two-way DRb duplexed over a
196
+ # single pair of filedescriptors.
197
+ class DRbSSHServerConn
198
+ attr_reader :uri
199
+
200
+ # Create a new server-connection for the specified +client+.
201
+ def initialize(uri, config, client)
202
+ @uri = uri
203
+ @client = client
204
+ @srv_requestq = Queue.new
205
+
206
+ msg = DRbMessage.new(config)
207
+
208
+ # Read-thread
209
+ Thread.new do
210
+ # Read from client, and delegate request/reply to the correct place.
211
+ begin
212
+ loop do
213
+ type = msg.load(client.read_fd)
214
+ if type == 'req'
215
+ @srv_requestq.push(msg.recv_request(client.read_fd))
216
+ else
217
+ client.receiveq.push(msg.recv_reply(client.read_fd))
218
+ end
219
+ end
220
+ rescue
221
+ client.close
222
+ end
223
+ end
224
+
225
+ # Write-thread
226
+ Thread.new do
227
+ # Wait for outgoing data on send queue, and add header-packet before
228
+ # writing.
229
+ begin
230
+ loop do
231
+ type, data = client.sendq.pop
232
+
233
+ client.write_fd.write(msg.dump(type))
234
+
235
+ if type == 'req'
236
+ msg.send_request(client.write_fd, *data)
237
+ else
238
+ msg.send_reply(client.write_fd, *data)
239
+ end
240
+ end
241
+ rescue
242
+ client.close
243
+ end
244
+ end
245
+ end
246
+
247
+ # Delegate shutdown to client.
248
+ def close
249
+ @client.close
250
+ end
251
+
252
+ # Wait for a request to appear on the request-queue
253
+ def recv_request
254
+ @srv_requestq.pop
255
+ end
256
+
257
+ # Queue client-reply
258
+ def send_reply(succ, result)
259
+ @client.sendq.push(['rep', [succ, result]])
260
+ end
261
+ end
262
+ end
@@ -0,0 +1,77 @@
1
+ # -*- mode: ruby; tab-width: 4; indent-tabs-mode: t -*-
2
+
3
+ require 'drbssh'
4
+
5
+ describe DRb::DRbSSHProtocol do
6
+ it "responds to drbssh:// URIs" do
7
+ described_class.uri_option("drbssh://localhost/ruby", {}).should eq [ "drbssh://localhost/ruby", nil ]
8
+ described_class.uri_option("drbssh://localhost", {}).should eq [ "drbssh://localhost/", nil ]
9
+ described_class.uri_option("drbssh://", {}).first.should match(/^drbssh:\/\//)
10
+
11
+ expect { described_class.uri_option("druby://localhost/ruby", {}) }.to raise_exception DRb::DRbBadScheme
12
+ end
13
+
14
+ it "starts and stops when requested" do
15
+ expect { DRb.current_server }.to raise_exception DRb::DRbServerNotFound
16
+ DRb.start_service("drbssh://localhost")
17
+ DRb.current_server.instance_variable_get("@protocol").should be_an_instance_of DRb::DRbSSHServer
18
+ DRb.stop_service
19
+ expect { DRb.current_server }.to raise_exception DRb::DRbServerNotFound
20
+ end
21
+
22
+ it "disallows running two drbssh-servers" do
23
+ DRb.start_service("drbssh://localhost")
24
+ expect { DRb.start_service("drbssh://localhost2") }.to raise_exception DRb::DRbConnError
25
+ end
26
+
27
+ it "creates DRbObjects with a URI pointed to itself" do
28
+ DRb.start_service("drbssh://localhost")
29
+ DRb::DRbObject.new({}.extend(DRbUndumped)).__drburi.should eq 'drbssh://localhost'
30
+ DRb.stop_service
31
+ end
32
+
33
+ it "connects to a remote Ruby" do
34
+ DRb.start_service("drbssh://localhost")
35
+ drb = DRbObject.new_with_uri("drbssh://vagrant-zfs/ruby")
36
+ drb.should be_an_instance_of DRb::DRbObject
37
+ drb.__drburi.should eq "drbssh://vagrant-zfs/ruby"
38
+
39
+ drb.eval("1+1").should eq 2
40
+ drb.eval("`hostname`").should eq "vagrant-ubuntu-oneiric\n"
41
+ drb.eval("{ foo: :bar }.extend DRb::DRbUndumped").should be_an_instance_of DRb::DRbObject
42
+ DRb.stop_service
43
+ end
44
+
45
+ it "allows two-way communication" do
46
+ DRb.start_service("drbssh://localhost")
47
+
48
+ drb = DRbObject.new_with_uri("drbssh://vagrant-zfs/ruby")
49
+
50
+ remote_hash = drb.eval("@a = {}.extend(DRb::DRbUndumped)")
51
+
52
+ # remote server gets started in main thread, with binding as front object.
53
+ # server spawns thread to run in, and another thread to run client-connection in.
54
+ # client connects, sends message,
55
+
56
+ # Set local Proc in remote hash, re-fetch it and call it. Works without two-way comms
57
+ remote_hash["a"] = lambda { return 1 }
58
+ drb.eval("@a['a']").call.should eq 1
59
+
60
+ # Call same Proc in a remote context. This means establishing a connection to the local side, since
61
+ # the Proc is really a DRbObject on the remote side.
62
+ drb.eval("@a['a'].call").should eq 1
63
+
64
+ DRb.stop_service
65
+ end
66
+
67
+ it "reconnects when connection has been terminated" do
68
+ DRb.start_service("drbssh://localhost")
69
+ drb = DRbObject.new_with_uri("drbssh://vagrant-zfs/ruby")
70
+ drb.eval("`hostname`").should eq "vagrant-ubuntu-oneiric\n"
71
+ pid = drb.eval('$$')
72
+
73
+ expect { drb.eval('Kernel.exit! 0') }.to raise_exception IOError
74
+
75
+ drb.eval('$$').should_not eq pid # should create new connection
76
+ end
77
+ end
@@ -0,0 +1 @@
1
+ # -*- mode: ruby; tab-width: 4; indent-tabs-mode: t -*-
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: drbssh
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.5.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - kvs
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-03-19 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rspec
16
+ requirement: &70199265074880 !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: 2.8.0
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: *70199265074880
25
+ - !ruby/object:Gem::Dependency
26
+ name: guard-rspec
27
+ requirement: &70199265073940 !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ! '>='
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: *70199265073940
36
+ description: Allows DRb to create and use an SSH-connection.
37
+ email:
38
+ - kvs@binarysolutions.dk
39
+ executables: []
40
+ extensions: []
41
+ extra_rdoc_files: []
42
+ files:
43
+ - .gitignore
44
+ - Gemfile
45
+ - Guardfile
46
+ - LICENSE
47
+ - README.md
48
+ - Vagrantfile
49
+ - drbssh.gemspec
50
+ - lib/drbssh.rb
51
+ - spec/drbssh_spec.rb
52
+ - spec/spec_helper.rb
53
+ homepage: https://github.com/kvs/drbssh
54
+ licenses: []
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ none: false
61
+ requirements:
62
+ - - ! '>='
63
+ - !ruby/object:Gem::Version
64
+ version: '0'
65
+ required_rubygems_version: !ruby/object:Gem::Requirement
66
+ none: false
67
+ requirements:
68
+ - - ! '>='
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubyforge_project:
73
+ rubygems_version: 1.8.11
74
+ signing_key:
75
+ specification_version: 3
76
+ summary: An SSH protocol driver for DRb
77
+ test_files:
78
+ - spec/drbssh_spec.rb
79
+ - spec/spec_helper.rb