-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_setup.rb
executable file
·2021 lines (2020 loc) · 76.9 KB
/
new_setup.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 jruby
require 'rubygems'
require 'rubygems/gem_runner'
require 'rubygems/exceptions'
#
module Gem::UserInteraction
def terminate_interaction(exit_code = 0)
# Suppress the instruction to exit ruby:
# ui.terminate_interaction exit_code
end
end
#
class Object
private
def gem_command(commands=nil)
if commands.is_a?(::String)
Gem::GemRunner.new.run commands.split(" ")
end
end
public
end
#
require 'gxg-framework'
# ### Define Directory Layout for Server
::GxG::SYSTEM.gxg_root = File.dirname(__FILE__)
module GxG
# Define Server directories, ensure directories are present
SYSTEM_PATHS = ::GxG::SYSTEM.server_paths()
end
::GxG::SYSTEM_PATHS.values.each do |a_path|
if a_path
unless Dir.exist?(a_path)
begin
FileUtils.mkpath(a_path)
rescue Exception => error
log_error({:error => error, :parameters => a_path})
end
end
end
end
# ### Flesh out www dirs
public_dir = File.expand_path("./Public",gxg_root)
unless Dir.exist?(public_dir)
Dir.mkdir(public_dir, 0775)
end
pub_theme_dir = "#{public_dir}/www/themes"
unless Dir.exist?(pub_theme_dir)
Dir.mkdir(pub_theme_dir, 0775)
end
pub_js_dir = "#{public_dir}/www/javascript"
unless Dir.exist?(pub_js_dir)
Dir.mkdir(pub_js_dir, 0775)
end
pub_image_dir = "#{public_dir}/www/images"
unless Dir.exist?(pub_image_dir)
Dir.mkdir(pub_image_dir, 0775)
end
pub_audio_dir = "#{public_dir}/www/audio"
unless Dir.exist?(pub_audio_dir)
Dir.mkdir(pub_audio_dir, 0775)
end
pub_video_dir = "#{public_dir}/www/video"
unless Dir.exist?(pub_video_dir)
Dir.mkdir(pub_video_dir, 0775)
end
# Ensure specs dir is present
if Dir.exist?(GxG::SYSTEM_PATHS[:gems])
unless Dir.exist?("#{GxG::SYSTEM_PATHS[:gems]}/specs")
begin
FileUtils.mkpath("#{GxG::SYSTEM_PATHS[:gems]}/specs")
rescue Exception => error
log_error({:error => error, :parameters => "#{GxG::SYSTEM_PATHS[:gems]}/specs"})
end
end
else
begin
FileUtils.mkpath("#{GxG::SYSTEM_PATHS[:gems]}/specs")
rescue Exception => error
log_error({:error => error, :parameters => "#{GxG::SYSTEM_PATHS[:gems]}/specs"})
end
end
# Setup Rubygems paths
ENV['GEM_HOME']=GxG::SYSTEM_PATHS[:gems]
ENV['GEM_SPEC_CACHE']="#{GxG::SYSTEM_PATHS[:gems]}/specs"
ENV['GEM_PATH']=[(GxG::SYSTEM_PATHS[:gems]), (Gem.paths.path)].flatten.join(":")
Gem.clear_paths
Gem.paths = ENV
#
class Object
private
def gem_install(gem_name=nil,version_info=nil)
if gem_name.is_any?(::String, ::Symbol) && version_info.is_any?(::String, ::NilClass)
if version_info
gem_command("install --install-dir #{GxG::SYSTEM_PATHS[:gems]} --version #{version_info.to_s} #{gem_name.to_s}")
else
gem_command("install --install-dir #{GxG::SYSTEM_PATHS[:gems]} #{gem_name.to_s}")
end
end
else
raise Exception, "Invalid gem or version specifier"
end
public
end
# ### Establish Mount Details
# Core Configuration
unless File.exists?("#{GxG::SERVER_PATHS[:configuration]}/core.json")
handle = File.open("#{GxG::SERVER_PATHS[:configuration]}/core.json", "wb")
handle.write(::JSON.pretty_generate({:enabled => ["www"], :disabled => [], :available => ["www"]}))
handle.close
end
# WWW Configuration
unless File.exists?("#{GxG::SERVER_PATHS[:configuration]}/www.json")
handle = File.open("#{GxG::SERVER_PATHS[:configuration]}/www.json", "wb")
handle.write(::JSON.pretty_generate({:mode => "production", :listen => [{:address => "127.0.0.1", :port => 32767}], :relative_url => "", :cache_quota => 1073741824, :cache_max_item_size => 1073741824}))
handle.close
end
# DB configuration
def configure_db()
# Construct default configuration files:
# Database Configuration:
if File.exists?("#{GxG::SERVER_PATHS[:configuration]}/databases.json")
handle = File.open("#{GxG::SERVER_PATHS[:configuration]}/databases.json", "rb")
db_config = ::JSON::parse(handle.read(), {:symbolize_names => true})
handle.close
else
# paths are REALITIVE to the system db dir
db_config = {:databases => [{:url => "sqlite://default.gxg", :roles => ["users", "data", "formats", "vfs"]},{:url => "sqlite://Content.gxg", :roles => ["content"]},{:url => "sqlite://Software.gxg", :roles => ["software"]},{:url => "sqlite://Reference.gxg", :roles => ["reference"]}]}
#
end
puts "Current database configuration:\n#{db_config[:databases].inspect}\n"
puts "--------------------------\n"
puts "0) save, 1) create new db config\n"
if gets("\n").to_s.split("\n")[0].to_s.to_i == 1
new_config = []
editing = true
while editing == true do
puts "Current NEW configuration:\n#{new_config.inspect}\n"
puts "--------------------------\n"
puts "\nEnter a database URL (mysql://<user_id>:<password>@<host>/<database_name>) :\n"
the_url = gets("\n").to_s.split("\n")[0].to_s
puts "\nEnter the roles that this database serves (users, data, formats, vfs, reference) comma separated, no-spaces :\n"
the_roles = gets("\n").to_s.split("\n")[0].to_s.gsub(" ","").split(",")
new_config << {:url => the_url, :roles => the_roles}
puts "0) save as is, 1) add new db entry\n"
if gets("\n").to_s.split("\n")[0].to_s.to_i == 0
editing = false
db_config[:databases] = new_config
end
end
end
#
if File.exists?("#{GxG::SERVER_PATHS[:configuration]}/databases.json")
File.delete("#{GxG::SERVER_PATHS[:configuration]}/databases.json")
end
handle = File.open("#{GxG::SERVER_PATHS[:configuration]}/databases.json","w+b", 0664)
handle.write(::JSON.pretty_generate(db_config))
handle.close
# Return db_config
db_config
#
end
# ### Mount Databases by role
if File.exists?("#{GxG::SYSTEM_PATHS[:configuration]}/databases.json")
db_config = configure_db()
# ### Set DB Roles, and other details
::GxG::DB[:roles] = {}
if db_config[:databases].is_a?(::Array)
#
mounted = []
db_config[:databases].each do |entry|
entry[:roles].each do |the_role|
if the_role.downcase == "users"
#
if ::URI::parse(entry[:url]).scheme.downcase == "ldap"
# TODO: ExternalAuthority
mounted << {:url => entry[:url].to_s, :db => nil, :roles => [:user]}
else
if ::URI::parse(entry[:url]).scheme.downcase == "sqlite"
if ::URI::parse(entry[:url]).hostname.to_s[0] == "/" || ::URI::parse(entry[:url]).path.to_s[0] == "/"
# absolute path
the_db_url = entry[:url]
else
# relative path
the_db_url = "sqlite://#{GxG::SYSTEM_PATHS[:databases]}/#{::URI::parse(entry[:url]).hostname}"
end
else
the_db_url = entry[:url]
end
the_db = ::GxG::Database::connect(the_db_url)
if the_db
the_db.clear_all_element_locks
the_db.empty_trash
::GxG::DB[:authority] = the_db
::GxG::DB[:roles][:users] = ::GxG::DB[:authority]
mounted << {:url => entry[:url].to_s, :db => the_db, :roles => [:users]}
break
end
end
#
end
end
if ::GxG::DB[:authority].is_any?(::GxG::Database::Database, ::GxG::Database::ExternalAuthority)
break
end
end
#
if ::GxG::DB[:authority].is_any?(::GxG::Database::Database, ::GxG::Database::ExternalAuthority)
db_config[:databases].each do |entry|
log_info "Mounting or creating a database ..."
if (mounted.map {|item| item[:url]}).include?(entry[:url].to_s)
# Flesh out other roles : {:url => entry[:url].to_s, :db => the_db, :roles => [:user]}
mounted.each do |the_mount|
#
if entry[:url] == the_mount[:url]
entry[:roles].each do |the_role|
unless the_mount[:roles].include?(the_role)
::GxG::DB[:roles][(the_role.to_sym)] = the_mount[:db]
the_mount[:roles] << the_role.to_sym
end
end
end
#
end
else
# Mount fresh
if ::URI::parse(entry[:url]).scheme.downcase == "sqlite"
if ::URI::parse(entry[:url]).hostname.to_s[0] == "/" || ::URI::parse(entry[:url]).path.to_s[0] == "/"
# absolute path
the_db_url = entry[:url]
else
# relative path
the_db_url = "sqlite://#{GxG::SYSTEM_PATHS[:databases]}/#{::URI::parse(entry[:url]).hostname}"
end
else
the_db_url = entry[:url]
end
the_db = ::GxG::Database::connect(the_db_url, {:authority => ::GxG::DB[:authority]})
if the_db
# house cleaning:
the_db.clear_all_element_locks
the_db.empty_trash
mounted_roles = []
entry[:roles].each do |the_role|
unless ::GxG::DB[:roles][(the_role.to_sym)]
::GxG::DB[:roles][(the_role.to_sym)] = the_db
mounted_roles << the_role.to_sym
end
end
mounted << {:url => entry[:url].to_s, :db => the_db, :roles => mounted_roles}
end
#
end
end
else
# Error - no authority db found, unable to proceed.
log_error "No Authority Database Found : Unable to proceed."
exit 1
end
#
unless ::GxG::DB[:roles][:formats].is_a?(::GxG::Database::Database)
# Error - no format db found, unable to proceed.
log_error "No Format Database Found : Unable to proceed."
exit 1
end
#
end
# Set Administrator/Members credential for system use.
::GxG::DB[:administrator] = ::GxG::DB[:authority][:system_credentials][:administrator]
::GxG::DB[:administrators] = ::GxG::DB[:authority][:system_credentials][:administrators]
::GxG::DB[:developers] = ::GxG::DB[:authority][:system_credentials][:developers]
::GxG::DB[:designers] = ::GxG::DB[:authority][:system_credentials][:designers]
::GxG::DB[:users] = ::GxG::DB[:authority][:system_credentials][:users]
else
log_warn "No Database Configuration found: run setup.rb from the shell."
end
# ### Populate the Mandatory VFS with GxG::SYSTEM_PATHS
::GxG::VFS.mount(::GxG::Storage::Volume.new({:directory => ::GxG::SYSTEM_PATHS[:system]}), "/System")
::GxG::VFS.mount(::GxG::Storage::Volume.new({:directory => ::GxG::SYSTEM_PATHS[:services]}), "/Services")
::GxG::VFS.mount(::GxG::Storage::Volume.new({:directory => ::GxG::SYSTEM_PATHS[:installers]}), "/Installers")
::GxG::VFS.mount(::GxG::Storage::Volume.new({:directory => ::GxG::SYSTEM_PATHS[:temporary]}), "/Temporary")
::GxG::VFS.mount(::GxG::Storage::Volume.new({:directory => ::GxG::SYSTEM_PATHS[:logs]}), "/Logs")
::GxG::VFS.mount(::GxG::Storage::Volume.new({:directory => ::GxG::SYSTEM_PATHS[:public]}), "/Public")
# VFS configuration
def configure_vfs()
# VFS Mounting Configuration:
reserved_roles = ["users", "data"]
if File.exists?("#{GxG::SERVER_PATHS[:configuration]}/mounts.json")
handle = File.open("#{GxG::SERVER_PATHS[:configuration]}/mounts.json", "rb")
mount_config = ::JSON::parse(handle.read(), {:symbolize_names => true})
handle.close
else
mount_config = {:mount_points => [{:db_role => "vfs", :path => "/Storage"}, {:db_role => "reference", :path => "/Reference"}, {:file_system => "./Users", :path => "/User"}, {:db_role => "content", :path => "/Public/www/content"}, {:db_role => "software", :path => "/Public/www/software"}]}
handle = File.open("#{GxG::SERVER_PATHS[:configuration]}/mounts.json","w+b", 0664)
handle.write(::JSON.pretty_generate(mount_config))
handle.close
end
puts "Current VFS mount point configuration:\n#{mount_config[:mount_points].inspect}\n"
puts "--------------------------\n"
puts "0) save, 1) create new mount points\n"
if gets("\n").to_s.split("\n")[0].to_s.to_i == 1
new_config = []
editing = true
while editing == true do
puts "Current NEW configuration:\n#{new_config.inspect}\n"
puts "--------------------------\n"
puts "\nEnter a: 0) DB Role mount point, 1) File System mount point\n"
record = {}
choice = gets("\n").to_s.split("\n")[0].to_s.to_i
if choice == 0
puts "\nEnter the DB Role to mount (one only):\n"
the_role = gets("\n").to_s.split("\n")[0].to_s
record[:db_role] = the_role
else
puts "\nEnter a full File System path to mount:\n"
the_fs = gets("\n").to_s.split("\n")[0].to_s
record[:file_system] = the_fs
end
puts "\nEnter a VFS path to serve as mount point\n"
the_vfs = gets("\n").to_s.split("\n")[0].to_s
record[:path] = the_vfs
new_config << record
puts "0) save as is, 1) add another mount point\n"
if gets("\n").to_s.split("\n")[0].to_s.to_i == 0
editing = false
mount_config[:mount_points] = new_config
end
end
end
if File.exists?("#{GxG::SERVER_PATHS[:configuration]}/mounts.json")
File.delete("#{GxG::SERVER_PATHS[:configuration]}/mounts.json")
end
handle = File.open("#{GxG::SERVER_PATHS[:configuration]}/mounts.json","w+b", 0664)
handle.write(::JSON.pretty_generate(mount_config))
handle.close
# Return mount_config
mount_config
#
end
# Populate Optional VFS mount points
if GxG::valid_uuid?(GxG::DB[:administrator])
mount_config = configure_vfs()
if mount_config.is_a?(::Hash)
#
volume = nil
mount_config[:mount_points].each do |entry|
if entry[:db_role]
the_db = ::GxG::DB[:roles][(entry[:db_role].to_sym)]
if the_db
volume = ::GxG::Storage::Volume.new({:database => the_db, :credential => GxG::DB[:administrator]})
end
end
if entry[:file_system]
if ["./", ".."].include?(entry[:file_system][0..1])
# Relative Path - to GXGROOT
fs_path = File.expand_path(entry[:file_system],::GxG::SYSTEM.gxg_root())
else
# Absolute Path
fs_path = entry[:file_system]
end
unless Dir.exist?(fs_path)
FileUtils.mkdir_p(fs_path)
end
if entry[:path] == "/Users"
::GxG::SYSTEM_PATHS[:users] = fs_path
unless Dir.exist?(fs_path + "/Shared")
FileUtils.mkdir_p((fs_path + "/Shared"))
end
else
::GxG::SYSTEM_PATHS[(File.basename(entry[:path]).downcase.to_sym)] = fs_path
end
volume = ::GxG::Storage::Volume.new({:directory => fs_path})
end
if volume
GxG::VFS.mount(volume, entry[:path])
volume = nil
end
end
else
log_warn "No VFS Optional Configuration found: run setup.rb from the shell."
end
end
# ### Services Framework
module GxG
SERVICES = {}
module Services
# ### Service Management
def self.start_order()
# Calculate service startup order based upon interdepenedencies
# Review : Research a REAL dep tree calculator - See: https://stackoverflow.com/questions/21108109/how-do-i-find-out-all-the-dependencies-of-a-gem
deps = {}
::GxG::SERVICES.each_pair do |moniker, service|
unless moniker == :core
unless deps[(moniker)]
deps[(moniker)] = 0
end
service.required_services().each do |the_dep|
if deps[(the_dep.to_sym)]
deps[(the_dep.to_sym)] -= 1
else
deps[(the_dep.to_sym)] = 0
end
end
end
end
boot_queue = []
(deps.sort_by {|key,value| value}).to_h.keys.each do |the_service_moniker|
::GxG::SERVICES[(the_service_moniker)].required_services.each do |moniker|
unless boot_queue.include?(moniker)
boot_queue << moniker
end
end
unless boot_queue.include?(the_service_moniker)
boot_queue << the_service_moniker
end
end
#
boot_queue
end
#
def self.stop_order()
::GxG::Services::start_order().reverse!
end
#
def self.start_service(moniker=nil)
if moniker.is_a?(::Symbol)
if ::GxG::SERVICES[(moniker)]
# ::GxG::SERVICES[(moniker)].start
::GxG::SERVICES[(moniker)].call_event({:start => nil})
end
end
end
#
def self.stop_service(moniker=nil)
if moniker.is_a?(::Symbol)
if ::GxG::SERVICES[(moniker)]
# ::GxG::SERVICES[(moniker)].stop
::GxG::SERVICES[(moniker)].call_event({:stop => nil})
end
end
end
#
def self.install_service(moniker=nil)
if moniker.is_a?(::Symbol)
configuration = ::GxG::SERVICES[:core].configuration
unless configuration[:available].is_a?(::Array)
configuration[:available] = []
end
unless configuration[:available].include?(moniker.to_s)
configuration[:available] << moniker.to_s
end
::GxG::SERVICES[:core].save_configuration
#
true
else
false
end
end
#
def self.service_available?(moniker=nil)
if moniker.is_a?(::Symbol)
configuration = ::GxG::SERVICES[:core].configuration
if configuration[:available].is_a?(::Array)
if configuration[:available].include?(moniker.to_s)
true
else
false
end
else
false
end
else
false
end
end
#
def self.enable_service(moniker=nil)
if moniker.is_a?(::Symbol)
configuration = ::GxG::SERVICES[:core].configuration
unless configuration[:disabled].is_a?(::Array)
configuration[:disabled] = []
end
unless configuration[:enabled].is_a?(::Array)
configuration[:enabled] = []
end
if configuration[:disabled].include?(moniker.to_s)
configuration[:disabled].delete_at(configuration[:enabled].find_index(moniker.to_s))
end
unless configuration[:enabled].include?(moniker.to_s)
configuration[:enabled] << moniker.to_s
end
::GxG::SERVICES[:core].save_configuration
#
true
else
false
end
end
#
def self.disable_service(moniker=nil)
if moniker.is_a?(::Symbol)
configuration = ::GxG::SERVICES[:core].configuration
unless configuration[:disabled].is_a?(::Array)
configuration[:disabled] = []
end
unless configuration[:enabled].is_a?(::Array)
configuration[:enabled] = []
end
if configuration[:enabled].include?(moniker.to_s)
configuration[:enabled].delete_at(configuration[:enabled].find_index(moniker.to_s))
end
unless configuration[:disabled].include?(moniker.to_s)
configuration[:disabled] << moniker.to_s
end
::GxG::SERVICES[:core].save_configuration
#
true
else
false
end
end
#
def self.register_service(moniker=:unspecified, service_harness=nil)
if moniker
unless moniker == :unspecified
if service_harness.is_a?(GxG::Services::Service)
GxG::SERVICES[(moniker)] = service_harness
end
end
end
end
# ### Service Class Definition
class Service
# Class-level toolbox:
# Instance toolbox:
def initialize(moniker=:unspecified, options={:event_interval => 0.333})
if moniker.is_a?(::Symbol)
if moniker == :unspecified || (::GxG::SERVICES[:core] && moniker == :core)
raise Exception, "You MUST provide a unique, specific Symbol as your service moniker. This becomes the system-wide service name other services will need provided."
else
# Service Initialization code
@provides = moniker
@requirements = [:core]
@thread_safety = ::Mutex.new
@heap = {}
@status = :stopped
@state = nil
@configuration = {}
@dispatcher = ::GxG::Events::EventDispatcher.new((options[:event_interval] || 0.333))
@interface = {}
#
self.load_configuration
#
self.on(:interface, {:description => "Available Commands", :usage => "{ :interface => nil }", :public => true}) do
self.interface()
end
#
::GxG::Services::register_service(moniker, self)
#
end
else
raise Exception, "You MUST provide a unique service name as a Symbol for your service moniker."
end
self
end
#
def inspect()
"<Service #{@provides.inspect}>"
end
# ### FS & VFS
def vfs_root()
if @provides == :core
"/Services"
else
"/Services/#{@provides.to_s}"
end
end
#
def fs_root()
::File.expand_path("#{::GxG::SYSTEM.gxg_root()}/#{self.vfs_root()}")
end
# ### API Support
def publish_api()
if ::GxG::Services::service_available?(:www)
::GxG::SERVICES[:www].call_event({:publish_api => {:service => self, :path => "/#{@provides.to_s}"}}, ::GxG::DB[:administrator])
end
end
def unpublish_api()
if ::GxG::Services::service_available?(:www)
::GxG::SERVICES[:www].call_event({:unpublish_api => {:path => "/#{@provides.to_s}"}}, ::GxG::DB[:administrator])
end
end
# ### Service Management
def provides()
@provides
end
#
def required_services()
@requirements.clone
end
#
def require_service(moniker=:unspecified)
if moniker.is_a?(::Symbol)
unless moniker == :unspecified
unless @requirements.include?(moniker)
@requirements << moniker
end
end
end
end
# ### Configuration Management
def configuration()
@configuration
end
#
def save_configuration(options={})
result = false
config_path = ::File.expand_path(::GxG::SYSTEM_PATHS[:configuration] + "/" + "#{@provides.to_s}.json")
if File.exists?(config_path)
File.delete(config_path)
end
begin
handle = File.open(config_path, "w+b", 0664)
handle.write(::JSON::pretty_generate(@configuration))
handle.close
result = true
rescue Exception => the_error
log_warn("Failed to save configuration for #{@provides.inspect} --> #{the_error.to_s}")
end
result
end
#
def load_configuration(options={})
result = false
config_path = ::File.expand_path(::GxG::SYSTEM_PATHS[:configuration] + "/" + "#{@provides.to_s}.json")
if File.exists?(config_path)
handle = File.open(config_path, "rb", 0664)
begin
@configuration =::JSON::parse(handle.read(), {:symbolize_names => true})
result = true
rescue Exception => the_error
log_warn("Failed to load configuration for #{@provides.inspect} --> #{the_error.to_s}")
end
handle.close
#
if result == true
if ::GxG::valid_uuid?(@configuration[:state_uuid])
unless @state.is_a?(::GxG::Database::PersistedHash)
@state = ::GxG::DB[:roles][:data].retrieve_by_uuid(@configuration[:state_uuid].to_s.to_sym, ::GxG::DB[:administrator])
if @state.is_a?(::GxG::Database::PersistedHash)
@state.get_reservation
else
# This means the db was blown out and this must be reconstructed.
@state = ::GxG::DB[:roles][:data].try_persist({}, ::GxG::DB[:administrator])
@state.get_reservation
@state.set_title("#{@provides.to_s} State Data")
@state.save
@configuration[:state_uuid] = @state.uuid.to_s
end
end
else
orphaned_state_record = GxG::DB[:roles][:data].uuid_list(GxG::DB[:administrator],{:title => "#{@provides.to_s} State Data"}).first
if orphaned_state_record
@state = ::GxG::DB[:roles][:data].retrieve_by_uuid((orphaned_state_record[:uuid]),::GxG::DB[:administrator])
end
unless @state.is_a?(::GxG::Database::PersistedHash)
@state = ::GxG::DB[:roles][:data].try_persist({}, ::GxG::DB[:administrator])
@state.get_reservation
@state.set_title("#{@provides.to_s} State Data")
@state.save
end
@configuration[:state_uuid] = @state.uuid.to_s
end
end
else
if @state.is_a?(::GxG::Database::PersistedHash)
unless ::GxG::valid_uuid?(@configuration[:state_uuid])
@configuration[:state_uuid] = @state.uuid.to_s
end
else
if ::GxG::valid_uuid?(@configuration[:state_uuid])
@state = ::GxG::DB[:roles][:data].retrieve_by_uuid(@configuration[:state_uuid].to_s.to_sym, ::GxG::DB[:administrator])
@state.get_reservation
else
orphaned_state_record = GxG::DB[:roles][:data].uuid_list(GxG::DB[:administrator],{:title => "#{@provides.to_s} State Data"}).first
if orphaned_state_record
@state = ::GxG::DB[:roles][:data].retrieve_by_uuid((orphaned_state_record[:uuid]),::GxG::DB[:administrator])
end
unless @state.is_a?(::GxG::Database::PersistedHash)
@state = ::GxG::DB[:roles][:data].try_persist({}, ::GxG::DB[:administrator])
@state.get_reservation
@state.set_title("#{@provides.to_s} State Data")
@state.save
end
@configuration[:state_uuid] = @state.uuid.to_s
end
end
self.save_configuration
result = true
end
result
end
# ### Heap & State Data
def keys()
@thread_safety.synchronize { @heap.keys }
end
#
def [](key=nil)
if key.is_any?(::String, ::Symbol)
@thread_safety.synchronize { @heap[(key)] }
else
nil
end
end
#
def []=(key=nil,value=nil)
if key.is_any?(::String, ::Symbol)
@thread_safety.synchronize { @heap[(key)] = value }
else
nil
end
end
#
def delete(key=nil)
if key.is_any?(::String, ::Symbol)
@thread_safety.synchronize { @heap.delete(key) }
else
nil
end
end
#
def state_keys()
@state.keys()
end
#
def state_get(state_key=nil)
result = nil
if state_key.is_a?(::Symbol)
if @state.is_a?(::GxG::Database::PersistedHash)
result = @state[(state_key)]
end
end
result
end
#
def state_set(state_key=nil, state_value=nil)
if state_key.is_a?(::Symbol)
if @state.is_a?(::GxG::Database::PersistedHash)
@state[(state_key)] = state_value
@state.save
end
end
end
#
def state_delete(key)
result = nil
if state_key.is_a?(::Symbol)
if @state.is_a?(::GxG::Database::PersistedHash)
result = @state.delete(state_key)
end
end
result
end
# ### Activity and Status Management
def is_running?()
@status == :running || @status == :paused
end
#
def status()
@status
end
#
def start(options={:timeout => 30000.0})
# start entire service, load configuration
@status = :starting
if self.load_configuration() == true
timeout = Time.now.to_f + (options[:timeout] || 30000.0)
all_loaded = false
#
if @provides == :core
all_loaded = true
else
# wait until all requirements load until timeout
requirement_count = @requirements.size
while (Time.now.to_f < timeout) do
started_count = 0
@requirements.each do |moniker|
if ::GxG::SERVICES[(moniker)].is_running? == true
started_count += 1
end
end
if requirement_count == started_count
all_loaded = true
break
else
sleep 1.0
end
end
unless all_loaded == true
log_warn("Aborted service startup for #{@provides.inspect} because other required services did not start in time.")
end
end
#
if all_loaded == true
if self.respond_to_event?(:before_start)
self.call_event({:before_start => self}, ::GxG::DB[:administrator])
end
# start event dispatcher
@dispatcher.startup
@status = :running
if self.respond_to_event?(:at_start)
self.call_event({:at_start => self}, ::GxG::DB[:administrator])
end
if self.respond_to_event?(:after_start)
self.call_event({:after_start => self}, ::GxG::DB[:administrator])
end
true
else
@status = :stopped
false
end
#
else
@status = :stopped
false
end
#
end
#
def stop(options={})
# stop entire service
if self.respond_to_event?(:before_stop)
self.call_event({:before_stop => self}, ::GxG::DB[:administrator])
end
@status = :stopping
#
if self.respond_to_event?(:at_stop)
self.call_event({:at_stop => self}, ::GxG::DB[:administrator])
end
@dispatcher.shutdown
#
@status = :stopped
if self.respond_to_event?(:after_stop)
self.call_event({:after_stop => self}, ::GxG::DB[:administrator])
end
true
end
#
def restart(options={})
# restart entire service, reloading configuration
if self.respond_to_event?(:before_restart)
self.call_event({:before_restart => self}, ::GxG::DB[:administrator])
end
if self.stop(options) == true
self.start(options)
if self.respond_to_event?(:at_restart)
self.call_event({:at_restart => self}, ::GxG::DB[:administrator])
end
if self.respond_to_event?(:after_restart)
self.call_event({:after_restart => self}, ::GxG::DB[:administrator])
end
true
else
false
end
#
end
#
def pause(options={})
# pause dispatcher
if self.respond_to_event?(:before_pause)
self.call_event({:before_pause => self}, ::GxG::DB[:administrator])
end
@dispatcher.shutdown
@status = :paused
if self.respond_to_event?(:at_pause)
self.call_event({:at_pause => self}, ::GxG::DB[:administrator])
end
if self.respond_to_event?(:after_pause)
self.call_event({:after_pause => self}, ::GxG::DB[:administrator])
end
true
end
#
def resume(options={})
# resume dispatcher
if self.respond_to_event?(:before_resume)
self.call_event({:before_resume => self}, ::GxG::DB[:administrator])
end
@dispatcher.startup
@status = :running
if self.respond_to_event?(:at_resume)
self.call_event({:at_resume => self}, ::GxG::DB[:administrator])
end
if self.respond_to_event?(:after_resume)
self.call_event({:after_resume => self}, ::GxG::DB[:administrator])
end
true
end
# ### Command Interface:
def dispatcher()
@dispatcher
end
#
def on(the_event, options={}, &block)
unless the_event.is_a?(::Symbol)
raise ArgumentError, "You must specify an event listener with a unique Symbol."
end
unless block.respond_to?(:call)
raise ArgumentError, "You must provide an event code block to execute."
end
unless options[:description]
options[:description] = "Event : :#{the_event.to_s}"
end
unless options[:usage]
options[:usage] = "{ :#{the_event.to_s} => (your_data_payload / nil) }"
end
unless options[:public] == true
options[:public] = false
end
@interface[(the_event)] = {:description => options[:description], :usage => options[:usage], :public => (options[:public] || false), :users => (options[:users] || false), :administrators => true, :procedure => block}
true
end
#
def call_event(operation_envelope=nil, credential=(::GxG::DB[:administrator] || :"00000000-0000-4000-0000-000000000000"))
result = nil
if operation_envelope.is_a?(::Hash)
the_event = operation_envelope.keys[0]
if the_event
data = operation_envelope[(the_event)]
if @interface[(the_event)]
begin
can_call = false
if credential == :"00000000-0000-4000-0000-000000000000" && @interface[(the_event)][:public] == true
can_call = true
else
if ::GxG::DB[:authority].role_member?(GxG::DB[:authority][:system_credentials][:administrators].to_s.to_sym, credential)
if @interface[(the_event)][:administrators] == true
can_call = true
end
else
if ::GxG::valid_uuid?(credential) && @interface[(the_event)][:users] == true && credential != :"00000000-0000-4000-0000-000000000000"
can_call = true
end
end
end
#
if can_call
result = {:result => @interface[(the_event)][:procedure].call(data, credential)}
else
result = {:result => nil, :error => "You Do Not Have Sufficient Permissions for Command #{the_event.inspect}"}
end
rescue Exception => the_error
log_error({:error => the_error, :parameters => {:data => data, :credential => credential}})
result = {:result => nil, :error => the_error.to_s}
end
else
result = {:result => nil, :error => "Command #{the_event.inspect} Not Found"}
end
end
end
result
end
#
def interface(credential=:"00000000-0000-4000-0000-000000000000")
result = {}
is_administrator = ::GxG::DB[:authority].role_member?(::GxG::DB[:authority][:system_credentials][:administrators].to_s.to_sym, credential)
@interface.each_pair do |the_event, the_record|
can_view = false
if credential == :"00000000-0000-4000-0000-000000000000" && the_record[:public] == true
can_view = true
else
if is_administrator == true
if the_record[:administrators] == true
can_view = true
end
else
if ::GxG::valid_uuid?(credential) && the_record[:users] == true && credential != :"00000000-0000-4000-0000-000000000000"
can_view = true
end
end
end
#
if can_view == true
result[(the_event)] = (the_record[:description] + ", Usage : " + the_record[:usage])
end
end
result
end
#
def respond_to_event?(the_event=nil)
result = false
if the_event.is_a?(::Symbol)
if @interface[(the_event)]
result = true
end
end
result
end
#