Class: Dry::Stack

Inherits:
Object
  • Object
show all
Defined in:
lib/version.rb,
lib/dry-stack/stack.rb

Constant Summary collapse

VERSION =
'0.1.58'
COMPOSE_VERSION =
'3.8'

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Stack

def self.new(*args, &block)

super

end



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/dry-stack/stack.rb', line 112

def initialize(name)
  @name = name || 'stack'
  @version = COMPOSE_VERSION
  @description = ''
  @options = {}
  @services = {}
  @networks = {}
  @volumes = {}
  @environment = {}
  @publish_ports = {}
  @ingress = {}
  @deploy = {}
  @labels = {}
  @configs = {}
  @logging = {}
  @configurations = {}
end

Class Attribute Details

.last_stackObject

Returns the value of attribute last_stack.



101
102
103
# File 'lib/dry-stack/stack.rb', line 101

def last_stack
  @last_stack
end

Instance Attribute Details

#configurationObject

Returns the value of attribute configuration.



103
104
105
# File 'lib/dry-stack/stack.rb', line 103

def configuration
  @configuration
end

#descriptionObject

Returns the value of attribute description.



103
104
105
# File 'lib/dry-stack/stack.rb', line 103

def description
  @description
end

#nameObject

Returns the value of attribute name.



103
104
105
# File 'lib/dry-stack/stack.rb', line 103

def name
  @name
end

#optionsObject

Returns the value of attribute options.



103
104
105
# File 'lib/dry-stack/stack.rb', line 103

def options
  @options
end

Instance Method Details

#_ServiceDeferred(name, opts = {}, &block) ⇒ Object



460
461
462
463
464
465
466
467
# File 'lib/dry-stack/stack.rb', line 460

def _ServiceDeferred(name, opts = {}, &block)
  (@before_blocks || []).each do |before|
    next unless before[:names].empty? || before[:names].include?(name)
    next if before[:except]&.include? name
    before[:block].call(name)
  end
  _ServiceImplementation(name, opts, &block)
end

#_ServiceImplementation(name, opts = {}) ⇒ Object



469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/dry-stack/stack.rb', line 469

def _ServiceImplementation(name, opts = {}, &)
  opts = opts.dup
  opts[:ports] = [opts[:ports]].flatten if opts.key? :ports
  opts[:environment] = opts.delete(:env) if opts.key? :env

  service = @services[name.to_sym] ||= begin
    s = {environment: {}, deploy: {labels: []}, networks: {}}
    DEFAULT_INIT_SERVICE ? s.merge(init: true) : s
  end

  service.deep_merge! opts
  ServiceFunction.new(service, &) if block_given?
end

#After(&block) ⇒ Object



417
418
419
# File 'lib/dry-stack/stack.rb', line 417

def After(&block)
  (@after_blocks ||=[]) << block
end

#AfterService(name = nil, opts = {}, &block) ⇒ Object



440
441
442
443
444
445
446
447
448
449
# File 'lib/dry-stack/stack.rb', line 440

def AfterService(name = nil, opts = {}, &block)
  names, opts, except = normalize_service_hook_args(name, opts)
  After do
    hook_names = names.empty? ? @services.keys : names
    hook_names -= except
    hook_names.each do |s_name|
      _ServiceImplementation s_name, opts, &block
    end
  end
end

#apply_configuration(configuration) ⇒ Object



140
141
142
143
# File 'lib/dry-stack/stack.rb', line 140

def apply_configuration(configuration)
  raise "Configuration not found: #{configuration}" unless @configurations[configuration.to_sym]
  @configurations[configuration.to_sym][:block_function].call
end

#BeforeService(name = nil, opts = {}, &block) ⇒ Object



432
433
434
435
436
437
438
# File 'lib/dry-stack/stack.rb', line 432

def BeforeService(name = nil, opts = {}, &block)
  names, opts, except = normalize_service_hook_args(name, opts)
  (@before_blocks ||=[]).push names:, except:,
                              block: ->(s_name) {
    _ServiceImplementation s_name, opts, &block
  }
end

#Config(name, opts) ⇒ Object



503
504
505
# File 'lib/dry-stack/stack.rb', line 503

def Config(name, opts)
  @configs[name] = opts
end

