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
|
# File 'lib/puppet_x/cf_web/futoin/app.rb', line 95
def create_futoin(conf)
cf_system = cf_system()
site = conf[:site]
type = conf[:type]
user = conf[:user]
app_name = conf[:app_name]
site_dir = conf[:site_dir]
service_name = conf[:service_name]
misc = conf[:misc]
deploy_conf = misc['deploy']
limits = misc['limits']
conf_prefix = misc['conf_prefix']
tune = misc['tune']
persist_dir = misc['persist_dir']
deploy_dir = misc['deploy_dir']
mem_limit = cf_system.getMemory(service_name)
mem_limit = 1 if mem_limit == 0
run_dir = "/run/#{service_name}"
deployer_group = "deployer_#{site}"
env_file = "#{deploy_dir}/.env"
if deploy_conf['type'] == 'rms'
url_arg = 'rmsRepo'
deploy_args = [
'rms',
deploy_conf['pool']
]
else
url_arg = 'vcsRepo'
deploy_args = [ deploy_conf['type'] ]
end
if deploy_conf['match']
deploy_args += [ deploy_conf['match'] ]
end
deploy_args += [
"--#{url_arg}=#{deploy_conf['tool']}:#{deploy_conf['url']}",
"--deployDir=#{deploy_dir}",
]
redeploy_file = "#{deploy_dir}/.redeploy"
redeploy = File.exists? redeploy_file
deploy_futoin_file = "#{deploy_dir}/futoin.json"
current_file = "#{deploy_dir}/current"
orig_current = nil
orig_current_ts = 0
orig_current = File.readlink(current_file) if File.exists? current_file
orig_current_ts = File.lstat(current_file).mtime if File.exists? current_file
warning("CID deploy: #{deploy_dir}")
orig_cwd = Dir.pwd
begin
Dir.chdir(deploy_dir)
pre_conf = ''
pre_conf = File.read(deploy_futoin_file) if File.exists? deploy_futoin_file
Puppet::Util::Execution.execute(
[
'/usr/local/bin/cid',
'deploy', 'setup',
"--user=#{user}",
"--group=#{user}",
"--limit-memory=#{mem_limit}M",
],
{
:failonfail => true,
:uid => user,
:gid => deployer_group,
}
)
cid_vesion = Puppet::Util::Execution.execute(
[
'/usr/local/bin/cid', '--version'
],
{
:failonfail => true,
:uid => user,
:gid => deployer_group,
}
).strip()
phpfpm_tune = {
'phpini' => {
'open_basedir' => [
"#{File.realpath(deploy_dir)}/",
"#{File.realpath(persist_dir)}/",
].join(':'),
}
}
uwsgi_tune = {
'minMemory' => '16M',
'uwsgi' => {
'chmod-socket' => '660',
'pythonpath' => File.join(deploy_dir, 'current'),
},
}
deploy_set = [
%Q{tooltune cid version=#{Shellwords.escape(cid_vesion)}},
%Q{tooltune phpfpm #{Shellwords.escape(JSON.generate(phpfpm_tune))}},
%Q{tooltune uwsgi #{Shellwords.escape(JSON.generate(uwsgi_tune))}},
%Q{env syslogTag #{service_name}}
] + (deploy_conf['deploy_set'] || [])
if File.exists? env_file
env_entries = File.read(env_file).split("\n")
env_entries.each do |l|
l = l.split("=", 2)
next unless l.size == 2
deploy_set << %Q{env #{l[0]} #{l[1]}}
end
end
deploy_set.each do |v|
res = Puppet::Util::Execution.execute(
[
'/usr/local/bin/cid',
'deploy', 'set'] +
Shellwords.split(v),
{
:uid => user,
:gid => deployer_group,
}
)
if res.exitstatus != 0
err("\n---\n#{res}---")
raise "Failed at deploy set: #{v}"
end
end
custom_script = deploy_conf['custom_script']
if custom_script
custom_script_file = '.custom_script'
cf_system.atomicWrite(
custom_script_file, custom_script,
{
:user => user,
:mode => 0700,
}
)
Puppet::Util::Execution.execute(
[ 'bash', custom_script_file ],
{
:failonfail => true,
:uid => user,
:gid => deployer_group,
}
)
end
redeploy = true if pre_conf != File.read(deploy_futoin_file)
deploy_args << '--redeploy' if redeploy
res = Puppet::Util::Execution.execute(
[
'/usr/local/bin/cid',
'deploy',
] + deploy_args,
{
:failonfail => false,
:combine => true,
:uid => user,
:gid => deployer_group,
}
)
if File.exists? current_file
new_current = File.readlink(current_file)
new_current_ts = File.lstat(current_file).mtime
redeploy ||= (new_current != orig_current)
redeploy ||= (orig_current_ts != new_current_ts)
end
cf_system.atomicWrite(
'.deploy.log', res,
{
:user => user,
:mode => 0600,
:show_diff => false
}
)
if res.exitstatus != 0
warning("\n---\n#{res}---")
raise 'Failed to deploy'
else
info("\n---\n#{res}---")
end
File.unlink redeploy_file if File.exists? redeploy_file
rescue Exception => e
futoin_conf_file = "#{deploy_dir}/.futoin.merged.json"
raise e unless File.exists? futoin_conf_file
err(e.to_s)
futoin_conf = File.read(futoin_conf_file)
futoin_conf = JSON.parse(futoin_conf)
res = []
futoin_conf['deploy']['autoServices'].each do |name, instances|
ep = futoin_conf['entryPoints'][name]
next if ep['tool'] == 'nginx'
i = 0
instances.each do |v|
res << "#{service_name}_#{name}-#{i}"
i += 1
end
end
return res
ensure
Dir.chdir(orig_cwd)
end
futoin_conf = File.read("#{deploy_dir}/.futoin.merged.json")
futoin_conf = JSON.parse(futoin_conf)
entryPoints = futoin_conf['entryPoints']
autoServices = futoin_conf['deploy']['autoServices']
webcfg = futoin_conf.fetch('webcfg', {})
mounts = webcfg.fetch('mounts', {}).clone
if webcfg['main']
mounts['/'] ||= {}
mounts['/']['app'] = webcfg['main']
end
vhost_global = []
vhost_server = []
webroot = webcfg['root']
if webroot
webroot = File.join(deploy_dir, 'current', webroot)
else
webroot = File.join(deploy_dir, 'current')
end
upstream_zone_size = tune.fetch('upstreamZoneSize', '64k')
fail_timeout = tune.fetch('upstreamFailTimeout', '0')
keep_alive_percent = tune.fetch('upstreamKAPercent', 25).to_i
upstream_queue = tune.fetch('upstreamQueue', nil)
autoServiceLocations = {}
autoServices.each do |name, instances|
ep = entryPoints[name]
ep_tool = ep['tool']
if ep_tool == 'nginx'
ep_tune = ep.fetch('tune', {})
= (
ep_tune
.fetch('config', {})
.fetch('http', {})
.fetch('server', {})
)
vhost_server += prep_nginx_config()
next
end
protocol = instances[0]['socketProtocol']
next if protocol == 'custom'
upstream_name = "futoin_#{site}_#{name}"
vhost_global << "upstream #{upstream_name} {"
if upstream_queue
vhost_global << " queue #{upstream_queue};"
vhost_global << " zone upstreams #{upstream_zone_size};"
vhost_global << " hash $binary_remote_addr consistent;"
else
vhost_global << " least_conn;"
end
keepalive = ['fcgi', 'http'].include? protocol
force_maxconn = ['node'].include? ep_tool
if keepalive and keep_alive_percent > 0
ka_conn = instances.reduce(0) { |m, v| m + v['maxConnections'] }
ka_conn = (ka_conn * keep_alive_percent / 100).to_i
if ka_conn > 0
vhost_global << " keepalive #{ka_conn};"
end
end
instances.each do |v|
options = []
options << "max_fails=0"
options << "fail_timeout=#{fail_timeout}"
if upstream_queue
options << "max_conns=#{v['maxConnections']}"
elsif force_maxconn
options << "max_conns=#{v['maxConnections']}"
end
socket_type = v['socketType']
if socket_type == 'unix'
socket = "unix:#{v['socketPath']}"
elsif socket_type == 'tcp'
sock_addr = v['socketAddress']
if sock_addr == '0.0.0.0'
sock_addr = '127.0.0.1'
end
socket = "#{sock_addr}:#{v['socketPort']}"
elsif socket_type == 'tcp6'
sock_addr = v['socketAddress']
if sock_addr == '::'
sock_addr = '::1'
end
socket = "#{sock_addr}:#{v['socketPort']}"
elsif !socket_type
next
else
raise %Q{Unsupported socket type "#{socket_type}" for "#{name}"}
end
vhost_global << %Q{ server #{socket} #{options.join(' ')};}
end
vhost_global << "}"
vhost_global << ""
next_tries = instances.size
body_size = instances[0]['maxRequestSize'].downcase
location_conf = []
if limits[name]
location_conf << " #{limits[name]['expr']}"
else
location_conf << " #{limits['dynamic']['expr']}"
end
location_conf << " client_max_body_size #{body_size};";
if protocol == 'http'
location_conf << " proxy_pass http://#{upstream_name};"
location_conf << " proxy_next_upstream_tries #{next_tries};"
location_conf << " include /etc/nginx/cf_http_params;"
elsif protocol == 'fcgi'
location_conf << " fastcgi_pass #{upstream_name};"
location_conf << " fastcgi_next_upstream_tries #{next_tries};"
location_conf << " include /etc/nginx/cf_fastcgi_params;"
file_path = File.join(deploy_dir, 'current', ep.fetch('path', ''))
location_conf << " fastcgi_param SCRIPT_FILENAME #{file_path};"
elsif protocol == 'scgi'
location_conf << " scgi_pass #{upstream_name};"
location_conf << " scgi_next_upstream_tries #{next_tries};"
location_conf << " include /etc/nginx/cf_scgi_params;"
elsif protocol == 'uwsgi'
location_conf << " uwsgi_pass #{upstream_name};"
location_conf << " uwsgi_next_upstream_tries #{next_tries};"
location_conf << " include /etc/nginx/cf_uwsgi_params;"
elsif protocol == 'custom'
next
else
raise "Not supported protocol '#{protocol}'"
end
autoServiceLocations[name] = location_conf
vhost_server << "location @#{name} {"
vhost_server += location_conf
vhost_server << "}"
vhost_server << ""
end
if mounts['/']
vhost_server << "location /favicon.ico {"
vhost_server << " try_files $uri @empty_gif;"
vhost_server << "}"
vhost_server << "location @empty_gif {"
vhost_server << " expires 1h;"
vhost_server << " empty_gif;"
vhost_server << "}"
vhost_server << ""
vhost_server << "location ~ /\\. {"
vhost_server << " deny all;"
vhost_server << " limit_req zone=unlikely nodelay;"
vhost_server << " log_not_found off;"
vhost_server << "}"
vhost_server << ""
end
mounts.each do |path, mp|
mp = { 'app' => mp } if mp.is_a? String
vhost_server << "location #{path} {"
app = mp['app']
path_tune = mp.fetch('tune', {})
serve_static = mp.fetch('static', false)
if app
if serve_static
vhost_server << " try_files $uri @#{app};"
else
vhost_server += autoServiceLocations[app]
end
else
serve_static = true end
if serve_static
vhost_server << " #{limits['static']['expr']}"
vhost_server << " root #{webroot};"
vhost_server << " disable_symlinks if_not_owner;"
vhost_server << " index #{path_tune.fetch('index', 'index.html')};"
if path_tune.fetch('etag', false)
vhost_server << " etag on;"
else
vhost_server << " etag off;"
end
if path_tune.fetch('autoindex', false)
vhost_server << " autoindex on;"
else
vhost_server << " autoindex off;"
end
vhost_server << " expires #{path_tune.fetch('expires', 'max')};"
if path_tune.fetch('pattern', true)
text_assets = [
'html',
'htm',
'txt',
'css',
'js',
'svg',
'xml',
]
vhost_server << " location ~* \\.(#{text_assets.join('|')})$ {"
if app
vhost_server << " try_files $uri @#{app};"
end
if path_tune.fetch('gzip', true)
vhost_server << " gzip on;"
vhost_server << " gzip_types *;"
else
vhost_server << " gzip off;"
end
if path_tune.fetch('staticGzip', true)
vhost_server << " gzip_static on;"
else
vhost_server << " gzip_static off;"
end
vhost_server << " }"
else
if path_tune.fetch('gzip', false)
vhost_server << " gzip on;"
vhost_server << " gzip_types *;"
else
vhost_server << " gzip off;"
end
if path_tune.fetch('staticGzip', false)
vhost_server << " gzip_static on;"
else
vhost_server << " gzip_static off;"
end
end
end
vhost_server << "}"
vhost_server << ""
end
vhost_global_file = "#{conf_prefix}.global.#{app_name}"
vhost_server_file = "#{conf_prefix}.server.#{app_name}"
cf_system.atomicWrite(vhost_global_file, vhost_global.join("\n"))
cf_system.atomicWrite(vhost_server_file, vhost_server.join("\n"))
service_names = []
autoServices.each do |name, instances|
ep_conf = futoin_conf['entryPoints'][name]
tool = ep_conf['tool']
next if tool == 'nginx'
is_uwsgi = ['uwsgi'].include? tool
is_phpfpm = ['phpfpm'].include? tool
max_conn = 0
i = 0
mem_lock = is_uwsgi
instances.each do |v|
service_name_i = "#{service_name}_#{name}-#{i}"
service_names << service_name_i
max_conn += v['maxConnections']
cow_reserve = 0
mem_limit = parse_mem(v['maxMemory'])
if is_uwsgi or is_phpfpm
min_memory = parse_mem(ep_conf['tune']['minMemory'])
cow_reserve += v['maxConnections'] * min_memory
end
content_ini = {
'Unit' => {
'Description' => "CFWEB App: #{site} (#{name}-#{i})",
},
'Service' => {
'LimitNOFILE' => 'infinity',
'WorkingDirectory' => "#{deploy_dir}",
'Slice' => "#{PuppetX::CfWeb::SLICE_PREFIX}#{user}.slice",
'ExecStart' => "/usr/local/bin/cid service exec #{name} #{i}",
'ExecReload' => %Q{/usr/local/bin/cid service reload #{name} #{i} "$MAINPID"},
'ExecStop' => %Q{/bin/sh -c '[ -n "$MAINPID" ] && /usr/local/bin/cid service stop #{name} #{i} $MAINPID || /bin/true'},
},
}
sock_path = v['socketPath']
if sock_path
script = "while ! chmod 0770 -f #{sock_path}; do sleep 0.01; done"
content_ini['Service']['ExecStartPre'] = "/bin/rm -f #{sock_path}"
content_ini['Service']['ExecStartPost'] = "/bin/sh -c '#{script}'"
end
service_changed = self.cf_system().createService({
:service_name => service_name_i,
:user => user,
:content_ini => content_ini,
:mem_limit => mem_limit,
:mem_lock => mem_lock,
:cow_reserve => cow_reserve,
})
begin
systemctl('enable', "#{service_name_i}.service")
if service_changed
systemctl('restart', "#{service_name_i}.service")
elsif redeploy
systemctl('reload-or-restart', "#{service_name_i}.service")
else
systemctl('start', "#{service_name_i}.service")
end
rescue Exception => e
err(e.to_s)
end
i += 1
end
saveMaxConn(site, name, max_conn)
end
begin
systemctl('reload', "cfnginx.service")
rescue Exception => e
warning(e.to_s)
end
return service_names
end
|