Class: Kdep::OldFormat

Inherits:
Object
  • Object
show all
Defined in:
lib/kdep/old_format.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ OldFormat

Returns a new instance of OldFormat.



5
6
7
# File 'lib/kdep/old_format.rb', line 5

def initialize(path)
  @path = path
end

Instance Method Details

#app_nameObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/kdep/old_format.rb', line 9

def app_name
  # Try .app-name file in deploy dir
  name_file = File.join(@path, ".app-name")
  if File.exist?(name_file)
    return File.read(name_file).strip
  end
  # Try .app-name in parent dir (old pattern: repo/.app-name + repo/deploy/)
  parent_name_file = File.join(@path, "..", ".app-name")
  if File.exist?(parent_name_file)
    return File.read(parent_name_file).strip
  end
  # Try name from app.yml config
  cfg = config
  return cfg["name"] if cfg["name"]
  # Fall back to image field
  return cfg["image"] if cfg["image"]
  # Fall back to directory name (deploy_web -> web)
  dirname = File.basename(@path)
  name = dirname.sub(/\Adeploy_?/, "")
  return name unless name.empty?
  # "deploy" dir -> use parent dir name (repo name)
  File.basename(File.expand_path(File.join(@path, "..")))
end

#configObject



33
34
35
36
37
38
# File 'lib/kdep/old_format.rb', line 33

def config
  config_file = File.join(@path, "app.yml")
  return {} unless File.exist?(config_file)
  content = File.read(config_file)
  Kdep::YAMLCompat.safe_load(content) || {}
end

#extract_custom_resourcesObject

Return custom resources that need to be generated as standalone templates Returns array of { kind:, doc:, file: } hashes



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/kdep/old_format.rb', line 233

def extract_custom_resources
  customs = []
  each_manifest do |doc|
    case doc["kind"]
    when "PersistentVolumeClaim"
      customs << { "kind" => doc["kind"], "doc" => doc }
    when "Secret"
      # stringData secrets are custom (not handled by standard secret template)
      if doc["stringData"]
        customs << { "kind" => "Secret", "doc" => doc, "subtype" => "stringData" }
      end
    end
  end
  customs
end

#extract_envObject

Return env vars from materialized ConfigMap



250
251
252
253
254
255
256
257
258
259
# File 'lib/kdep/old_format.rb', line 250

def extract_env
  env = {}
  each_manifest do |doc|
    next unless doc["kind"] == "ConfigMap" && doc["data"]
    doc["data"].each do |k, v|
      env[k] = v
    end
  end
  env
end

#extract_secretsObject

Return secrets extracted from materialized Secret manifest (already base64)



220
221
222
223
224
225
226
227
228
229
# File 'lib/kdep/old_format.rb', line 220

def extract_secrets
  secrets = {}
  each_manifest do |doc|
    next unless doc["kind"] == "Secret" && doc["data"]
    doc["data"].each do |k, v|
      secrets[k] = v  # already base64-encoded
    end
  end
  secrets
end

#materialized_dirObject



59
60
61
62
63
64
65
# File 'lib/kdep/old_format.rb', line 59

def materialized_dir
  dir = File.join(@path, "materialized")
  return dir if File.directory?(dir)
  dir = File.join(@path, ".rendered")
  return dir if File.directory?(dir)
  nil
end

#materialized_filesObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/kdep/old_format.rb', line 40

def materialized_files
  mat_dir = materialized_dir
  if mat_dir
    return Dir.glob(File.join(mat_dir, "*.yml")).sort
  end
  # Collect yml/yaml files from subdirectories (app/, config/, secrets/, net/)
  files = []
  Dir.entries(@path).sort.each do |entry|
    next if entry.start_with?(".")
    next if entry.start_with?("_")
    subdir = File.join(@path, entry)
    next unless File.directory?(subdir)
    next if entry == "script"
    next if entry == "disabled"
    Dir.glob(File.join(subdir, "*.{yml,yaml}")).sort.each { |f| files << f }
  end
  files
end

#to_kdep_configObject

Build a complete kdep app.yml by extracting config from materialized K8s files



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
# File 'lib/kdep/old_format.rb', line 68

