Class: Dry::Stack

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

Constant Summary collapse

VERSION =
'0.1.22'
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



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/dry-stack/stack.rb', line 106

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.



96
97
98
# File 'lib/dry-stack/stack.rb', line 96

def last_stack
  @last_stack
end

Instance Attribute Details

#configurationObject

Returns the value of attribute configuration.



98
99
100
# File 'lib/dry-stack/stack.rb', line 98

def configuration
  @configuration
end

#descriptionObject

Returns the value of attribute description.



98
99
100
# File 'lib/dry-stack/stack.rb', line 98

def description
  @description
end

#nameObject

Returns the value of attribute name.



98
99
100
# File 'lib/dry-stack/stack.rb', line 98

def name
  @name
end

#optionsObject

Returns the value of attribute options.



98
99
100
# File 'lib/dry-stack/stack.rb', line 98

def options
  @options
end

Instance Method Details

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



378
379
380
381
382
383
384
385
# File 'lib/dry-stack/stack.rb', line 378

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



387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/dry-stack/stack.rb', line 387

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



348
349
350
# File 'lib/dry-stack/stack.rb', line 348

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

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



359
360
361
362
363
364
365
366
367
# File 'lib/dry-stack/stack.rb', line 359

def AfterService(name = nil, opts = {}, &block)
  After do
    names = [name || @services.keys].flatten
    names -= [opts[:except]].flatten if opts.key? :except
    names.each do |s_name|
      _ServiceImplementation s_name, opts, &block
    end
  end
end

#apply_configuration(configuration) ⇒ Object



134
135
136
137
# File 'lib/dry-stack/stack.rb', line 134

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



352
353
354
355
356
357
# File 'lib/dry-stack/stack.rb', line 352

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

#Config(name, opts) ⇒ Object



421
422
423
# File 'lib/dry-stack/stack.rb', line 421

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

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



467
468
469
470
471
472
473
# File 'lib/dry-stack/stack.rb', line 467

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



425
426
427
428
429
430
431
432
433
# File 'lib/dry-stack/stack.rb', line 425

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



401
402
403
# File 'lib/dry-stack/stack.rb', line 401

def Description(string)
  @description = string
end

#Environment(names = nil, envs) ⇒ Object



435
436
437
438
439
440
441
442
443
# File 'lib/dry-stack/stack.rb', line 435

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



343
344
345
346
# File 'lib/dry-stack/stack.rb', line 343

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



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

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

#Labels(labels) ⇒ Object



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

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

#Logging(names = nil, opts) ⇒ Object



451
452
453
454
455
456
457
458
459
# File 'lib/dry-stack/stack.rb', line 451

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



445
446
447
448
449
# File 'lib/dry-stack/stack.rb', line 445

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

#nginx_host2regexp(str) ⇒ Object



124
125
126
127
128
129
130
131
132
# File 'lib/dry-stack/stack.rb', line 124

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

#Options(opts) ⇒ Object



405
406
407
408
409
# File 'lib/dry-stack/stack.rb', line 405

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



369
370
371
# File 'lib/dry-stack/stack.rb', line 369

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

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



373
374
375
376
# File 'lib/dry-stack/stack.rb', line 373

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

#StackObject



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

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

#to_compose(opts = @options) ⇒ Object



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

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
        service[:deploy][:labels] += [
          "traefik.http.routers.#{service_name}-#{index}.service=#{service_name}-#{index}",
          "traefik.http.services.#{service_name}-#{index}.loadbalancer.server.port=#{ing[:port]}"
        ]

        if opts[:traefik_tls]
          domain = opts[:tls_domain] || 'example.com'
          domain = ing[:host].gsub('.*', ".#{domain}") if ing[:host]
          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(`#{nginx_host2regexp ing[:path]}`)" if ing[:path]
        rule << "#{ing[:rule]}" if ing[:rule]

        middlewares = []

        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
    service.delete :ingress

    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_i = @publish_ports[name]&.reject { _1.class == String }
    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?

    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



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

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