This repository has been archived by the owner on Nov 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathserver_config.rb
3224 lines (2739 loc) · 108 KB
/
server_config.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
###############################################################################
# Copyright 2012-2015 MarkLogic Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
require 'util'
require 'uri'
require 'net/http'
require 'fileutils'
require 'json'
require 'RoxyHttp'
require 'xcc'
require 'MLClient'
require 'date'
require 'ml_rest'
require 'time'
require 'tmpdir'
class ExitException < Exception; end
class HelpException < Exception
attr_reader :command, :message
def initialize(command, message = nil)
@command = command
@message = message
end
end
class DanglingVarsException < Exception
def initialize(vars)
@vars = vars
end
def vars
return @vars
end
end
class ServerConfig < MLClient
# needed to determine if Roxy is running inside a jar
@@is_jar = is_jar?
@@path = @@is_jar ? "./deploy" : "../.."
@@context = @@is_jar ? Dir.pwd : __FILE__
def self.path
@@path
end
def initialize(options)
@options = options
@properties = options[:properties]
super(
:user_name => @properties["ml.user"],
:password => @properties["ml.password"],
:logger => options[:logger],
:no_prompt => options[:no_prompt],
:quiet => options[:quiet],
:http_connection_retry_count => @properties["ml.http.retry-count"].to_i,
:http_connection_open_timeout => @properties["ml.http.open-timeout"].to_i,
:http_connection_read_timeout => @properties["ml.http.read-timeout"].to_i,
:http_connection_retry_delay => @properties["ml.http.retry-delay"].to_i
)
@environment = @properties["environment"]
@properties["ml.server"] = @properties["ml.#{@environment}-server"] unless @properties["ml.server"]
if !@@quiet
if (@properties["ml.server"] == nil)
raise "Error! ml.server not set. You may be missing deploy/" + @properties["environment"] + ".properties"
end
end
@hostname = @properties["ml.server"]
@bootstrap_port_four = @properties["ml.bootstrap-port-four"]
@bootstrap_port_five = @properties["ml.bootstrap-port-five"]
@use_https = @properties["ml.use-https"] == "true"
@protocol = "http#{@use_https ? 's' : ''}"
@server_version = @properties["ml.server-version"].to_i
@hostname = @properties["ml.server"]
@bootstrap_port_four = @properties["ml.bootstrap-port-four"]
@bootstrap_port_five = @properties["ml.bootstrap-port-five"]
@use_https = @properties["ml.use-https"] == "true"
@protocol = "http#{@use_https ? 's' : ''}"
@server_version = @properties["ml.server-version"].to_i
if !@@quiet
if (@server_version < 7)
logger.warn "WARN: This version of Roxy is not tested against MarkLogic #{@server_version}."
if (@server_version > 4)
logger.info " Consider downgrading to v1.7.0 using `./ml upgrade --branch=v1.7.0`."
end
logger.warn "Note: MarkLogic #{@server_version} is EOL."
end
end
if @properties["ml.bootstrap-port"]
@bootstrap_port = @properties["ml.bootstrap-port"]
else
if @server_version == 4
@bootstrap_port = @bootstrap_port_four
else
@bootstrap_port = @bootstrap_port_five
@properties["ml.bootstrap-port"] = @bootstrap_port
end
end
if @properties['ml.qconsole-port']
@qconsole_port = @properties['ml.qconsole-port']
else
@qconsole_port = @bootstrap_port
end
if !(@ml_user == nil || @ml_password == nil) || !@@quiet
begin
r = execute_query %Q{xdmp:host-name()}
@properties["ml.server-name"] = parse_body(r.body)
rescue
if !@@quiet
logger.warn "WARN: unable to determine MarkLogic Host name of #{@hostname}"
end
end
end
@properties["ml.password"] = @ml_password
if !@@quiet
begin
r = execute_query %Q{ substring-before(xdmp:version(), ".") }
r.body = parse_body r.body
if r.body.to_i != @server_version
logger.warn "WARN: #{@hostname} is running MarkLogic #{r.body}, but server-version is set to #{@server_version}!"
end
rescue
logger.warn "WARN: unable to determine MarkLogic Version of #{@hostname}"
end
end
end
def get_properties
return @properties
end
def info
format = find_arg(['--format'])
info = {}
info["isJar"] = @@is_jar
info["properties"] = @properties
if format == "json"
logger.info "#{JSON.pretty_generate(info)}"
elsif format == "xml"
logger.info "<info>"
logger.info "\s\s<isJar>#{@@is_jar}</isJar>"
logger.info "\s\s<properties>"
# applying ascending order for better readability
@properties.sort {|x,y| x <=> y}.each do |k, v|
logger.info "\s\s\s\s<property name=\"#{k}\">#{v}</property>"
end
logger.info "\s\s</properties>"
logger.info "</info>"
else
logger.info "IS_JAR: #{@@is_jar}"
logger.info "Properties:"
@properties.sort {|x,y| x <=> y}.each do |k, v|
logger.info k + ": " + v.to_s
end
end
return true
end
# This method exists to return a path relative to roxy
# when running as regular old Roxy or as a jar
def ServerConfig.expand_path(path)
# logger.info("path: #{path}")
# logger.info("context: #{@@context}")
result = File.expand_path(path, @@context)
# logger.info("result: #{result}")
return result
end
def ServerConfig.strip_path(path)
basepath = File.expand_path(@@path + "/..", @@context)
return path.sub(basepath + '/', '')
end
def self.jar
raise HelpException.new("jar", "You must be using JRuby to create a jar") unless RUBY_PLATFORM == "java"
begin
# ensure warbler gem is installed
gem 'warbler'
require 'warbler'
jar_file = ServerConfig.expand_path("#{@@path}/../roxy.jar")
logger.debug(jar_file)
Dir.mktmpdir do |tmp_dir|
logger.debug(tmp_dir)
temp_roxy_dir = tmp_dir + "/roxy"
Dir.mkdir temp_roxy_dir
FileUtils.mkdir_p temp_roxy_dir + "/bin"
FileUtils.cp(ServerConfig.expand_path("#{@@path}/lib/ml.rb"), temp_roxy_dir + "/bin/roxy.rb")
FileUtils.cp_r(ServerConfig.expand_path("#{@@path}/lib"), temp_roxy_dir)
FileUtils.cp_r(ServerConfig.expand_path("#{@@path}/sample"), temp_roxy_dir)
Dir.chdir(temp_roxy_dir) do
Warbler::Application.new.run
FileUtils.cp(Dir.glob("*.jar")[0], jar_file)
end
end
return true
rescue Gem::LoadError
raise HelpException.new("jar", "Please install the warbler gem")
end
end
def self.init
# input files
if @@is_jar
sample_config = "roxy/sample/ml-config.sample.xml"
sample_properties = "roxy/sample/build.sample.properties"
sample_options = "roxy/sample/all.sample.xml"
sample_rest_properties = "roxy/sample/properties.sample.xml"
sample_app_config = "roxy/deploy/sample/custom-config.xqy"
else
sample_config = ServerConfig.expand_path("#{@@path}/sample/ml-config.sample.xml")
sample_properties = ServerConfig.expand_path("#{@@path}/sample/build.sample.properties")
sample_options = ServerConfig.expand_path("#{@@path}/sample/all.sample.xml")
sample_rest_properties = ServerConfig.expand_path("#{@@path}/sample/properties.sample.xml")
sample_app_config = ServerConfig.expand_path("#{@@path}/sample/custom-config.xqy")
end
# output files
build_properties = ServerConfig.expand_path("#{@@path}/build.properties")
options_file = ServerConfig.expand_path("#{@@path}/../rest-api/config/options/all.xml")
rest_properties = ServerConfig.expand_path("#{@@path}/../rest-api/config/properties.xml")
app_config = ServerConfig.expand_path("#{@@path}/../src/config/config.xqy")
# dirs to create
rest_ext_dir = ServerConfig.expand_path("#{@@path}/../rest-api/ext")
rest_transforms_dir = ServerConfig.expand_path("#{@@path}/../rest-api/transforms")
options_dir = ServerConfig.expand_path("#{@@path}/../rest-api/config/options")
config_dir = ServerConfig.expand_path("#{@@path}/../src/config")
# get supplied options
force = find_arg(['--force']).present?
force_props = find_arg(['--force-properties']).present?
force_config = find_arg(['--force-config']).present?
app_type = find_arg(['--app-type'])
server_version = find_arg(['--server-version'])
# Check for required --server-version argument value
if (!server_version.present? || server_version == '--server-version' || !(%w(4 5 6 7 8 9).include? server_version))
server_version = prompt_server_version
end
error_msg = []
if !force && !force_props && File.exists?(build_properties)
error_msg << "build.properties has already been created."
else
#create clean properties file
copy_file sample_properties, build_properties
properties_file = File.read(build_properties)
# replace the appname if one is provided
name = ARGV.shift
properties_file.gsub!(/app-name=roxy/, "app-name=#{name}") if name
# do app-type customizations
properties_file.gsub!(/app-type=mvc/, "app-type=#{app_type}")
# If this app will use the ML REST API, we need rewrite-resolved-globally to get those URLs to work
if ["rest", "hybrid"].include? app_type
properties_file.gsub!(/rewrite-resolves-globally=/, "rewrite-resolves-globally=true")
end
if app_type == "bare"
# bare applications don't use rewriter and error handler
properties_file.gsub!(/url-rewriter=\/roxy\/rewrite.xqy/, "url-rewriter=")
properties_file.gsub!(/error-handler=\/roxy\/error.xqy/, "error-handler=")
elsif app_type == "rest"
# rest applications don't use Roxy's MVC structure, so they can use MarkLogic's rewriter and error handler
# Note: ML8 rest uses the new native rewriter
rewriter_name = (server_version.to_i >= 8) ? "rewriter.xml" : "rewriter.xqy"
properties_file.gsub!(/url-rewriter=\/roxy\/rewrite.xqy/, "url-rewriter=/MarkLogic/rest-api/" + rewriter_name)
properties_file.gsub!(/error-handler=\/roxy\/error.xqy/, "error-handler=/MarkLogic/rest-api/error-handler.xqy")
end
# replace the text =random with a random string
o = (33..126).to_a
properties_file.gsub!(/=random/) do |match|
random = (0...20).map{ o[rand(o.length)].chr }.join
"=#{random}"
end
# Update properties file to set server-version to value specified on command-line
properties_file.gsub!(/server-version=6/, "server-version=#{server_version}")
if ["mvc"].include? app_type
properties_file.gsub!(/application-conf-file=[^\n]*/, 'application-conf-file=src/app/config/config.xqy')
elsif ["rest"].include? app_type
properties_file.gsub!(/application-conf-file=[^\n]*/, 'application-conf-file=src/config/config.xqy')
elsif ["bare"].include? app_type
properties_file.gsub!(/application-conf-file=[^\n]*/, 'application-conf-file=')
end
# save the replacements
open(build_properties, 'w') {|f| f.write(properties_file) }
end
# If this is a rest or hybrid app, set up some initial options
if ["rest", "hybrid"].include? app_type
FileUtils.mkdir_p rest_ext_dir
FileUtils.mkdir_p rest_transforms_dir
FileUtils.mkdir_p options_dir
copy_file sample_options, options_file
copy_file sample_rest_properties, rest_properties
end
if ["rest", "bare"].include? app_type
FileUtils.mkdir_p config_dir
copy_file sample_app_config, app_config
end
target_config = ServerConfig.expand_path(ServerConfig.properties["ml.config.file"])
if !force && !force_config && File.exists?(target_config)
error_msg << "ml-config.xml has already been created."
else
#create clean marklogic configuration file
copy_file sample_config, target_config
end
raise HelpException.new("init", error_msg.join("\n")) if error_msg.length > 0
return true
end
def self.initcpf
if @@is_jar
sample_config = "roxy/sample/pipeline-config.sample.xml"
else
sample_config = ServerConfig.expand_path("#{@@path}/sample/pipeline-config.sample.xml")
end
target_config = ServerConfig.expand_path(ServerConfig.properties["ml.pipeline-config-file"])
force = find_arg(['--force']).present?
if !force && File.exists?(target_config)
raise HelpException.new("initcpf", "cpf configuration has already been created.")
else
copy_file sample_config, target_config
end
return true
end
def self.prompt_server_version
if @@no_prompt
puts 'Required option --server-version=[version] not specified with valid value,
but --no-prompt parameter prevents prompting for password.'
server_version = 0
else
puts 'Required option --server-version=[version] not specified with valid value.
What is the version number of the target MarkLogic server? [7, 8, or 9]'
server_version = STDIN.gets.chomp.to_i
end
if server_version == 0
puts "Defaulting to 9.."
server_version = 9
end
server_version
end
def self.index
if @@no_prompt
raise ExitException.new("--no-prompt parameter prevents prompting for input")
else
puts "What type of index do you want to build?
1 element range index
2 attribute range index"
# TODO:
# 3 field range index
# 4 geospatial index
type = STDIN.gets.chomp.to_i
if type == 1
build_element_index
elsif type == 2
build_attribute_element_index
else
puts "Sorry, I don't know how to do that yet"
end
end
end
def self.request_type
if @@no_prompt
raise ExitException.new("--no-prompt parameter prevents prompting for input")
else
scalar_types = %w[int unsignedInt long unsignedLong float double decimal dateTime
time date gYearMonth gYear gMonth gDay yearMonthDuration dayTimeDuration string anyURI]
puts "What will the scalar type of the index be [1-" + scalar_types.length.to_s + "]? "
i = 1
for t in scalar_types
puts "#{i} #{t}"
i += 1
end
scalar = STDIN.gets.chomp.to_i
scalar_types[scalar - 1]
end
end
def self.request_collation
if @@no_prompt
raise ExitException.new("--no-prompt parameter prevents prompting for input")
else
puts "What is the collation URI (leave blank for the root collation)?"
collation = STDIN.gets.chomp
collation = "http://marklogic.com/collation/" if collation.blank?
collation
end
end
def self.request_range_value_positions
if @@no_prompt
raise ExitException.new("--no-prompt parameter prevents prompting for input")
else
puts "Turn on range value positions? [y/N]"
positions = STDIN.gets.chomp.downcase
if positions == "y"
positions = "true"
else
positions = "false"
end
positions
end
end
def self.inject_index(key, index)
properties = ServerConfig.properties
config_path = ServerConfig.expand_path(properties["ml.config.file"])
existing = File.read(config_path)
existing = existing.gsub(key) { |match| "#{match}\n#{index}" }
File.open(config_path, "w") { |file| file.write(existing) }
end
def self.build_attribute_element_index
if @@no_prompt
raise ExitException.new("--no-prompt parameter prevents prompting for input")
else
scalar_type = request_type
puts "What is the parent element's namespace URI?"
p_uri = STDIN.gets.chomp
puts "What is the parent element's localname?"
p_localname = STDIN.gets.chomp
puts "What is the attribute's namespace URI?"
uri = STDIN.gets.chomp
puts "What is the attribute's localname?"
localname = STDIN.gets.chomp
collation = request_collation if scalar_type == "string"
positions = request_range_value_positions
index = " <range-element-attribute-index>
<scalar-type>#{scalar_type}</scalar-type>
<parent-namespace-uri>#{p_uri}</parent-namespace-uri>
<parent-localname>#{p_localname}</parent-localname>
<namespace-uri>#{uri}</namespace-uri>
<localname>#{localname}</localname>
<collation>#{collation}</collation>
<range-value-positions>#{positions}</range-value-positions>
</range-element-attribute-index>"
properties = ServerConfig.properties
puts "Add this index to #{properties["ml.config.file"]}? [y/N]\n" + index
approve = STDIN.gets.chomp.downcase
if approve == "y"
inject_index("<range-element-attribute-indexes>", index)
puts "Index added"
end
end
end
def self.build_element_index
if @@no_prompt
raise ExitException.new("--no-prompt parameter prevents prompting for input")
else
scalar_type = request_type
puts "What is the element's namespace URI?"
uri = STDIN.gets.chomp
puts "What is the element's localname?"
localname = STDIN.gets.chomp
collation = request_collation if scalar_type == "string" # string
positions = request_range_value_positions
index = " <range-element-index>
<scalar-type>#{scalar_type}</scalar-type>
<namespace-uri>#{uri}</namespace-uri>
<localname>#{localname}</localname>
<collation>#{collation}</collation>
<range-value-positions>#{positions}</range-value-positions>
</range-element-index>"
properties = ServerConfig.properties
puts "Add this index to #{properties["ml.config.file"]}? [y/N]\n" + index
approve = STDIN.gets.chomp.downcase
if approve == "y"
inject_index("<range-element-indexes>", index)
puts "Index added"
end
end
end
def self.howto
begin
optional_require 'open-uri'
optional_require 'nokogiri'
search = ARGV.first
doc = Nokogiri::HTML(open("https://github.com/marklogic/roxy/wiki/_pages"))
pages = doc.css('.content').select do |page|
search == nil or page.text.downcase().include? search
end
selected = 1
if pages.length > 1
count = 0
pages.each do |page|
count = count + 1
puts "#{count} - #{page.text}\n\thttps://github.com/#{page.xpath('a/@href').text}"
end
print "Select a page: "
selected = STDIN.gets.chomp().to_i
if selected == 0
return
end
if selected > pages.length
selected = pages.length
end
end
count = 0
pages.each do |page|
count = count + 1
if count == selected
puts "\n#{page.text}\n\thttps://github.com/#{page.xpath('a/@href').text}"
uri = "https://github.com/#{page.xpath('a/@href').text}"
doc = Nokogiri::HTML(open(uri))
puts doc.css('.markdown-body').text.gsub(/\n\n\n+/, "\n\n")
end
end
rescue NameError => e
puts "Missing library: #{e}"
end
end
def execute_query(query, properties = {})
r = nil
if @server_version == 4
r = execute_query_4 query, properties
elsif @server_version == 5 || @server_version == 6
r = execute_query_5 query, properties
elsif @server_version == 7
r = execute_query_7 query, properties
else # 8 or 9
r = execute_query_8 query, properties
end
raise ExitException.new(r.body) unless r.code.to_i == 200
return r
end
def restart_group(group = nil, legacy = false)
logger.debug "group: #{group}"
logger.debug "legacy: #{legacy}"
if ! group
# Note:
# Restarting partial cluster is unsafe when working with multiple groups.
# Therefor restart entire cluster by default..
group = "cluster"
end
if group == "cluster"
logger.info "Restarting MarkLogic Server cluster of #{@hostname}"
else
logger.info "Restarting MarkLogic Server group #{group}"
end
if @server_version > 7 && !legacy
# MarkLogic 8+, make use of Management REST api and return details of all involved hosts
if group == "cluster"
r = go(%Q{http://#{@properties["ml.server"]}:#{@properties["ml.bootstrap-port"]}/manage/v2?format=json}, "post", {
'Content-Type' => 'application/json'
}, nil, %Q{
{ "operation": "restart-local-cluster" }
})
else
r = go(%Q{http://#{@properties["ml.server"]}:#{@properties["ml.bootstrap-port"]}/manage/v2/groups/#{group}?format=json}, "post", {
'Content-Type' => 'application/json'
}, nil, %Q{
{ "operation": "restart-group" }
})
end
raise ExitException.new(r.body) unless r.code.to_i == 202
return JSON.parse(r.body)['restart']['last-startup']
else
# MarkLogic 7- fallback, restart as before, and only verify restart of bootstrap host
old_timestamp = go(%Q{http://#{@properties["ml.server"]}:8001/admin/v1/timestamp}, "get").body
setup = File.read ServerConfig.expand_path("#{@@path}/lib/xquery/setup.xqy")
r = execute_query %Q{#{setup} setup:do-restart("#{group}")}
logger.debug "code: #{r.code.to_i}"
r.body = parse_body(r.body)
logger.info r.body
return [{
'host-id' => @properties["ml.server"],
'value' => old_timestamp
}]
end
end
def get_host_names
r = go(%Q{http://#{@properties["ml.server"]}:8002/manage/v2/hosts?format=json}, "get")
raise ExitException.new(r.body) unless r.code.to_i == 200
names = { @properties["ml.server"] => @properties["ml.server"] } # ml7 fallback
JSON.parse(r.body)['host-default-list']['list-items']['list-item'].each do |host|
names[host['idref']] = host['nameref']
end
return names
end
def restart
# Default to verified restart
verify = find_arg(['--no-verify']) == nil && find_arg(['--verify']) != 'false'
# Default to using Management Rest api (if available)
legacy = find_arg(['--legacy']) != nil
logger.debug "verify: #{verify}"
logger.debug "legacy: #{legacy}"
group = next_arg("^[^-]")
@ml_username = @properties['ml.bootstrap-user'] || @properties['ml.user']
if @ml_username == @properties['ml.bootstrap-user']
@ml_password = @properties['ml.bootstrap-password']
else
@ml_password = @properties['ml.password']
end
if ! verify
restart_group(group, legacy)
else
host_names = get_host_names()
old_timestamps = restart_group(group, legacy)
# Iterate until all hosts have restarted (or max is reached)
old_timestamps.each do |host|
host_name = host_names[host['host-id']]
old_timestamp = host['value']
print "Verifying restart for #{host_name}"
# Initialize vars for repeated check
retry_count = 0
retry_max = @properties["ml.verify_retry_max"].to_i
retry_interval = [@properties["ml.verify_retry_interval"].to_i, 10].max # 10 sec sleep at least
new_timestamp = old_timestamp
while retry_count < retry_max do
begin
new_timestamp = go(%Q{http://#{host_name}:8001/admin/v1/timestamp}, "get").body
rescue
logger.debug 'Retry attempt ' + retry_count.to_s + ' failed'
end
if new_timestamp != old_timestamp
# Indicates that restart is confirmed successful
break
end
# Retry..
print ".."
sleep retry_interval
retry_count += 1
end
if retry_max < 1
puts ": SKIPPED"
elsif new_timestamp == old_timestamp
puts ": FAILED"
else
puts ": OK"
end
end
end
end
def merge
what = ARGV.shift
raise HelpException.new("merge", "Missing WHAT") unless what
case what
when 'content'
merge_db(@properties['ml.content-db'])
else
raise HelpException.new("merge", "Invalid WHAT")
end
return true
end
def merge_db(target_db)
logger.info "Merging #{target_db} on #{@hostname}"
r = execute_query %Q{
xdmp:merge(
<options xmlns="xdmp:merge">
<merge-timestamp>{xdmp:request-timestamp()}</merge-timestamp>
</options>)
},
{ :db_name => target_db }
logger.debug "code: #{r.code.to_i}"
r.body = parse_body(r.body)
logger.info r.body
end
def reindex
what = ARGV.shift
raise HelpException.new("reindex", "Missing WHAT") unless what
case what
when 'content'
reindex_db(@properties['ml.content-db'])
else
raise HelpException.new("reindex", "Invalid WHAT")
end
return true
end
def reindex_db(target_db)
logger.info "Reindexing #{target_db} on #{@hostname}"
r = execute_query %Q{
xquery version "1.0-ml";
import module namespace admin = "http://marklogic.com/xdmp/admin"
at "/MarkLogic/admin.xqy";
admin:save-configuration-without-restart(
admin:database-set-reindexer-timestamp(
admin:get-configuration(),
xdmp:database("#{target_db}"),
xdmp:request-timestamp()
)
)
},
{ :db_name => target_db }
logger.debug "code: #{r.code.to_i}"
r.body = parse_body(r.body)
logger.info r.body
end
def properties_map
entries = []
@properties.each do |k, v|
entries.push %Q{map:entry("#{k}", "#{v.xquery_safe}")}
end
"map:new((\n" + entries.join(",\n ")+ "))"
end
def config
setup = File.read ServerConfig.expand_path("#{@@path}/lib/xquery/setup.xqy")
query = %Q{
#{setup}
try {
xdmp:quote(
setup:rewrite-config(#{get_config}, #{properties_map}, (), fn:true()),
<options xmlns="xdmp:quote">
<indent>yes</indent>
<indent-untyped>yes</indent-untyped>
</options>
)
} catch($ex) {
xdmp:log($ex),
fn:concat($ex/err:format-string/text(), ' See MarkLogic Server error log for more details.')
}
}
r = execute_query query
logger.debug "code: #{r.code.to_i}"
r.body = parse_body(r.body)
logger.info r.body
return true
end
def bootstrap
raise ExitException.new("Bootstrap requires the target environment's hostname to be defined") unless @hostname.present?
@ml_username = @properties['ml.bootstrap-user'] || @properties['ml.user']
if @ml_username == @properties['ml.bootstrap-user']
@ml_password = @properties['ml.bootstrap-password']
else
@ml_password = @properties['ml.password']
end
internals = find_arg(['--replicate-internals'])
if internals
dointernals = 'internals'
# Number of hosts
r = execute_query %Q{ fn:count(xdmp:hosts()) }
r.body = parse_body(r.body)
# check cluster size
nr = find_arg(['--nr-replicas'])
if nr
if nr.downcase == "max"
nr = r.body.to_i - 1
else
nr = nr.to_i
end
else
nr = 1
end
raise ExitException.new("Increase nr-replicas, minimum is 1") if nr < 1
raise ExitException.new("Adding #{nr} replicas to internals requires at least a #{nr + 1} node cluster") if r.body.to_i <= nr
logger.info "Bootstrapping replicas for #{@properties['ml.system-dbs']} on #{@hostname}..."
# build custom ml-config
assigns = ''
internals = @properties['ml.system-dbs'].split ','
internals.each do |db|
repnames = %Q{
<replica-name>#{db}-rep1</replica-name>}
repassigns = %Q{
<assignment>
<forest-name nr-replicas="#{nr}">#{db}-rep1</forest-name>
</assignment>}
assigns = assigns + %Q{
<!-- #{db} -->
<assignment>
<forest-name>#{db}</forest-name>
<replica-names>#{repnames}
</replica-names>
</assignment>#{repassigns}}
end
databases = ''
internals.each do |db|
databases = databases + %Q{
<!-- #{db} -->
<database>
<database-name>#{db}</database-name>
<forests>
<forest-id name="#{db}"/>
</forests>
</database>}
end
config = %Q{
<configuration default-group="#{@properties['ml.group']}">
<assignments xmlns="http://marklogic.com/xdmp/assignments">#{assigns}
</assignments>
<databases xmlns="http://marklogic.com/xdmp/database">#{databases}
</databases>
</configuration>
}
logger.debug config
else
dointernals = ''
logger.info "Bootstrapping your project into MarkLogic #{@properties['ml.server-version']} on #{@hostname}..."
config = get_config
end
apply_changes = find_arg(['--apply-changes'])
if apply_changes == nil or apply_changes == ""
apply_changes = "all"
end
setup = File.read(ServerConfig.expand_path("#{@@path}/lib/xquery/setup.xqy"))
r = execute_query %Q{#{setup} setup:do-setup(#{config}, "#{apply_changes},#{dointernals}", #{properties_map})}
logger.debug "code: #{r.code.to_i}"
r.body = parse_body(r.body)
logger.debug r.body
if r.body.match("error log")
logger.error r.body
raise ExitException.new("... Bootstrap FAILED")
return false
else
if r.body.match("(note: restart required)")
logger.warn "************************************"
logger.warn "*** RESTART OF MARKLOGIC IS REQUIRED"
logger.warn "************************************"
end
logger.info "... Bootstrap Complete"
return true
end
end
def clean_replicas_state
internals = find_arg(['--internal-replicas'])
if internals == nil
internals = ''
logger.info "Cleaning application forest decommissioned replica state"
else
logger.info "Cleaning interal forest decommissioned replica state"
internals = 'internals'
end
setup = File.read(ServerConfig.expand_path("#{@@path}/lib/xquery/setup.xqy"))
r = execute_query %Q{#{setup} setup:do-clean-replicas-state("#{internals}")}
if r.body.match("error log")
logger.error r.body
logger.error "... Cleaning replicas FAILED"
return false
end
logger.info r.body
logger.info "... Cleaning replicas Complete"
return true
end
def clean_replicas
internals = find_arg(['--internal-replicas'])
if internals == nil
internals = ''
logger.info "Cleaning application forest decommissioned replicas, if ready."
config = get_config
else
logger.info "Cleaning interal forest decommissioned replicas, if ready."
internals = 'internals'
config = get_config
end
setup = File.read(ServerConfig.expand_path("#{@@path}/lib/xquery/setup.xqy"))
r = execute_query %Q{#{setup} setup:do-clean-replicas(#{config}, "#{internals}", #{properties_map})}
logger.debug "code: #{r.code.to_i}"
r.body = parse_body(r.body)
logger.debug r.body
if r.body.match("error log")
logger.error r.body
logger.error "... Cleaning replicas FAILED"
return false
end
if r.body.match("Replicas not ready")
logger.error r.body
return false
end
if r.body.match("nothing to do")
logger.error r.body
logger.info "No replicas were found to be retired. Nothing to do."
return false
end