#Configuration(name, opts = {}, &b) ⇒ Object



549
550
551
552
553
554
555
# File 'lib/dry-stack/stack.rb', line 549

def Configuration(name, opts = {}, &b)
  configuration = @configurations[name.to_sym] ||= {}
  configuration.merge! opts
  configuration.merge! block_function: -> {
    instance_exec(&b) if block_given? # https://rubyreferences.github.io/rubychanges/3.3.html#anonymous-parameters-forwarding-inside-blocks-are-disallowed
  }
end

#Deploy(names = nil, services) ⇒ Object



507
508
509
510
511
512
513
514
515
# File 'lib/dry-stack/stack.rb', line 507

def Deploy(names = nil, services)
  if names
    [names].flatten.each do |name|
      (@deploy[name.to_sym] ||= {}).merge! expand_hash(services)
    end
  else
    @deploy.merge! expand_hash(services)
  end
end

#Description(string) ⇒ Object



483
484
485
# File 'lib/dry-stack/stack.rb', line 483

def Description(string)
  @description = string
end

#ENV!Object



106
# File 'lib/dry-stack/stack.rb', line 106

def ENV! = ENV.method(:fetch)

#Environment(names = nil, envs) ⇒ Object



517
518
519
520
521
522
523
524
525
# File 'lib/dry-stack/stack.rb', line 517

def Environment(names = nil, envs)
  if names
    [names].flatten.each do |name|
      (@environment[name.to_sym] ||= {}).merge! envs
    end
  else
    @environment.merge! envs
  end
end

#Include(file_name) ⇒ Object



412
413
414
415
# File 'lib/dry-stack/stack.rb', line 412

def Include(file_name)
  dir = Dry.cmd_params[:stack] ? File.dirname(Dry.cmd_params[:stack]) : '.'
  eval IO.read( File.join dir, file_name )
end

#Ingress(services) ⇒ Object



497
498
499
500
501
# File 'lib/dry-stack/stack.rb', line 497

def Ingress(services)
  services.each do |name, ing|
    @ingress[name] = ((@ingress[name] || [] ) | [ing]).flatten
  end
end

#Labels(labels) ⇒ Object



493
494
495
# File 'lib/dry-stack/stack.rb', line 493

def Labels(labels)
  @labels.merge! labels
end

#Logging(names = nil, opts) ⇒ Object



533
534
535
536
537
538
539
540
541
# File 'lib/dry-stack/stack.rb', line 533

def Logging(names = nil, opts )
  if names
    [names].flatten.each do |name|
      (@logging[name.to_sym] ||= {}).merge! expand_hash(opts)
    end
  else
    @logging.merge! expand_hash(opts)
  end
end

#Network(name, opts = {}) ⇒ Object



527
528
529
530
531
# File 'lib/dry-stack/stack.rb', line 527

def Network(name, opts = {})
  @networks[name] ||= {}
  @networks[name].merge! opts
  yield if block_given?
end

#nginx_host2regexp(str) ⇒ Object



130
131
132
133
134
135
136
137
138
# File 'lib/dry-stack/stack.rb', line 130

def nginx_host2regexp(str)
  # http://nginx.org/en/docs/http/server_names.html
  if str[0] == '~'
    # ~^(?<user>.+)\.example\.net$;
    str[1..]
  else
    str.to_s.gsub('.', '\.').gsub('*', '.*')
  end
end

#normalize_service_hook_args(name, opts) ⇒ Object



421
422
423
424
425
426
427
428
429
430
# File 'lib/dry-stack/stack.rb', line 421

def normalize_service_hook_args(name, opts)
  if name.is_a?(Hash) && opts.empty?
    opts = name
    name = nil
  end

  opts = opts.dup
  except = [opts.delete(:except)].flatten.compact
  [[name].flatten.compact, opts, except]
end

#Options(opts) ⇒ Object



487
488
489
490
491
# File 'lib/dry-stack/stack.rb', line 487

def Options(opts)
  # warn 'WARN: Options command is used for testing purpose.\
  #       Not recommended in real life configurations.' unless $0 =~ /rspec/
  @options.merge! opts
end

#PublishPorts(ports) ⇒ Object



451
452
453
# File 'lib/dry-stack/stack.rb', line 451

