This repository has been archived by the owner on Jul 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 164
/
genghis.rb
executable file
·1110 lines (902 loc) · 622 KB
/
genghis.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
#
# Genghis v2.3.11
#
# The single-file MongoDB admin app
#
# http://genghisapp.com
#
# @author Justin Hileman <justin@justinhileman.info>
#
module Genghis
VERSION = "2.3.11"
end
GENGHIS_VERSION = Genghis::VERSION
require 'mongo'
require 'json'
module Genghis
class JSON
class << self
def as_json(object)
enc(object, Array, Hash, BSON::OrderedHash, Genghis::Models::Query)
end
def encode(object)
as_json(object).to_json
end
def decode(str)
dec(::JSON.parse(str))
end
private
def enc(o, *a)
o = o.to_s if o.is_a? Symbol
fail "invalid: #{o.inspect}" unless a.empty? or a.include? o.class
case o
when Genghis::Models::Query then enc(o.as_json)
when Array then o.map { |e| enc(e) }
when Hash then enc_hash(o.clone)
when Time then thunk('ISODate', enc_time(o))
when Regexp then thunk('RegExp', {'$pattern' => o.source, '$flags' => enc_re_flags(o.options)})
when BSON::ObjectId then thunk('ObjectId', o.to_s)
when BSON::DBRef then db_ref(o)
when BSON::Binary then thunk('BinData', {'$subtype' => o.subtype, '$binary' => enc_bin_data(o)})
else o
end
end
def enc_time(o)
# strip trailing microsecond zeros, because wtf.
o.strftime('%FT%T.%LZ').sub(/\.?[0]{0,3}Z$/, 'Z')
end
def enc_hash(o)
o.keys.each { |k| o[k] = enc(o[k]) }
o
end
def thunk(name, value)
{'$genghisType' => name, '$value' => value }
end
def enc_re_flags(opt)
((opt & Regexp::MULTILINE != 0) ? 'm' : '') + ((opt & Regexp::IGNORECASE != 0) ? 'i' : '')
end
def enc_bin_data(o)
Base64.strict_encode64(o.to_s)
end
def db_ref(o)
o = o.to_hash
{'$ref' => o['$ns'], '$id' => enc(o['$id'])}
end
def dec(o)
case o
when Array then o.map { |e| dec(e) }
when Hash then
case o['$genghisType']
when 'ObjectId' then mongo_object_id o['$value']
when 'ISODate' then mongo_iso_date o['$value']
when 'RegExp' then mongo_reg_exp o['$value']
when 'BinData' then mongo_bin_data o['$value']
else o.merge(o) { |k, v| dec(v) }
end
else o
end
end
def dec_re_flags(flags)
f = flags || ''
(f.include?('m') ? Regexp::MULTILINE : 0) | (f.include?('i') ? Regexp::IGNORECASE : 0)
end
def mongo_object_id(value)
value.nil? ? BSON::ObjectId.new : BSON::ObjectId.from_string(value)
end
def mongo_iso_date(value)
return Time.now if value.nil?
# because Rails overrides DateTime.to_time to return a DateTime. Grr.
d = DateTime.parse(value)
Time.utc(d.year, d.month, d.day, d.hour, d.min, d.sec + d.sec_fraction)
end
def mongo_reg_exp(value)
Regexp.new(value['$pattern'], dec_re_flags(value['$flags']))
end
def mongo_bin_data(value)
BSON::Binary.new(Base64.decode64(value['$binary']), value['$subtype'])
end
end
end
end
require 'sinatra'
module Genghis
class Exception < ::Exception
end
class MalformedDocument < Exception
def http_status; 400 end
def initialize(msg=nil)
@msg = msg
end
def message
@msg || 'Malformed document'
end
end
class NotFound < Exception
def http_status; 404 end
def message
'Not found'
end
end
class AlreadyExists < Exception
def http_status; 400 end
end
class ServerNotFound < NotFound
def initialize(name)
@name = name
end
def message
"Server '#{@name}' not found"
end
end
class ServerAlreadyExists < AlreadyExists
def initialize(name)
@name = name
end
def message
"Server '#{@name}' already exists"
end
end
class DatabaseNotFound < NotFound
def initialize(server, name)
@server = server
@name = name
end
def message
"Database '#{@name}' not found on '#{@server.name}'"
end
end
class DatabaseAlreadyExists < AlreadyExists
def initialize(server, name)
@server = server
@name = name
end
def message
"Database '#{@name}' already exists on '#{@server.name}'"
end
end
class CollectionNotFound < NotFound
def initialize(database, name)
@database = database
@name = name
end
def message
"Collection '#{@name}' not found in '#{@database.name}'"
end
end
class GridFSNotFound < CollectionNotFound
def message
"GridFS collection '#{@name}' not found in '#{@database.name}'"
end
end
class CollectionAlreadyExists < AlreadyExists
def initialize(database, name)
@database = database
@name = name
end
def message
"Collection '#{@name}' already exists in '#{@database.name}'"
end
end
class DocumentNotFound < NotFound
def initialize(collection, doc_id)
@collection = collection
@doc_id = doc_id
end
def message
"Document '#{@doc_id}' not found in '#{@collection.name}'"
end
end
class GridFileNotFound < DocumentNotFound
def message
"GridFS file '#{@doc_id}' not found"
end
end
end
require 'base64'
module Genghis
module Models
class Collection
def initialize(collection)
@collection = collection
end
def name
@collection.name
end
def drop!
@collection.drop
end
def insert(data)
begin
id = @collection.insert data
rescue Mongo::OperationFailure => e
# going out on a limb here and assuming all of these are malformed...
raise Genghis::MalformedDocument.new(e.result['errmsg'])
end
@collection.find_one('_id' => id)
end
def remove(doc_id)
query = {'_id' => thunk_mongo_id(doc_id)}
raise Genghis::DocumentNotFound.new(self, doc_id) unless @collection.find_one(query)
@collection.remove query
end
def update(doc_id, data)
begin
document = @collection.find_and_modify \
:query => {'_id' => thunk_mongo_id(doc_id)},
:update => data,
:new => true
rescue Mongo::OperationFailure => e
# going out on a limb here and assuming all of these are malformed...
raise Genghis::MalformedDocument.new(e.result['errmsg'])
end
raise Genghis::DocumentNotFound.new(self, doc_id) unless document
document
end
def documents(query={}, page=1)
Query.new(@collection, query, page)
end
def [](doc_id)
doc = @collection.find_one('_id' => thunk_mongo_id(doc_id))
raise Genghis::DocumentNotFound.new(self, doc_id) unless doc
doc
end
def put_file(data)
file = data.delete('file') or raise Genghis::MalformedDocument.new 'Missing file.'
opts = {}
data.each do |k, v|
case k
when 'filename'
opts[:filename] = v
when 'metadata'
opts[:metadata] = v unless v.empty?
when '_id'
opts[:_id] = v
when 'contentType'
opts[:content_type] = v
else
raise Genghis::MalformedDocument.new "Unexpected property: '#{k}'"
end
end
id = grid.put(decode_file(file), opts)
self[id]
end
def get_file(doc_id)
begin
doc = grid.get(thunk_mongo_id(doc_id))
rescue Mongo::GridFileNotFound
raise Genghis::GridFileNotFound.new(self, doc_id)
end
raise Genghis::DocumentNotFound.new(self, doc_id) unless doc
raise Genghis::GridFileNotFound.new(self, doc_id) unless is_grid_file?(doc)
doc
end
def delete_file(doc_id)
begin
grid.get(thunk_mongo_id(doc_id))
rescue Mongo::GridFileNotFound
raise Genghis::GridFileNotFound.new(self, doc_id)
end
res = grid.delete(thunk_mongo_id(doc_id))
raise Genghis::Exception.new res['err'] unless res['ok']
end
def as_json(*)
{
:id => @collection.name,
:name => @collection.name,
:count => @collection.count,
:indexes => @collection.index_information.values,
:stats => @collection.stats,
}
end
def to_json(*)
as_json.to_json
end
private
def thunk_mongo_id(doc_id)
if doc_id.is_a? BSON::ObjectId
doc_id
elsif (doc_id[0..0] == '~')
doc_id = Base64.decode64(doc_id[1..-1])
::Genghis::JSON.decode("{\"_id\":#{doc_id}}")['_id']
else
doc_id =~ /^[a-f0-9]{24}$/i ? BSON::ObjectId(doc_id) : doc_id
end
end
def is_grid_collection?
name.end_with? '.files'
end
def grid
Genghis::GridFSNotFound.new(@collection.db, name) unless is_grid_collection?
@grid ||= Mongo::Grid.new(@collection.db, name.sub(/\.files$/, ''))
end
def is_grid_file?(doc)
!! doc['chunkSize']
end
def decode_file(data)
unless data =~ /^data:[^;]+;base64,/
raise Genghis::MalformedDocument.new 'File must be a base64 encoded data: URI'
end
Base64.strict_decode64(data.sub(/^data:[^;]+;base64,/, '').strip)
rescue ArgumentError
raise Genghis::MalformedDocument.new 'File must be a base64 encoded data: URI'
end
end
end
end
module Genghis
module Models
class Database
def initialize(client, name)
@client = client
@name = name
end
def name
database.name
end
def drop!
database.connection.drop_database(database.name)
end
def create_collection(coll_name)
raise Genghis::CollectionAlreadyExists.new(self, coll_name) if database.collection_names.include? coll_name
database.create_collection coll_name rescue raise Genghis::MalformedDocument.new('Invalid collection name')
Collection.new(database[coll_name])
end
def collections
@collections ||= database.collections.map { |c| Collection.new(c) unless system_collection?(c) }.compact
end
def [](coll_name)
raise Genghis::CollectionNotFound.new(self, coll_name) unless database.collection_names.include? coll_name
Collection.new(database[coll_name])
end
def as_json(*)
{
:id => database.name,
:name => database.name,
:count => collections.count,
:collections => collections.map { |c| c.name },
:stats => stats,
}
rescue Mongo::InvalidNSName => e
{
:id => @name,
:name => @name,
:error => e.message,
}
end
def to_json(*)
as_json.to_json
end
private
def database
@database ||= @client[@name]
end
def info
@info ||= begin
name = database.name
database.connection['admin'].command({:listDatabases => true})['databases'].detect do |db|
db['name'] == name
end
end
end
def stats
@stats ||= database.command({:dbStats => true})
end
def system_collection?(coll)
[
Mongo::DB::SYSTEM_NAMESPACE_COLLECTION,
Mongo::DB::SYSTEM_INDEX_COLLECTION,
Mongo::DB::SYSTEM_PROFILE_COLLECTION,
Mongo::DB::SYSTEM_USER_COLLECTION,
Mongo::DB::SYSTEM_JS_COLLECTION
].include?(coll.name)
end
end
end
end
module Genghis
module Models
class Query
PAGE_LIMIT = 50
def initialize(collection, query={}, page=1)
@collection = collection
@page = page
@query = query
end
def as_json(*)
{
:count => documents.count,
:page => @page,
:pages => pages,
:per_page => PAGE_LIMIT,
:offset => offset,
:documents => documents.to_a
}
end
def to_json(*)
as_json.to_json
end
private
def pages
[0, (documents.count / PAGE_LIMIT.to_f).ceil].max
end
def offset
PAGE_LIMIT * (@page - 1)
end
def documents
@documents ||= @collection.find(@query, :limit => PAGE_LIMIT, :skip => offset)
end
end
end
end
module Genghis
module Models
class Server
attr_reader :name
attr_reader :dsn
attr_reader :error
attr_accessor :default
@default = false
def initialize(dsn)
dsn = 'mongodb://'+dsn unless dsn.include? '://'
begin
dsn, uri = get_dsn_and_uri(extract_extra_options(dsn))
# name this server something useful
name = uri.host
if user = uri.auths.map { |a| a[:username] || a['username'] }.first
name = "#{user}@#{name}"
end
name = "#{name}:#{uri.port}" unless uri.port == 27017
if db = uri.auths.map { |a| a[:db_name] || a['db_name'] }.first
unless db == 'admin'
name = "#{name}/#{db}"
@db = db
end
end
@name = name
rescue Mongo::MongoArgumentError
@error = 'Malformed server DSN'
@name = dsn
end
@dsn = dsn
end
def create_database(db_name)
raise Genghis::DatabaseAlreadyExists.new(self, db_name) if db_exists? db_name
begin
client[db_name]['__genghis_tmp_collection__'].drop
rescue Mongo::InvalidNSName
raise Genghis::MalformedDocument.new('Invalid database name')
end
Database.new(client, db_name)
end
def databases
info['databases'].map { |db| Database.new(client, db['name']) }
end
def [](db_name)
raise Genghis::DatabaseNotFound.new(self, db_name) unless db_exists? db_name
Database.new(client, db_name)
end
def as_json(*)
json = {
:id => @name,
:name => @name,
:editable => !@default,
}
if @error
json.merge!({:error => @error})
else
begin
client
info
rescue Mongo::AuthenticationError => e
json.merge!({:error => "Authentication error: #{e.message}"})
rescue Mongo::ConnectionFailure => e
json.merge!({:error => "Connection error: #{e.message}"})
rescue Mongo::OperationFailure => e
json.merge!({:error => "Connection error: #{e.result['errmsg']}"})
else
json.merge!({
:size => info['totalSize'].to_i,
:count => info['databases'].count,
:databases => info['databases'].map { |db| db['name'] },
})
end
end
json
end
def to_json(*)
as_json.to_json
end
private
def get_dsn_and_uri(dsn)
[dsn, ::Mongo::URIParser.new(dsn)]
rescue Mongo::MongoArgumentError => e
raise e unless e.message.include? "MongoDB URI must include username"
# We'll try one more time...
dsn = dsn.sub(%r{/?$}, '/admin')
[dsn, ::Mongo::URIParser.new(dsn)]
end
def extract_extra_options(dsn)
host, opts = dsn.split('?', 2)
keep = {}
@opts = {}
Rack::Utils.parse_query(opts).each do |opt, value|
case opt
when 'replicaSet'
keep[opt] = value
when 'connectTimeoutMS'
unless value =~ /^\d+$/
raise Mongo::MongoArgumentError.new("Unexpected #{opt} option value: #{value}")
end
@opts[:connect_timeout] = (value.to_f / 1000)
when 'ssl'
unless value == 'true'
raise Mongo::MongoArgumentError.new("Unexpected #{opt} option value: #{value}")
end
@opts[opt.to_sym] = true
else
raise Mongo::MongoArgumentError.new("Unknown option #{opt}")
end
end
opts = Rack::Utils.build_query keep
opts.empty? ? host : [host, opts].join('?')
end
def client
@client ||= Mongo::MongoClient.from_uri(@dsn, {:connect_timeout => 1, :w => 1}.merge(@opts))
rescue OpenSSL::SSL::SSLError => e
raise Mongo::ConnectionFailure.new('SSL connection error')
rescue StandardError => e
raise Mongo::ConnectionFailure.new(e.message)
end
def info
@info ||= begin
if @db.nil?
client['admin'].command({:listDatabases => true})
else
stats = client[@db].command(:dbStats => true)
{
'databases' => [{'name' => @db}],
'totalSize' => stats['fileSize']
}
end
end
end
def db_exists?(db_name)
if @db.nil?
client.database_names.include? db_name
else
@db == db_name
end
end
end
end
end
require 'mongo'
require 'json'
module Genghis
module Helpers
PAGE_LIMIT = 50
### Genghis JSON responses ###
def genghis_json(doc, *args)
json(::Genghis::JSON.as_json(doc), *args)
end
### Misc request parsing helpers ###
def query_param
::Genghis::JSON.decode(params.fetch('q', '{}'))
end
def page_param
params.fetch('page', 1).to_i
end
def request_json
@request_json ||= ::JSON.parse request.body.read
rescue
raise Genghis::MalformedDocument.new
end
def request_genghis_json
@request_genghis_json ||= ::Genghis::JSON.decode request.body.read
rescue
raise Genghis::MalformedDocument.new
end
def thunk_mongo_id(id)
id =~ /^[a-f0-9]{24}$/i ? BSON::ObjectId(id) : id
end
### Seemed like a good place to put this ###
def server_status_alerts
require 'rubygems'
alerts = []
if check_json_ext?
msg = <<-MSG.strip.gsub(/\s+/, " ")
<h4>JSON C extension not found.</h4>
Falling back to the pure Ruby variant. <code>gem install json</code> for better performance.
MSG
alerts << {:level => 'warning', :msg => msg}
end
# It would be awesome if we didn't have to resort to this :)
if Gem::Specification.respond_to? :find_all
if check_bson_ext?
Gem.refresh
installed = Gem::Specification.find_all { |s| s.name == 'mongo' }.map { |s| s.version }.sort.last
if Gem::Specification.find_all { |s| s.name == 'bson_ext' && s.version == installed }.empty?
msg = <<-MSG.strip.gsub(/\s+/, " ")
<h4>MongoDB driver C extension not found.</h4>
Install this extension for better performance: <code>gem install bson_ext -v #{installed}</code>
MSG
alerts << {:level => 'warning', :msg => msg}
else
msg = <<-MSG.strip.gsub(/\s+/, " ")
<h4>Restart required</h4>
You have recently installed the <tt>bson_ext</tt> extension.
Run <code>genghisapp --kill</code> then restart <code>genghisapp</code> to use it.
MSG
alerts << {:level => 'info', :msg => msg}
end
end
unless ENV['GENGHIS_NO_UPDATE_CHECK']
require 'open-uri'
Gem.refresh
latest = nil
installed = Gem::Specification.find_all { |s| s.name == 'genghisapp' }.map { |s| s.version }.sort.last
running = Gem::Version.new(Genghis::VERSION.gsub(/[\+_-]/, '.'))
begin
open('https://raw.github.com/bobthecow/genghis/master/VERSION') do |f|
latest = Gem::Version.new(f.read.gsub(/[\+_-]/, '.'))
end
rescue
# do nothing...
end
if latest && (installed || running) < latest
msg = <<-MSG.strip.gsub(/\s+/, " ")
<h4>A Genghis update is available</h4>
You are running Genghis version <tt>#{Genghis::VERSION}</tt>. The current version is <tt>#{latest}</tt>.
Visit <a href="http://genghisapp.com">genghisapp.com</a> for more information.
MSG
alerts << {:level => 'warning', :msg => msg}
elsif installed && running < installed
msg = <<-MSG.strip.gsub(/\s+/, " ")
<h4>Restart required</h4>
You have installed Genghis version <tt>#{installed}</tt> but are still running <tt>#{Genghis::VERSION}</tt>.
Run <code>genghisapp --kill</code> then restart <code>genghisapp</code>.
MSG
alerts << {:level => 'info', :msg => msg}
end
end
end
alerts
end
### Server management ###
def servers
@servers ||= begin
dsn_list = ::JSON.parse(request.cookies['genghis_rb_servers'] || '[]')
servers = default_servers.merge(init_servers(dsn_list))
servers.empty? ? init_servers(['localhost']) : servers # fall back to 'localhost'
end
end
def default_servers
@default_servers ||= init_servers((ENV['GENGHIS_SERVERS'] || '').split(';'), :default => true)
end
def init_servers(dsn_list, opts={})
Hash[dsn_list.map { |dsn|
server = Genghis::Models::Server.new(dsn)
server.default = opts[:default] || false
[server.name, server]
}]
end
def add_server(dsn)
server = Genghis::Models::Server.new(dsn)
raise Genghis::MalformedDocument.new(server.error) if server.error
raise Genghis::ServerAlreadyExists.new(server.name) unless servers[server.name].nil?
servers[server.name] = server
save_servers
server
end
def remove_server(name)
raise Genghis::ServerNotFound.new(name) if servers[name].nil?
@servers.delete(name)
save_servers
end
def save_servers
dsn_list = servers.collect { |name, server| server.dsn unless server.default }.compact
response.set_cookie(
:genghis_rb_servers,
:path => '/',
:value => dsn_list.to_json,
:expires => Time.now + 60*60*24*365
)
end
def is_ruby?
(defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ruby') || !(RUBY_PLATFORM =~ /java/)
end
def check_json_ext?
!ENV['GENGHIS_NO_JSON_CHECK'] && is_ruby? && !defined?(::JSON::Ext)
end
def check_bson_ext?
!ENV['GENGHIS_NO_BSON_CHECK'] && is_ruby? && !defined?(::BSON::BSON_C)
end
end
end
require 'sinatra/base'
require 'sinatra/mustache'
require 'sinatra/json'
require 'sinatra/reloader'
require 'sinatra/streaming'
require 'mongo'
module Genghis
class Server < Sinatra::Base
# default to 'production' because yeah
set :environment, :production
# work around path param slash encoding issues.
set :protection, :except => :path_traversal
enable :inline_templates
helpers Sinatra::Streaming
helpers Sinatra::JSON
set :json_encoder, :to_json
set :json_content_type, :json
helpers Genghis::Helpers
def self.version
Genghis::VERSION
end
### Error handling ###
helpers do
def error_response(status, message)
@status, @message = status, message
@genghis_version = Genghis::VERSION
@base_url = request.env['SCRIPT_NAME']
if request.xhr?
content_type :json
error(status, {:error => message, :status => status}.to_json)
else
error(status, mustache('error.html.mustache'.intern))
end
end
end
error 400..599 do
err = env['sinatra.error']
error_response(err.respond_to?(:http_status) ? err.http_status : 500, err.message)
end
not_found do
error_response(404, env['sinatra.error'].message.sub(/^Sinatra::NotFound$/, 'Not Found'))
end
### Asset routes ###
get '/assets/style.css' do
content_type 'text/css'
self.class.templates['style.css'.intern].first
end
get '/assets/script.js' do
content_type 'text/javascript'
self.class.templates['script.js'.intern].first
end
### GridFS handling ###
get '/servers/:server/databases/:database/collections/:collection/files/:document' do |server, database, collection, document|
file = servers[server][database][collection].get_file document
content_type file['contentType'] || 'application/octet-stream'
attachment file['filename'] || document
stream do |out|
file.each do |chunk|
out << chunk
end
end
end
# delete '/servers/:server/databases/:database/collections/:collection/files/:document' do |server, database, collection, document|
# # ...
# json :success => true
# end
### Default route ###
get '*' do
# Unless this is XHR, render index and let the client-side app handle routing
pass if request.xhr?
@genghis_version = Genghis::VERSION
@base_url = request.env['SCRIPT_NAME']
mustache 'index.html.mustache'.intern
end
### Genghis API ###
get '/check-status' do
json :alerts => server_status_alerts
end
get '/servers' do
json servers.values
end
post '/servers' do
json add_server request_json['name']
end
get '/servers/:server' do |server|
raise Genghis::ServerNotFound.new(server) if servers[server].nil?
json servers[server]
end
delete '/servers/:server' do |server|
remove_server server
json :success => true
end
get '/servers/:server/databases' do |server|
json servers[server].databases
end
post '/servers/:server/databases' do |server|
json servers[server].create_database request_json['name']
end