Class: Dry::Stack

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

Constant Summary collapse

VERSION =
'0.0.72'
COMPOSE_VERSION =
'3.8'

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Stack

Returns a new instance of Stack.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/dry-stack/stack.rb', line 81

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

Class Attribute Details

.last_stackObject

Returns the value of attribute last_stack.



72
73
74
# File 'lib/dry-stack/stack.rb', line 72

def last_stack
  @last_stack
end

Instance Attribute Details

#descriptionObject

Returns the value of attribute description.



74
75
76
# File 'lib/dry-stack/stack.rb', line 74

def description
  @description
end

#nameObject

Returns the value of attribute name.



74
75
76
# File 'lib/dry-stack/stack.rb', line 74

def name
  @name
end

#optionsObject

Returns the value of attribute options.



74
75
76
# File 'lib/dry-stack/stack.rb', line 74

def options
  @options
end

#swarm_deployObject

Returns the value of attribute swarm_deploy.



74
75
76
# File 'lib/dry-stack/stack.rb', line 74

def swarm_deploy
  @swarm_deploy
end

Instance Method Details

#Config(name, opts) ⇒ Object



286
287
288
# File 'lib/dry-stack/stack.rb', line 286

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

#Deploy(names = nil, services) ⇒ Object



290
291
292
293
294
295
296
297
298
# File 'lib/dry-stack/stack.rb', line 290

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



268
269
270
# File 'lib/dry-stack/stack.rb', line 268

def Description(string)
  @description = string
end

#Environment(names = nil, envs) ⇒ Object



300
301
302
303
304
305
306
307
308
# File 'lib/dry-stack/stack.rb', line 300

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

#expand_hash(hash) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/dry-stack/stack.rb', line 99

def expand_hash(hash)
  hash.select { _1.to_s =~ /\./ }.each do |k, v|
    name = k.to_s.scan(/([^\.]*)\.(.*)/).flatten
    hash.delete k
    hash[name[0]] ||= {}
    hash[name[0]][name[1]] ||= {}
    hash[name[0]][name[1]].merge! v if v.is_a?(Hash)
    hash[name[0]][name[1]] = v unless v.is_a?(Hash)
  end
  hash.each { expand_hash(_2) if _2.is_a?(Hash) }
  hash
end

#Ingress(services) ⇒ Object



282
283
284
# File 'lib/dry-stack/stack.rb', line 282

def Ingress(services)
  @ingress.merge! services
end

#Labels(labels) ⇒ Object



278
279
280
# File 'lib/dry-stack/stack.rb', line 278

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

#Logging(names, opts = {}) ⇒ Object



316
317
318
319
320
# File 'lib/dry-stack/stack.rb', line 316

def Logging(names, opts = {})
  [names].flatten.each do |name|
    @logging[name.to_sym] = opts
  end
end

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



310
311
312
313
314
# File 'lib/dry-stack/stack.rb', line 310

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

#nginx_host2regexp(str) ⇒ Object



112
113
114
115
116
117
118
119
120
# File 'lib/dry-stack/stack.rb', line 112

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



272
273
274
275
276
# File 'lib/dry-stack/stack.rb', line 272

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



255
256
257
# File 'lib/dry-stack/stack.rb', line 255

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

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



259
260
261
262
263
264
265
266
# File 'lib/dry-stack/stack.rb', line 259

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

  service = @services[name.to_sym] ||= {environment: {}, deploy: {labels: []}}
  service.merge! opts
  ServiceFunction.new(service, &)  if block_given?
end

#Stack(name = nil) ⇒ Object



76
77
78
79
# File 'lib/dry-stack/stack.rb', line 76

def Stack(name = nil, &)
  Stack.last_stack = Stack.new name
  Stack.last_stack.instance_exec(&) if block_given?
end

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



328
329
330
331
332
333
334
# File 'lib/dry-stack/stack.rb', line 328

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

  swarm = @swarm_deploy[name.to_sym] ||= { environment: {} }
  swarm.merge! opts
  SwarmFunction.new(swarm, &) if block_given?
end

#to_compose(opts = @options) ⇒ Object



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

def to_compose(opts = @options )
  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)
  }

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

  compose[:services].each do |name, service|
    ingress = [@ingress[name]].flatten.compact
    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 << "PathPrefix(`#{nginx_host2regexp ing[:path]}`)" if ing[:path]
        rule << "#{ing[:rule]}" if ing[:rule]

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

        if ing[:path_sub]
          service[:deploy][:labels] += [
            "traefik.http.routers.#{service_name}-#{index}.middlewares=#{service_name}-#{index}-path_sub",
            "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
      end
    end

    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}
    hash.default = ''
    original_verbosity = $VERBOSE
    $VERBOSE = nil
    service[:deploy][:labels] = service[:deploy][:labels].map{ _1 % hash }
    service[:environment].transform_values!{ _1.is_a?(String) ? (_1 % hash) : _1 }
    $VERBOSE = original_verbosity

    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[:configs]&.each do |config|
      if config[:file_content]
        compose[:configs][config[:source].to_sym] = {file_content: config[:file_content]}
        config.delete :file_content
      end
    end
  end

  compose[:configs].update(compose[:configs]) do |name, config|
    if config[:file_content]
      md5 = Digest::MD5.hexdigest config[:file_content]
      fname = "./#{@name}.config.#{name}"
      File.write fname, config[:file_content]
      {name: "#{name}-#{md5}", file: fname}.merge config.except(:file_content)
    else
      config
    end
  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] = 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



322
323
324
325
326
# File 'lib/dry-stack/stack.rb', line 322

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