def PublishPorts(ports)
  @publish_ports.merge! ports.to_h { |k, v| [k,@publish_ports[k].to_a + [v].flatten] }
end

#Service(name, opts = {}, &block) ⇒ Object



455
456
457
458
# File 'lib/dry-stack/stack.rb', line 455

def Service(name, opts = {}, &block)
  @services_blocks ||=[]
  (@services_blocks ||=[]).push -> { _ServiceDeferred(name, opts, &block) }
end

#StackObject



105
# File 'lib/dry-stack/stack.rb', line 105

def Stack(...) = Dry::Stack(...)

#to_compose(opts = @options) ⇒ Object



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
# File 'lib/dry-stack/stack.rb', line 145

def to_compose(opts = @options)
  @name = @options[:name] || @name

  compose = {
    # name: @name.to_s, # https://docs.docker.com/compose/compose-file/#name-top-level-element
    # Not allowed by docker stack deploy
    version: @version,
    services: YAML.load(@services.to_yaml, aliases: true),
    volumes: YAML.load(@volumes.to_yaml, aliases: true),
    networks: YAML.load(@networks.to_yaml, aliases: true),
    configs: YAML.load(@configs.to_yaml, aliases: true)
  }

  compose[:services].each do |name, service|

    service[:image].gsub!(/:latest$/, '') if service[:image] # let docker swarm to create tag: :latest@sha265:0000...

    ingress = [@ingress[name], service[:ingress] || [] ].flatten.compact

    if ingress.any?
      compose[:networks].merge! ingress_routing: {external: true, name: 'ingress-routing'}
    end

    service[:deploy] ||= {}
    service[:deploy][:labels] ||= []
    service[:deploy][:labels] += @labels.map { "#{_1}=#{_2}" }

    if ingress[0] && (opts[:ingress] || opts[:traefik] || opts[:traefik_tls])
      service[:networks] ||= {}
      service[:networks][:default] ||= {} if service[:networks].empty?
      service[:networks][:ingress_routing] ||= {}
    end

    ingress.each do |rule|
      if opts[:host_sed] && rule[:host]
        a, b = opts[:host_sed].split('/').reject(&:empty?)
        rule[:host].gsub! %r{#{a}}, b
      end
    end

    service_name = "#{@name}_#{name}"

    if ingress[0] && (opts[:traefik] || opts[:traefik_tls])
      service[:deploy][:labels] << 'traefik.enable=true'
      ingress[0][:port] ||= service[:ports]&.first

      ingress.each_with_index do |ing, index|
        ing[:port] ||= service[:ports]&.first
        load_balancer = []
        load_balancer << "server.url=#{ing[:url]}" if ing[:url]
        load_balancer << "server.port=#{ing[:port]}" if ing[:port]

        if ing[:host_sni]
          domain = opts[:tls_domain] || 'example.com'

          if ing[:host_sni]&.include?('*')
            domain = ing[:host_sni].gsub('.*', ".#{domain}")
          else
            domain = ing[:host_sni]
          end

          domain = ing[:tls_domain] if ing[:tls_domain]

          ing[:passthrough] = false unless ing.key? :passthrough
          # Without specifying entrypoints any/all are user by traefik to to connectio to the service
          raise "'entrypoints' required for SNI tcp route" if ing[:entrypoints].to_s.empty?

          service[:deploy][:labels] += [
            "traefik.tcp.routers.#{service_name}-#{index}.tls=true",
            "traefik.tcp.routers.#{service_name}-#{index}.tls.certresolver=le",
            "traefik.tcp.routers.#{service_name}-#{index}.tls.domains[0].main=#{domain}",

            "traefik.tcp.routers.#{service_name}-#{index}.rule=HostSNI(`#{domain}`)",
            "traefik.tcp.routers.#{service_name}-#{index}.tls.passthrough=#{ing[:passthrough]}",

            "traefik.tcp.routers.#{service_name}-#{index}.service=#{service_name}-#{index}",
            "traefik.tcp.routers.#{service_name}-#{index}.entrypoints=#{ing[:entrypoints]}"
          ]
          service[:deploy][:labels] += load_balancer.map { "traefik.tcp.services.#{service_name}-#{index}.loadbalancer.#{_1}" }

        else
          service[:deploy][:labels] += [
            "traefik.http.routers.#{service_name}-#{index}.service=#{service_name}-#{index}",
          ]
          service[:deploy][:labels] += load_balancer.map { "traefik.http.services.#{service_name}-#{index}.loadbalancer.#{_1}" }

          if opts[:traefik_tls]
            domain = opts[:tls_domain] || 'example.com'
            if ing[:host]
              if ing[:host]&.include?('*')
                domain = ing[:host].gsub('*', domain)
              else
                domain = ing[:host]
              end
            end

            domain = ing[:tls_domain] if ing[:tls_domain]
            service[:deploy][:labels] += [
              "traefik.http.routers.#{service_name}-#{index}.tls=true",
              "traefik.http.routers.#{service_name}-#{index}.tls.certresolver=le",
              "traefik.http.routers.#{service_name}-#{index}.tls.domains[0].main=#{domain}"
            ]
          end

          rule = []
          rule << "HostRegexp(`{name:#{nginx_host2regexp ing[:host]}}`)" if ing[:host]
          rule << "ClientIP(#{[ing[:client_ip]].flatten.map{ "`#{_1}`" }.join ','})" if ing[:client_ip]
          rule << "PathPrefix(`#{ing[:path]}`)" if ing[:path]
          rule << "PathRegexp(`#{ing[:path_regexp]}`)" if ing[:path_regexp]
          rule << "#{ing[:rule]}" if ing[:rule]

          middlewares = []
          if ing[:oauth_provider] || service[:oauth_provider]
            pname = "#{service_name}-#{index}_oauth_provider"
            value = ing[:oauth_provider] || service[:oauth_provider]
            value = "http://#{value}" unless value =~ /^http/
            middlewares << pname
            service[:deploy][:labels] << "traefik.http.middlewares.#{pname}.forwardauth.address=#{value}"
            service[:deploy][:labels] << "traefik.http.middlewares.#{pname}.forwardauth.authResponseHeadersRegex=^X-"
          end

          if ing[:basic_auth]
            ba_user, ba_password, salt = ing[:basic_auth].split ':'
            hashed_password = apr1_crypt ba_password, (salt || rand(36**8).to_s(36))
            service[:deploy][:labels] << "traefik.http.middlewares.#{service_name}-#{index}_auth.basicauth.users=#{ba_user}:#{hashed_password.gsub('$','$$')}"
            middlewares << "#{service_name}-#{index}_auth"
          end

          service[:deploy][:labels] << "traefik.http.routers.#{service_name}-#{index}.rule=#{rule.join ' && '}"

          if ing[:path_sub]
            middlewares << "#{service_name}-#{index}-path_sub"
            service[:deploy][:labels] += [
              "traefik.http.middlewares.#{service_name}-#{index}-path_sub.replacepathregex.regex=#{ing[:path_sub][0]}",
              "traefik.http.middlewares.#{service_name}-#{index}-path_sub.replacepathregex.replacement=#{ing[:path_sub][1].gsub('$','$$')}"
            ]
          end

          service[:deploy][:labels] << "traefik.http.routers.#{service_name}-#{index}.middlewares=#{middlewares.join ","}" unless middlewares.empty?
        end
      end
    end
    service.delete :ingress
    service.delete :oauth_provider

    service[:environment] = @environment[name].merge(service[:environment])  if @environment[name]
    service[:environment].merge! STACK_NAME: @name.to_s, STACK_SERVICE_NAME: name.to_s
    service[:environment].transform_values! { !!_1 == _1 ? _1.to_s : _1 } # (false|true) to string

    service[:deploy].deep_merge! @deploy[name] if @deploy[name]

    # hash = {'service-name': service_name, 'stack-name': @name}
    env_sub = ->(s) {
      s = s.to_s.dup
      s.gsub!('%{stack-name}', @name.to_s)
      s.gsub!('%{service-name}', service_name)
      s
    }
    service[:deploy][:labels] = service[:deploy][:labels].map{ env_sub[_1] }
    service[:environment].transform_values!{ _1.is_a?(String) ? (env_sub[_1]) : _1 }

    pp_h = @publish_ports[name]&.select { _1.class == Hash }
    pp_i = @publish_ports[name]&.select { _1.class == Integer }
    pp_s = @publish_ports[name]&.select { _1.class == String }
    service[:ports] = pp_i&.zip(service[:ports] || pp_i)&.map { _1.join ':' }
    service[:ports] = (service[:ports] || []) + pp_s unless pp_s.nil?

    if pp_h&.any?
      service[:ports] = service[:ports].map { |s|
        if s.class == String
          published, target = s.split(':').map(&:to_i)
          { published:, target:, protocol: 'tcp', mode: 'ingress'}
        else
          s
        end
      } + pp_h
    end

    service[:logging] ||= @logging[name.to_sym]

    service[:volumes]&.map!&.with_index do |volume, index|
      if volume.is_a? Hash
        if volume.key?(:name) && volume.key?(:source)
          $stderr.puts 'Use either :name or :source in volume declaration as a Hash'
          $stderr.puts ':name will create Volume section automatically'
          raise 'invalid volume declaration'
        end
        unless volume.key? :source
          v_name = (volume[:local_name] || "#{service_name}-volume-#{index}").to_sym
          compose[:volumes][v_name] ||= {}
          compose[:volumes][v_name].merge! volume.slice(:name, :driver, :driver_opts, :labels)
          compose[:volumes][v_name][:external] = false if compose[:volumes][v_name].empty?
          volume[:type] ||= 'volume'
          volume.except(:name, :driver, :driver_opts, :local_name).merge source: v_name
        else
          volume
        end
      else
        volume
      end
    end

    service[:networks]&.each do |name, network|
      # raise "network name is invalid: #{name}" unless name.is_a? String, Symbol # https://bugs.ruby-lang.org/issues/20793
      raise "network name is invalid: #{name}" unless name in String | Symbol
      next unless network.is_a? Hash

      (compose[:networks][name] ||= {}).merge! network.except(:aliases)
      compose[:networks][name].merge(name: network[:name]) if network[:name]
      network.delete :external
      network.delete :name
      network.delete :attachable

      service[:networks][name] = EMPTY_HASH if network.empty?
    end

    service[:configs]&.each_with_index do |config, index|
      config[:source] = "#{service_name}-config-#{index}" if config[:source].to_s.empty?
      compose[:configs][config[:source].to_sym] ||= {}
      compose[:configs][config[:source].to_sym].merge! config.except(:source, :target)
      config.replace config.except :file_content, :file, :name
    end
  end

  compose[:configs].update(compose[:configs]) do |name, config|
    # total config name must be max 64 characters length. MD5 - 32 characters
    short_name = name[0..30]

    if config[:file_content]
      md5 = Digest::MD5.hexdigest config[:file_content]
      fname = "./#{@name}.config.#{name}.#{md5}" # use MD5, when run in parallel may have different content
      File.write fname, config[:file_content]
      {name: "#{short_name}-#{md5}", file: fname}.merge config.except(:file_content)
    elsif config[:file]
      body = File.read config[:file] rescue ''
      md5 = Digest::MD5.hexdigest body
      {name: "#{short_name}-#{md5}", file: fname}.merge config
    else
      config
    end
  end

  compose[:networks].delete_if{ |k,v| k == :default && v.empty? }
  compose[:networks].transform_values! do |network|
    network.empty? ? EMPTY_HASH : network
  end

  prune = ->(o) {
    o.each { prune[_2] }  if o.is_a? Hash
    o.delete_if { _2.nil? || ( _2.respond_to?(:empty?) && _2.empty?) } if o.is_a? Hash
  }
  prune[compose]

  each_recursive _root: compose do |_path, node, v|

    v.transform_keys!(&:to_s) if v.is_a? Hash
    node.transform_keys!(&:to_s) if node.is_a? Hash
    _path.last[node] = v.to_s if v.is_a? Symbol
    _path.last[node] = nil if v == EMPTY_HASH

    _path.last[node] = v.to_s if node.to_s == 'fluentd-async'
  end

  # compose.to_yaml
  JSON.parse(compose.to_json).to_yaml
end

#Volume(name, opts = {}) ⇒ Object



543
544
545
546
547
# File 'lib/dry-stack/stack.rb', line 543

def Volume(name, opts = {})
  @volumes[name] ||= {}
  @volumes[name].merge! opts
  yield if block_given?
end