/
storage.rb
336 lines (245 loc) · 7.3 KB
/
storage.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#--
# Copyright (c) 2005-2012, John Mettraux, jmettraux@gmail.com
#
# 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:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# 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.
#
# Made in Japan.
#++
require 'fileutils'
require 'beanstalk-client'
#require 'ruote/storage/base'
module Ruote
module Beanstalk
#
# An error class just for BsStorage.
#
class StorageError < RuntimeError
end
#
# This ruote storage can be used in two modes : client and server.
#
# Beanstalk is the medium.
#
# == client
#
# The storage is pointed at a beanstalk queue
#
# engine = Ruote::Engine.new(
# Ruote::Worker.new(
# Ruote::Beanstalk::Storage.new('127.0.0.1:11300', opts)))
#
# All the operations(put, get, get_many, ...) of the storage are done
# by a server, connected to the same beanstalk queue.
#
# == server
#
# The storage point to a beanstalk queue and receives orders from clients
# via the queue.
#
# Ruote::Beanstalk::Storage.new(':11300', 'ruote_work', :fork => true)
#
# Note the directory passed as a string. When in server mode, this storage
# uses an embedded Ruote::FsStorage for the actual storage.
#
# The :fork => true lets the storage start and adjacent OS process containing
# the Beanstalk server. The storage takes care of stopping the beanstalk
# server when the Ruby process exits.
#
class Storage
include Ruote::StorageBase
def initialize(uri, directory=nil, options=nil)
@uri, address, port = split_uri(uri)
directory, @options = if directory.nil?
[ nil, {} ]
elsif directory.is_a?(Hash)
[ nil, directory ]
else
[ directory, options || {} ]
end
@cloche = nil
if directory
#
# run embedded Ruote::FsStorage
require 'rufus/cloche'
FileUtils.mkdir_p(directory)
@cloche = Rufus::Cloche.new(
:dir => directory, :nolock => @options['cloche_nolock'])
end
if fork_opts = @options[:fork]
#
# run beanstalk in a forked process
fork_opts = fork_opts.is_a?(Hash) ? fork_opts : {}
fork_opts = { :address => address, :port => port }.merge(fork_opts)
Ruote::Beanstalk.fork(fork_opts)
sleep 0.1
end
replace_engine_configuration(@options)
serve if @cloche
end
# One catch : will return [] in case of [network] error
#
def get_msgs
super rescue []
end
# One catch : will return true (failure) in case of [network] error
#
def reserve(doc)
super(doc) rescue true
end
def put(doc, opts={})
doc.merge!('put_at' => Ruote.now_to_utc_s)
return @cloche.put(doc, opts) if @cloche
r = operate('put', [ doc ])
return r unless r.nil?
doc['_rev'] = (doc['_rev'] || -1) + 1 if opts[:update_rev]
nil
end
def get(type, key)
return @cloche.get(type, key) if @cloche
operate('get', [ type, key ])
end
def delete(doc)
return @cloche.delete(doc) if @cloche
operate('delete', [ doc ])
end
def get_many(type, key=nil, opts={})
return operate('get_many', [ type, key, opts ]) unless @cloche
if key
key = Array(key).collect { |k|
k[0..6] == '(?-mix:' ? Regexp.new(k[7..-2]) : "!#{k}"
} if key
end
# assuming /!#{wfid}$/...
@cloche.get_many(type, key, opts)
end
def ids(type)
return @cloche.ids(type) if @cloche
operate('ids', [ type ])
end
def purge!
if @cloche
FileUtils.rm_rf(@cloche.dir)
else
operate('purge!', [])
end
end
def dump(type)
get_many(type)
end
def shutdown
Thread.list.each do |t|
t.keys.each do |k|
next unless k.to_s.match(CONN_KEY)
t[k].close
t[k] = nil
end
end
end
def close
shutdown
end
# Mainly used by ruote's test/unit/ut_17_storage.rb
#
def add_type(type)
# nothing to do
end
# Nukes a db type and reputs it(losing all the documents that were in it).
#
def purge_type!(type)
if @cloche
@cloche.purge_type!(type)
else
operate('purge_type!', [ type ])
end
end
protected
CONN_KEY = 'ruote-beanstalk-connection'
TUBE_NAME = 'ruote-storage-commands'
def split_uri(uri)
uri = ':' if uri == ''
address, port = uri.split(':')
address = '127.0.0.1' if address.strip == ''
port = 11300 if port.strip == ''
[ "#{address}:#{port}", address, port ]
end
def connection
c = Thread.current[CONN_KEY]
#begin
# c.stats
# return c
#rescue Exception => e
# c = nil
#end if c
# keeping around the idea around
return c if c
c = ::Beanstalk::Connection.new(@uri, TUBE_NAME)
c.ignore('default')
Thread.current[CONN_KEY] = c
end
def operate(command, params)
client_id = "BsStorage-#{Thread.current.object_id}-#{$$}"
timestamp = Time.now.to_f.to_s
con = connection
con.put(Rufus::Json.encode([ command, params, client_id, timestamp ]))
con.watch(client_id)
con.ignore(TUBE_NAME)
result = nil
loop do
job = nil
begin
job = con.reserve
rescue Exception => e
# probably our timeout
break
end
job.delete
result, ts = Rufus::Json.decode(job.body)
break if ts == timestamp # hopefully
end
if result.is_a?(Array) && result.first == 'error'
raise ArgumentError.new(result.last) if result[1] == 'ArgumentError'
raise StorageError.new(result.last)
end
result
end
COMMANDS = %w[ put get get_many delete ids purge! purge_type! dump ]
def serve
con = connection
loop do
job = con.reserve
job.delete
command, params, client_id, timestamp = Rufus::Json.decode(job.body)
result = begin
if COMMANDS.include?(command)
send(command, *params)
else
[ 'error', 'UnknownCommand', command ]
end
rescue Exception => e
#p e
#e.backtrace.each { |l| puts l }
[ 'error', e.class.to_s, e.to_s ]
end
con.use(client_id)
con.put(Rufus::Json.encode([ result, timestamp ]))
end
end
end
end
end