This repository has been archived by the owner on Aug 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 516
/
v2_cart_model.rb
1679 lines (1421 loc) · 72.2 KB
/
v2_cart_model.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 2013 Red Hat, Inc.
#
# 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 'rubygems'
require 'shellwords'
require 'openshift-origin-node/model/application_repository'
require 'openshift-origin-node/model/cartridge_repository'
require 'openshift-origin-common/models/manifest'
require 'openshift-origin-node/model/pub_sub_connector'
require 'openshift-origin-node/model/gear_registry'
require 'openshift-origin-node/utils/shell_exec'
require 'openshift-origin-node/utils/selinux_context'
require 'openshift-origin-node/utils/node_logger'
require 'openshift-origin-node/utils/cgroups'
require 'openshift-origin-node/utils/sdk'
require 'openshift-origin-node/utils/environ'
require 'openshift-origin-common/utils/path_utils'
require 'openshift-origin-node/utils/application_state'
require 'openshift-origin-node/utils/managed_files'
require 'openshift-origin-node/utils/sanitize'
module OpenShift
module Runtime
class MissingCartridgeIdentError < RuntimeError
end
class FileLockError < Exception
attr_reader :filename
def initialize(msg = nil, filename)
super(msg)
@filename = filename
end
end
class FileUnlockError < Exception
attr_reader :filename
def initialize(msg = nil, filename)
super(msg)
@filename = filename
end
end
class V2CartridgeModel
include NodeLogger
def initialize(config, container, state, hourglass)
@config = config
@container = container
@state = state
@timeout = 30
@cartridges = {}
@hourglass = hourglass
end
def stop_lock
PathUtils.join(@container.container_dir, 'app-root', 'runtime', '.stop_lock')
end
def stop_lock?
File.exists?(stop_lock)
end
##
# Yields a +Cartridge+ instance for each cartridge in the gear.
def each_cartridge
process_cartridges do |cartridge_dir|
cartridge = get_cartridge_from_directory(File.basename(cartridge_dir))
yield cartridge
end
end
##
# Returns the primary +Cartridge+ in the gear as specified by the
# +OPENSHIFT_PRIMARY_CARTRIDGE_DIR+ environment variable, or +Nil+ if
# no primary cartridge is present.
def primary_cartridge
env = ::OpenShift::Runtime::Utils::Environ.for_gear(@container.container_dir)
primary_cart_dir = env['OPENSHIFT_PRIMARY_CARTRIDGE_DIR']
raise "No primary cartridge detected in gear #{@container.uuid}" unless primary_cart_dir and !primary_cart_dir.empty?
return get_cartridge_from_directory(File.basename(primary_cart_dir))
end
##
# Returns the +Cartridge+ in the gear whose +web_proxy+ flag is set to
# true, nil otherwise
def web_proxy
each_cartridge do |cartridge|
return cartridge if cartridge.web_proxy?
end
nil
end
##
# Returns true if the primary +Cartridge+ is also the +web_proxy+.
# This occurs in the case of applications that have a web cartridge
# that is deployed on a platform different than the web proxy's.
def standalone_web_proxy?
(web_proxy != nil) and (web_proxy.name == primary_cartridge.name)
end
##
# Detects and returns a builder +Cartridge+ in the gear if present, otherwise +nil+.
def builder_cartridge
builder_cart = nil
each_cartridge do |c|
if c.categories.include? 'ci_builder'
builder_cart = c
break
end
end
builder_cart
end
# FIXME: Once Broker/Node protocol updated to provided necessary information this hack must go away
def map_cartridge_name(cartridge_name)
results = cartridge_name.split(/\-([0-9\.]+)$/)
if !Runtime::Manifest.valid_cartridge_name?(cartridge_name)
raise "Invalid cartridge identifier '#{cartridge_name}': expected name-version"
end
results
end
def cartridge_directory(cart_name)
name, _ = map_cartridge_name(cart_name)
cart_dir = Dir.glob(PathUtils.join(@container.container_dir, "#{name}"))
raise "Ambiguous cartridge name #{cart_name}: found #{cart_dir}:#{cart_dir.size}" if 1 < cart_dir.size
raise "Cartridge directory not found for #{cart_name}" if 1 > cart_dir.size
File.basename(cart_dir.first)
end
# Load the cartridge's local manifest from the Broker token 'name-version'
def get_cartridge(cart_name)
unless @cartridges.has_key? cart_name
cart_dir = ''
begin
cart_dir = cartridge_directory(cart_name)
@cartridges[cart_name] = get_cartridge_from_directory(cart_dir)
rescue Exception => e
logger.error e.message
logger.error e.backtrace.join("\n")
raise "Failed to get cartridge '#{cart_name}' from #{cart_dir} in gear #{@container.uuid}: #{e.message}"
end
end
@cartridges[cart_name]
end
# Load cartridge's local manifest from cartridge directory name
def get_cartridge_from_directory(directory)
raise "Directory name is required" if (directory == nil || directory.empty?)
unless @cartridges.has_key? directory
cartridge_path = PathUtils.join(@container.container_dir, directory)
manifest_path = PathUtils.join(cartridge_path, 'metadata', 'manifest.yml')
ident_path = Dir.glob(PathUtils.join(cartridge_path, 'env', "OPENSHIFT_*_IDENT")).first
raise "Cartridge manifest not found: #{manifest_path} missing" unless File.exists?(manifest_path)
raise MissingCartridgeIdentError, "Cartridge Ident not found in #{cartridge_path}" unless ident_path
_, _, version, _ = Runtime::Manifest.parse_ident(IO.read(ident_path))
@cartridges[directory] = Manifest.new(manifest_path, version, :file, @container.container_dir)
end
@cartridges[directory]
end
# Load the cartridge's local manifest from the Broker token 'name-version'
def get_cartridge_fallback(cart_name)
directory = cartridge_directory(cart_name)
_, version = map_cartridge_name(cart_name)
raise "Directory name is required" if (directory == nil || directory.empty?)
cartridge_path = PathUtils.join(@container.container_dir, directory)
manifest_path = PathUtils.join(cartridge_path, 'metadata', 'manifest.yml')
raise "Cartridge manifest not found: #{manifest_path} missing" unless File.exists?(manifest_path)
Manifest.new(manifest_path, version, :file, @container.container_dir)
end
# Optionally back up the gear directory contents to a
# user-specified "dump site" if a gear is rolled back due to
# failure during app create
def archive_gear()
archive_dir = @config.get("ARCHIVE_DESTROYED_GEARS_DIR", nil)
if @config.get_bool("ARCHIVE_DESTROYED_GEARS", false)
if not archive_dir
logger.warn "Cannot archive destroyed gears; ARCHIVE_DESTROYED_GEARS_DIR is not set in node.conf"
return
elsif not File.directory? archive_dir
logger.warn "Cannot archive destroyed gears; #{archive_dir} is not a directory"
return
elsif not File.writable? archive_dir
logger.warn "Cannot archive destroyed gears; #{archive_dir} is not writable"
return
elsif File.world_readable? archive_dir or File.world_writable? archive_dir
logger.warn "Cannot archive destroyed gears; #{archive_dir} is world readable and/or writable"
return
end
archive_filespec = PathUtils.join(archive_dir, "#{@container.application_name}-#{@container.uuid}.tar.bz2")
if File.exists? archive_filespec
logger.warn "Cannot archive destroyed gears; #{archive_filespec} already exists"
else
command = "tar --selinux --acls --preserve --create --bzip2 --file=#{archive_filespec} #{@container.container_dir}"
tarout, tarerr, rc = Utils.oo_spawn(command)
unless rc == 0
logger.warn "Error occurred running \"#{command}\"; rc=#{rc}, stdout=#{tarout}, stderr=#{tarerr}"
FileUtils.rm_f archive_filespec
end
end
end
end
# destroy(skip_hooks = false, is_group_rollback = false) -> [buffer, '', 0]
#
# Remove all cartridges from a gear and delete the gear. Accepts
# and discards any parameters to comply with the signature of V1
# require, which accepted a single argument.
#
# destroy() => ['', '', 0]
def destroy(skip_hooks = false, is_group_rollback = false)
logger.info('V2 destroy')
buffer = ''
begin
# only archive if app create failed
archive_gear if is_group_rollback
unless skip_hooks
each_cartridge do |cartridge|
unlock_gear(cartridge, false) do |c|
begin
buffer << cartridge_teardown(c.directory, false)
rescue ::OpenShift::Runtime::Utils::ShellExecutionException => e
logger.warn("Cartridge teardown operation failed on gear #{@container.uuid} for cartridge #{c.directory}: #{e.message} (rc=#{e.rc})")
end
end
end
end
rescue Exception => e
logger.warn("Cartridge teardown operation failed on gear #{@container.uuid} for some cartridge: #{e.message}")
buffer << "CLIENT_ERROR: Abandoned cartridge teardowns. There may be extraneous data left on system."
end
# FIXME: V1 contract is there a better way?
[buffer, '', 0]
end
# tidy() -> nil
#
# Run tidy operation on each cartridge on a gear
#
# tidy()
def tidy
each_cartridge do |cartridge|
begin
output = do_control('tidy', cartridge)
rescue ::OpenShift::Runtime::Utils::ShellExecutionException => e
logger.warn("Tidy operation failed for cartridge #{cartridge.name} on "\
"gear #{@container.uuid}: #{e.message} (rc=#{e.rc}), output=#{output}")
end
end
end
# configure(Ident, template_git_url, manifest) -> stdout
#
# Add a cartridge to a gear
#
# configure(ident)
# configure(ident, 'git://')
# configure(ident, 'git://', 'git://')
def configure(ident, template_git_url = nil, manifest = nil)
output = ''
cartridge = if manifest
logger.debug("Loading #{ident.name} from manifest for #{@container.uuid}")
Runtime::Manifest.new(manifest, ident.software_version)
else
CartridgeRepository.instance.select(
ident.cartridge_vendor,
ident.name,
ident.software_version)
end
::OpenShift::Runtime::Utils::Cgroups.new(@container.uuid).boost do
create_cartridge_directory(cartridge, ident.software_version)
# Note: the following if statement will check the following criteria long-term:
# 1. Is the app scalable?
# 2. Is this the head gear?
# 3. Is this the first time the platform has generated an ssh key?
#
# In the current state of things, the following check is sufficient to test all
# of these criteria, and we do not have a way to explicitly check the first two
# criteria. However, it should be considered a TODO to add more explicit checks.
if cartridge.web_proxy?
::OpenShift::Runtime::GearRegistry.new(@container)
end
create_private_endpoints(cartridge)
unlock_gear(cartridge) do |c|
expected_entries = Dir.glob(PathUtils.join(@container.container_dir, '*'))
create_dependency_directories(cartridge)
output << cartridge_action(cartridge, 'setup', ident.software_version, true)
output << process_erb_templates(c)
output << cartridge_action(cartridge, 'install', ident.software_version)
actual_entries = Dir.glob(PathUtils.join(@container.container_dir, '*'))
illegal_entries = actual_entries - expected_entries
unless illegal_entries.empty?
raise RuntimeError.new(
"Cartridge created the following directories in the gear home directory: #{illegal_entries.join(', ')}")
end
output << populate_gear_repo(c.directory, template_git_url) if populate_repository?(cartridge, template_git_url)
end
validate_cartridge(cartridge)
output << connect_frontend(cartridge)
end
logger.info "configure output: #{Runtime::Utils.sanitize_credentials(output)}"
return output
rescue ::OpenShift::Runtime::Utils::ShellExecutionException => e
rc_override = e.rc < 100 ? 157 : e.rc
raise ::OpenShift::Runtime::Utils::Sdk.translate_shell_ex_for_client(e, rc_override)
rescue => e
logger.error "Unexpected error during configure: #{e.message} (#{e.class})\n #{e.backtrace.join("\n ")}"
ex = RuntimeError.new(Utils::Sdk.translate_out_for_client("Unexpected error: #{e.message}", :error))
ex.set_backtrace(e.backtrace)
raise ex
end
def validate_cartridge(manifest)
illegal_overrides = ::OpenShift::Runtime::Utils::Environ.load(PathUtils.join(@container.container_dir, '.env')).keys &
::OpenShift::Runtime::Utils::Environ.load(PathUtils.join(@container.container_dir, manifest.directory, 'env')).keys
# Older gears may have these and cartridges are allowed to override them
illegal_overrides.delete('LD_LIBRARY_PATH')
illegal_overrides.delete('PATH')
unless illegal_overrides.empty?
raise RuntimeError.new(
"Cartridge attempted to override the following gear environment variables: #{illegal_overrides.join(', ')}")
end
end
def post_install(cartridge, software_version, options = {})
output = cartridge_action(cartridge, 'post_install', software_version)
options[:out].puts(output) if options[:out]
output
end
def post_configure(cartridge_name)
output = ''
name, software_version = map_cartridge_name(cartridge_name)
cartridge = get_cartridge(name)
::OpenShift::Runtime::Utils::Cgroups.new(@container.uuid).boost do
if cartridge.name == primary_cartridge.name and empty_repository?
output << "CLIENT_MESSAGE: An empty Git repository has been created for your application. Use 'git push' to add your code."
else
output << start_cartridge('start', cartridge, user_initiated: true)
end
output << cartridge_action(cartridge, 'post_install', software_version)
end
logger.info("post-configure output: #{output}")
output
rescue ::OpenShift::Runtime::Utils::ShellExecutionException => e
raise ::OpenShift::Runtime::Utils::Sdk.translate_shell_ex_for_client(e, 157)
end
# deconfigure(Ident) -> nil
#
# Remove cartridge from gear with the following workflow:
#
# 1. Delete private endpoints
# 2. Stop the cartridge
# 3. Execute the cartridge `control teardown` action
# 4. Disconnect the frontend for the cartridge
# 5. Delete the cartridge directory
#
# If the cartridge stop or teardown operations fail, the error output will be
# captured, but the frontend will still be disconnect and the cartridge directory
# will be deleted.
#
# deconfigure(ident)
def deconfigure(ident)
teardown_output = ''
cartridge = nil
begin
cartridge = get_cartridge(ident.to_name)
rescue
teardown_output << "CLIENT_ERROR: Corrupted cartridge #{ident} removed. There may be extraneous data left on system.\n"
logger.warn("Corrupted cartridge #{@container.uuid}/#{ident} removed. There may be extraneous data left on system.")
begin
logger.warn("Corrupted cartridge #{@container.uuid}/#{ident}. Attempting to auto-correct for deconfigure using local manifest.yml.")
cartridge = get_cartridge_fallback(ident.to_name)
rescue
logger.warn("Corrupted cartridge #{@container.uuid}/#{ident}. Attempting to auto-correct for deconfigure resorting to CartridgeRepository.")
begin
cartridge = CartridgeRepository.instance.select(ident.cartridge_vendor,
ident.name,
ident.software_version)
rescue
logger.warn("Cartridge #{ident} not found in CartridgeRepostory.")
teardown_output << "Cartridge #{ident} not found on the gear or in the CartridgeRepository. It is most likely a downloaded cartridge that failed to configure and was removed."
return teardown_output
end
end
write_environment_variables(
PathUtils.join(@container.container_dir, cartridge.directory, 'env'),
{"#{cartridge.short_name}_IDENT" => ident.to_s})
end
delete_private_endpoints(cartridge)
::OpenShift::Runtime::Utils::Cgroups.new(@container.uuid).boost do
begin
stop_cartridge(cartridge, user_initiated: true)
unlock_gear(cartridge, false) do |c|
teardown_output << cartridge_teardown(c.directory)
end
rescue ::OpenShift::Runtime::Utils::ShellExecutionException => e
teardown_output << ::OpenShift::Runtime::Utils::Sdk::translate_out_for_client(e.stdout, :error)
teardown_output << ::OpenShift::Runtime::Utils::Sdk::translate_out_for_client(e.stderr, :error)
rescue RuntimeError => e
teardown_output << "\n#{e.message}"
ensure
disconnect_frontend(cartridge)
delete_cartridge_directory(cartridge)
end
end
teardown_output
end
# unlock_gear(cartridge_name) -> nil
#
# Prepare the given cartridge for the cartridge author
#
# v2_cart_model.unlock_gear('php-5.3')
def unlock_gear(cartridge, relock=true)
begin
do_unlock(@container.locked_files(cartridge))
yield cartridge
ensure
do_lock(relock ? @container.locked_files(cartridge) : [])
end
nil
end
# do_unlock_gear(array of file names) -> array
#
# Take the given array of file system entries and prepare them for the cartridge author
#
# v2_cart_model.do_unlock_gear(entries)
def do_unlock(entries)
entries.each do |entry|
if entry.end_with?('/')
entry.chomp!('/')
FileUtils.mkpath(entry, mode: 0755) unless File.exist? entry
else
# FileUtils.touch not used as it doesn't support mode
File.new(entry, File::CREAT|File::TRUNC|File::WRONLY, 0644).close() unless File.exist?(entry)
end
# It is expensive doing one file at a time but...
# ...it allows reporting on the failed command at the file level
# ...we don't have to worry about the length of argv
begin
@container.set_rw_permission(entry)
rescue Exception => e
raise FileUnlockError.new("Failed to unlock file system entry [#{entry}]: #{e}",
entry)
end
end
begin
@container.set_rw_permission(@container.container_dir)
rescue Exception => e
raise FileUnlockError.new(
"Failed to unlock gear home [#{@container.container_dir}]: #{e}",
@container.container_dir)
end
end
# do_lock_gear(array of file names) -> array
#
# Take the given array of file system entries and prepare them for the application developer
# v2_cart_model.do_lock_gear(entries)
def do_lock(entries)
# It is expensive doing one file at a time but...
# ...it allows reporting on the failed command at the file level
# ...we don't have to worry about the length of argv
entries.each do |entry|
begin
@container.set_ro_permission(entry)
rescue Exception => e
raise OpenShift::Runtime::FileLockError.new("Failed to lock file system entry [#{entry}]: #{e}",
entry)
end
end
begin
@container.set_ro_permission(@container.container_dir)
rescue Exception => e
raise OpenShift::Runtime::FileLockError.new("Failed to lock gear home [#{@container.container_dir}]: #{e}",
@container.container_dir)
end
end
# create_cartridge_directory(Manifest, version) -> nil
#
# Create the cartridges home directory
#
# v2_cart_model.create_cartridge_directory(manifest, '5.3')
def create_cartridge_directory(cartridge, software_version)
logger.info("Creating cartridge directory #{@container.uuid}/#{cartridge.directory}")
target = PathUtils.join(@container.container_dir, cartridge.directory)
CartridgeRepository.instantiate_cartridge(cartridge, target)
ident = Runtime::Manifest.build_ident(cartridge.cartridge_vendor,
cartridge.name,
software_version,
cartridge.cartridge_version)
envs = {}
envs["#{cartridge.short_name}_DIR"] = target + File::SEPARATOR
envs["#{cartridge.short_name}_IDENT"] = ident
write_environment_variables(PathUtils.join(target, 'env'), envs)
envs.clear
envs['namespace'] = @container.namespace if @container.namespace
# If there's not already a primary cartridge on the gear, assume
# the new cartridge is the primary.
current_gear_env = ::OpenShift::Runtime::Utils::Environ.for_gear(@container.container_dir)
unless current_gear_env['OPENSHIFT_PRIMARY_CARTRIDGE_DIR']
envs['primary_cartridge_dir'] = target + File::SEPARATOR
logger.info("Cartridge #{cartridge.name} recorded as primary within gear #{@container.uuid}")
end
unless envs.empty?
write_environment_variables(PathUtils.join(@container.container_dir, '.env'), envs)
end
# Gear level actions: Placed here to be off the V1 code path...
old_path = PathUtils.join(@container.container_dir, '.env', 'PATH')
File.delete(old_path) if File.file? old_path
secure_cartridge(cartridge.short_name, @container.uid, @container.gid, target)
logger.info("Created cartridge directory #{@container.uuid}/#{cartridge.directory}")
nil
end
# Creates cartridge dependency directories listed in managed_files.yml.
#
# The directories are created in ~/app-root/runtime/dependencies and/or
# ~/app-root/runtime/build-dependencies.
#
# This method also creates symlinks from the cartridge directory to the appropriate
# symlink in ~/app-root/runtime/{dependencies,build-dependencies}. For example:
#
# ~/php/phplib -> ~/app-root/runtime/dependencies/php/phplib
def create_dependency_directories(cartridge)
%w(build-dependencies dependencies).each do |dependencies_dir_name|
if dependencies_dir_name == 'build-dependencies'
dirs = @container.build_dependency_dirs(cartridge)
else
dirs = @container.dependency_dirs(cartridge)
end
dirs.each do |entry|
if entry.is_a?(String)
# e.g. phplib
link = target = entry
else
# e.g. jbossas/standalone/deployments
link = entry.keys[0]
# e.g. jbossas/deployments
target = entry.values[0]
end
# create the target dir inside the runtime dir
dependencies_dir = PathUtils.join(@container.container_dir, 'app-root', 'runtime', dependencies_dir_name)
FileUtils.mkdir_p(PathUtils.join(dependencies_dir, target))
full_link = PathUtils.join(@container.container_dir, link)
# if the link is something like foo/bar/baz or jbossas/standalone/deployments,
# need to mkdir -p everything up to the link (foo/bar or jbossas/standalone)
#
# also need to chown -R the first directory in the path that is new, e.g.
# if jbossas exists but standalone is new, chown -R standalone
if link.count('/') > 0
parts = link.split('/')
# start the path at the home dir
path = @container.container_dir
parts.each do |part|
# check each segment of the link
path = PathUtils.join(path, part)
# if the path exists, skip to the next one
next if File.exist?(path)
# if the path doesn't exist, exit the loop
#
# path is now either the first dir in the link's path that doesn't exist
# or it's the link itself
break
end
# now that we've figured out the portion of the link path that doesn't exist
# go ahead and create all the parent dirs for the link
FileUtils.mkdir_p(PathUtils.join(@container.container_dir, parts[0..-2]))
# if the path != the full link, we need to change ownership for the new
# dir and below
if path != full_link
PathUtils.oo_chown_R(@container.uid, @container.gid, path)
end
end
full_target = PathUtils.join(@container.container_dir, 'app-root', 'runtime', dependencies_dir_name, target)
# the link only needs to be created when the cartridge is installed,
# which means it's running via mcollective as root
#
# once the link exists, it should never need to change and does not
# need to be recreated during a clean build
if !File.exist?(full_link)
FileUtils.ln_s(full_target, full_link)
# make sure the symlink is owned by the gear user
PathUtils.oo_lchown(@container.uid, @container.gid, full_link)
end
# in case anything was created below the dependencies dir, correct its ownership
PathUtils.oo_chown_R(@container.uid, @container.gid, dependencies_dir)
end
end
end
def secure_cartridge(short_name, uid, gid=uid, cartridge_home)
@container.set_rw_permission_R(cartridge_home)
files = ManagedFiles::IMMUTABLE_FILES.collect do |file|
file = file.gsub('*', short_name)
file = PathUtils.join(cartridge_home, file)
file if File.exist?(file)
end || []
files.compact!
unless files.empty?
@container.set_ro_permission(files)
FileUtils.chmod(0644, files)
end
end
##
# Write out environment variables.
def write_environment_variables(path, hash, prefix = true)
FileUtils.mkpath(path) unless File.exist? path
hash.each_pair do |k, v|
name = k.to_s.upcase
if prefix
name = "OPENSHIFT_#{name}"
end
File.open(PathUtils.join(path, name), 'w', 0666) do |f|
f.write(v)
end
end
end
def delete_cartridge_directory(cartridge)
logger.info("Deleting cartridge directory for #{@container.uuid}/#{cartridge.directory}")
# TODO: rm_rf correct?
FileUtils.rm_rf(PathUtils.join(@container.container_dir, cartridge.directory))
logger.info("Deleted cartridge directory for #{@container.uuid}/#{cartridge.directory}")
end
# :call-seq:
# model.populate_gear_repo(cartridge name) => nil
# model.populate_gear_repo(cartridge name, application git template url) -> nil
#
# Populate the gear git repository with a sample application
#
# model.populate_gear_repo('ruby-1.9')
# model.populate_gear_repo('ruby-1.9', 'http://rails-example.example.com')
def populate_gear_repo(cartridge_name, template_url = nil)
logger.info "Creating gear repo for #{@container.uuid}/#{cartridge_name} from `#{template_url}`"
repo = ApplicationRepository.new(@container)
if template_url.nil?
repo.populate_from_cartridge(cartridge_name)
elsif OpenShift::Git.empty_clone_spec?(template_url)
repo.populate_empty(cartridge_name)
else
repo.populate_from_url(cartridge_name, template_url)
end
if repo.exist?
repo.archive(PathUtils.join(@container.container_dir, 'app-root', 'runtime', 'repo'), 'master')
end
""
end
# process_erb_templates(cartridge_name) -> nil
#
# Search cartridge for any remaining <code>erb</code> files render them
def process_erb_templates(cartridge)
buffer = ''
directory = PathUtils.join(@container.container_dir, cartridge.name)
logger.info "Processing ERB templates for #{cartridge.name}"
env = ::OpenShift::Runtime::Utils::Environ.for_gear(@container.container_dir, directory)
erbs = @container.processed_templates(cartridge).map { |x| PathUtils.join(@container.container_dir, x) }
erbs.delete_if do |erb_file|
reject = !File.exists?(erb_file)
if reject
buffer << "CLIENT_ERROR: File declared in processed_templates does not exist and will not be rendered: #{erb_file}"
end
reject
end
render_erbs(env, erbs)
buffer
end
# cartridge_action(cartridge, action, software_version, render_erbs) -> buffer
#
# Returns the results from calling a cartridge's action script.
# Includes <code>--version</code> if provided.
# Raises exception if script fails
#
# stdout = cartridge_action(cartridge_obj)
def cartridge_action(cartridge, action, software_version, render_erbs=false)
logger.info "Running #{action} for #{@container.uuid}/#{cartridge.directory}"
cartridge_home = PathUtils.join(@container.container_dir, cartridge.directory)
action = PathUtils.join(cartridge_home, 'bin', action)
return "" unless File.exists? action
# Cache system + scaled env vars + user_vars
app_env = ::OpenShift::Runtime::Utils::Environ.for_gear(@container.container_dir)
# Cache system env vars
gear_env_home = PathUtils.join(@container.container_dir, '.env')
gear_env = Utils::Environ.load(gear_env_home)
# Cache user env vars
user_env_home = PathUtils.join(gear_env_home, 'user_vars')
user_env = Utils::Environ.load(user_env_home)
cartridge_env_home = PathUtils.join(cartridge_home, 'env')
cartridge_env = Utils::Environ.load(cartridge_env_home)
user_env.delete_if { |name, _| name != 'OPENSHIFT_SECRET_TOKEN' and gear_env.has_key?(name) }
cartridge_env.delete('PATH')
cartridge_env = app_env.merge(cartridge_env).merge(user_env)
if render_erbs
erbs = Dir.glob(cartridge_env_home + '/*.erb', File::FNM_DOTMATCH).select { |f| File.file?(f) }
render_erbs(cartridge_env, erbs)
cartridge_env = Utils::Environ.load(cartridge_env_home)
cartridge_env.delete('PATH')
cartridge_env = app_env.merge(cartridge_env).merge(user_env)
end
action << " --version #{software_version}"
out, _, _ = @container.run_in_container_context(action,
env: cartridge_env,
chdir: cartridge_home,
timeout: @hourglass.remaining,
expected_exitstatus: 0)
logger.info("Ran #{action} for #{@container.uuid}/#{cartridge.directory}\n#{Runtime::Utils.sanitize_credentials(out)}")
out
end
# render_erbs(program environment as a hash, erbs) -> nil
#
# Run <code>erb</code> against each template file submitted
#
# v2_cart_model.render_erbs({HOMEDIR => '/home/no_place_like'}, ['/var/lib/openshift/user/cart/foo.erb', ...])
def render_erbs(env, erbs)
erbs.each do |file|
begin
@container.run_in_container_context(%Q{/usr/bin/oo-erb -S 2 -- #{file} > #{file.chomp('.erb')}},
env: env,
chdir: @container.container_dir,
timeout: @hourglass.remaining,
expected_exitstatus: 0)
rescue ::OpenShift::Runtime::Utils::ShellExecutionException => e
logger.info("Failed to render ERB #{file}: #{e.stderr}")
else
begin
File.delete(file)
rescue Errno::ENOENT
# already gone for some reason; ignore it
end
end
end
nil
end
# cartridge_teardown(cartridge_name, remove_cartridge_dir) -> buffer
#
# Returns the output from calling the cartridge's teardown script.
# Raises exception if script fails
#
# stdout = cartridge_teardown('php-5.3')
def cartridge_teardown(cartridge_name, remove_cartridge_dir=true)
cartridge_home = PathUtils.join(@container.container_dir, cartridge_name)
env = ::OpenShift::Runtime::Utils::Environ.for_gear(@container.container_dir, cartridge_home)
teardown = PathUtils.join(cartridge_home, 'bin', 'teardown')
return "" unless File.exists? teardown
return "#{teardown}: is not executable\n" unless File.executable? teardown
# FIXME: Will anyone retry if this reports error, or should we remove from disk no matter what?
buffer, err, _ = @container.run_in_container_context(teardown,
env: env,
chdir: cartridge_home,
timeout: @hourglass.remaining,
expected_exitstatus: 0)
buffer << err
FileUtils.rm_r(cartridge_home) if remove_cartridge_dir
logger.info("Ran teardown for #{@container.uuid}/#{cartridge_name}")
buffer
end
# Expose an endpoint for a cartridge through the port proxy.
#
# Returns nil on success, or raises an exception if any errors occur: all errors
# here are considered fatal.
def create_public_endpoint(cartridge, endpoint, private_ip)
public_port = @container.create_public_endpoint(private_ip, endpoint.private_port)
@container.add_env_var(endpoint.public_port_name, public_port)
logger.info("Created public endpoint for cart #{cartridge.name} in gear #{@container.uuid}: "\
"[#{endpoint.public_port_name}=#{public_port}]")
end
def list_proxy_mappings
proxied_ports = []
gear_env = ::OpenShift::Runtime::Utils::Environ.for_gear(@container.container_dir)
each_cartridge do |cartridge|
cartridge.endpoints.each do |endpoint|
next if gear_env[endpoint.public_port_name].nil?
proxied_ports << {
:private_ip_name => endpoint.private_ip_name,
:public_port_name => endpoint.public_port_name,
:private_ip => gear_env[endpoint.private_ip_name],
:private_port => endpoint.private_port,
:proxy_port => gear_env[endpoint.public_port_name],
}
end
end
proxied_ports
end
# Allocates and assigns private IP/port entries for a cartridge
# based on endpoint metadata for the cartridge.
#
# Returns nil on success, or raises an exception if any errors occur: all errors
# here are considered fatal.
def create_private_endpoints(cartridge)
raise "Cartridge is required" unless cartridge
return unless cartridge.endpoints && cartridge.endpoints.length > 0
logger.info "Creating #{cartridge.endpoints.length} private endpoints for #{@container.uuid}/#{cartridge.directory}"
env = ::OpenShift::Runtime::Utils::Environ.for_gear(@container.container_dir, PathUtils.join(@container.container_dir, cartridge.directory))
allocated_ips = {}
allocated_endpoints = []
cartridge.endpoints.each do |endpoint|
# Reuse previously allocated IPs of the same name. When recycling
# an IP, double-check that it's not bound to the target port, and
# bail if it's unexpectedly bound.
unless allocated_ips.has_key?(endpoint.private_ip_name)
if env.has_key?(endpoint.private_ip_name)
allocated_ips[endpoint.private_ip_name] = env[endpoint.private_ip_name]
else
# Allocate a new IP for the endpoint
private_ip = find_open_ip(endpoint.private_port)
if private_ip.nil?
raise "No IP was available to create endpoint for cart #{cartridge.name} in gear #{@container.uuid}: "\
"#{endpoint.private_ip_name}(#{endpoint.private_port})"
end
@container.add_env_var(endpoint.private_ip_name, private_ip)
allocated_ips[endpoint.private_ip_name] = private_ip
end
end
private_ip = allocated_ips[endpoint.private_ip_name]
next if env[endpoint.private_port_name]
allocated_endpoints << endpoint
@container.add_env_var(endpoint.private_port_name, endpoint.private_port)
# Create the environment variable for WebSocket Port if it is specified
# in the manifest.
if endpoint.websocket_port_name && endpoint.websocket_port
@container.add_env_var(endpoint.websocket_port_name, endpoint.websocket_port)
end
logger.info("Created private endpoint for cart #{cartridge.name} in gear #{@container.uuid}: "\
"[#{endpoint.private_ip_name}=#{private_ip}, #{endpoint.private_port_name}=#{endpoint.private_port}]")
# Expose the public endpoint if ssl_to_gear option is set
if endpoint.options and endpoint.options["ssl_to_gear"]
logger.info("ssl_to_gear option set for the endpoint")
create_public_endpoint(cartridge, endpoint, private_ip)
end
end
# Validate all the allocations to ensure they aren't already bound. Batch up the initial check
# for efficiency, then do individual checks to provide better reporting before we fail.
address_list = allocated_endpoints.map { |e| {ip: allocated_ips[e.private_ip_name], port: e.private_port} }
if !address_list.empty? && @container.addresses_bound?(address_list, @hourglass)
failures = ''
allocated_endpoints.each do |endpoint|
if @container.address_bound?(allocated_ips[endpoint.private_ip_name], endpoint.private_port, @hourglass, true)
failures << "#{endpoint.private_ip_name}(#{endpoint.private_port})=#{allocated_ips[endpoint.private_ip_name]};"
end
end
raise "Failed to create the following private endpoints due to existing process bindings: #{failures}" unless failures.empty?
end
end
def delete_private_endpoints(cartridge)
logger.info "Deleting private endpoints for #{@container.uuid}/#{cartridge.directory}"
cartridge.endpoints.each do |endpoint|
@container.remove_env_var(endpoint.private_ip_name)
@container.remove_env_var(endpoint.private_port_name)
end
logger.info "Deleted private endpoints for #{@container.uuid}/#{cartridge.directory}"
end
def delete_private_endpoint(cartridge, endpoint, remove_private_ip=false)
logger.info "Deleting private endpoint #{endpoint.private_ip_name}:#{endpoint.private_port_name} for #{@container.uuid}/#{cartridge.directory}"
@container.remove_env_var(endpoint.private_ip_name) if remove_private_ip
@container.remove_env_var(endpoint.private_port_name)
disconnect_frontend_for_endpoint(cartridge, endpoint)
logger.info "Deleted private endpoint #{endpoint.private_ip_name}:#{endpoint.private_port_name} for #{@container.uuid}/#{cartridge.directory}"
end
# Finds the next IP address available for binding of the given port for
# the current gear user. The IP is assumed to be available only if the IP is
# not already associated with an existing endpoint defined by any cartridge within the gear.