def to_kdep_config
  old = config
  result = {}

  # Start with what's in the old app.yml
  %w[preset namespace name image registry context port replicas
     command args env_from resources probe domains
     image_pull_secrets image_pull_policy schedule service_port
     ingress_name ingress_annotations ingress_class_field
     tls_secret_name tls_hosts ssl_redirect
     volume_mounts volumes lifecycle security_context
     termination_grace_period container_name deployment_name
     configmap_name secret_name service_name cronjob_name
     restart_policy cronjob_label
     pod_labels service_type cluster_ip service_ports
     service_port_protocol container_port_protocol
     suspend ingress_backend_service statefulset_name
     secret_type].each do |key|
    result[key] = old[key] if old.key?(key)
  end

  # Migrate old "env" key to "configmap"
  result["configmap"] = old["env"] if old.key?("env")

  # Old format uses "target" as the preset name
  result["preset"] ||= old["target"]

  # Convert Hash-style domains (host => config) to Array-style
  if result["domains"].is_a?(Hash)
    result["domains"] = result["domains"].map do |host, cfg|
      if cfg.is_a?(Hash) && !cfg.empty?
        domain = { "host" => host }
        domain["path"] = cfg["path"] if cfg["path"]
        domain["path_type"] = cfg["path_type"] if cfg["path_type"]
        # Per-host TLS secret
        if cfg["tls_secret"]
          result["tls_hosts"] ||= {}
          result["tls_hosts"][host] = cfg["tls_secret"]
        end
        domain
      else
        host
      end
    end
  end

  # Extract missing config from materialized K8s files
  # Save app.yml namespace, let manifest namespace take priority
  appyml_namespace = result.delete("namespace")
  extract_from_manifests(result)
  # Fall back to app.yml namespace if manifests didn't have one
  result["namespace"] ||= appyml_namespace

  # Merge env from ConfigMap into config (for rendering)
  manifest_env = extract_env
  unless manifest_env.empty?
    result["configmap"] = (result["configmap"] || {}).merge(manifest_env)
  end

  # Ensure name: prefer deploy metadata name > image > app_name
  result["name"] ||= result.delete("deploy_meta_name")
  result["name"] ||= app_name
  if result["name"].nil? || result["name"].empty?
    result["name"] = result["image"]
  end
  # Ensure image defaults to name
  result["image"] ||= result["name"]

  # Resolve ingress_backend_service: if backend differs from app name
  candidate = result.delete("_ingress_backend_service_candidate")
  if candidate && result["name"] && candidate != result["name"]
    result["ingress_backend_service"] = candidate
  end

  # Handle ingress class annotation flag
  no_ingress_class = result.delete("_no_ingress_class_annotation")
  if no_ingress_class && !result["ingress_class_field"]
    # No annotation AND no ingressClassName field: tell template not to add annotation
    result["no_ingress_class_annotation"] = true
  elsif !no_ingress_class && result["ingress_class_field"]
    # Has BOTH annotation and ingressClassName field: keep both
    result["ingress_class_annotation"] = true
  end

  # Handle Secret-specific namespace (cross-namespace secrets)
  sec_ns = result.delete("_secret_namespace")
  if sec_ns && result["namespace"] && sec_ns != result["namespace"]
    result["secret_namespace"] = sec_ns
  end

  # Process multi-ingress domains
  if result["domains"].is_a?(Array)
    hash_domains = result["domains"].select { |d| d.is_a?(Hash) }

    # Extract common ssl_redirect to global if ALL domains share the same value
    # Domains without ssl_redirect default to "false"
    ssl_values = hash_domains.map { |d| d["ssl_redirect"] || "false" }.uniq
    if ssl_values.size == 1 && ssl_values[0] != "false"
      result["ssl_redirect"] = ssl_values[0]
      hash_domains.each { |d| d.delete("ssl_redirect") }
    elsif ssl_values.size == 1
      # All default "false" - no need for global
      hash_domains.each { |d| d.delete("ssl_redirect") }
    end
    # If ssl_redirect differs across groups, keep per-domain

    # Extract common ingress_annotations to global if all annotated domains share them
    all_annot = hash_domains.map { |d| d["ingress_annotations"] }.compact
    if all_annot.size > 0 && all_annot.uniq.size == 1
      result["ingress_annotations"] = all_annot[0]
      hash_domains.each { |d| d.delete("ingress_annotations") }
    end
    # If annotations differ across groups, keep them per-domain

    # Simplify: if all domains have same ingress name, remove ingress tag
    ingress_names = hash_domains.map { |d| d["ingress"] }.compact.uniq
    if ingress_names.size <= 1
      # All from same ingress (or no ingress tag), simplify domains
      result["domains"] = result["domains"].map do |d|
        if d.is_a?(Hash)
          d = d.dup
          d.delete("ingress")
          d.delete("ssl_redirect") if d["ssl_redirect"].nil?
          d.delete("ingress_annotations") if d["ingress_annotations"].nil?
          # Simplify to string if only host remains
          if d.keys == ["host"]
            d["host"]
          else
            d
          end
        else
          d
        end
      end
    end
  end

  # Simplify tls_hosts: if all hosts use same secret, use tls_secret_name
  if result["tls_hosts"].is_a?(Hash) && result["tls_hosts"].size > 0
    unique_secrets = result["tls_hosts"].values.uniq
    if unique_secrets.size == 1
      result["tls_secret_name"] = unique_secrets[0]
      result.delete("tls_hosts")
    end
  end

  # Clean up nil values
  result.delete_if { |_, v| v.nil? }
  result
end