| 1 | |
| 2 | |
| 3 | |
| 4 | package limatmpl |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/base64" |
| 10 | "fmt" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "unicode" |
| 17 | |
| 18 | "github.com/coreos/go-semver/semver" |
| 19 | "github.com/sirupsen/logrus" |
| 20 | |
| 21 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 22 | "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" |
| 23 | "github.com/lima-vm/lima/v2/pkg/limatype/filenames" |
| 24 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 25 | "github.com/lima-vm/lima/v2/pkg/version/versionutil" |
| 26 | "github.com/lima-vm/lima/v2/pkg/yqutil" |
| 27 | ) |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | func (tmpl *Template) Embed(ctx context.Context, embedAll, defaultBase bool) error { |
| 33 | if err := tmpl.UseAbsLocators(ctx); err != nil { |
| 34 | return err |
| 35 | } |
| 36 | seen := make(map[string]bool) |
| 37 | err := tmpl.embedAllBases(ctx, embedAll, defaultBase, seen) |
| 38 | |
| 39 | |
| 40 | |
| 41 | if err == nil { |
| 42 | err = tmpl.combineListEntries(ctx) |
| 43 | } |
| 44 | return tmpl.ClearOnError(err) |
| 45 | } |
| 46 | |
| 47 | func (tmpl *Template) embedAllBases(ctx context.Context, embedAll, defaultBase bool, seen map[string]bool) error { |
| 48 | logrus.Debugf("Embedding templates into %#q", tmpl.Locator) |
| 49 | if defaultBase { |
| 50 | configDir, err := dirnames.LimaConfigDir() |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | defaultBaseFilename := filepath.Join(configDir, filenames.Base) |
| 55 | if _, err := os.Stat(defaultBaseFilename); err == nil { |
| 56 | |
| 57 | |
| 58 | tmpl.expr.WriteString("| ($a.base | select(type == \"!!str\")) |= [\"\" + .]\n") |
| 59 | tmpl.expr.WriteString("| ($a.base | select(type == \"!!map\")) |= [[] + .]\n") |
| 60 | |
| 61 | fmt.Fprintf(&tmpl.expr, "| $a.base = [%q, $a.base[]]\n", defaultBaseFilename) |
| 62 | if err := tmpl.evalExpr(ctx); err != nil { |
| 63 | return err |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | for { |
| 68 | if err := tmpl.Unmarshal(); err != nil { |
| 69 | return err |
| 70 | } |
| 71 | if len(tmpl.Config.Base) == 0 { |
| 72 | break |
| 73 | } |
| 74 | baseLocator := tmpl.Config.Base[0] |
| 75 | if baseLocator.Digest != nil { |
| 76 | return fmt.Errorf("base %#q in %#q has specified a digest; digest support is not yet implemented", baseLocator.URL, tmpl.Locator) |
| 77 | } |
| 78 | isTemplate, _ := SeemsTemplateURL(baseLocator.URL) |
| 79 | if isTemplate && !embedAll { |
| 80 | |
| 81 | for i := 1; i < len(tmpl.Config.Base); i++ { |
| 82 | isTemplate, _ = SeemsTemplateURL(tmpl.Config.Base[i].URL) |
| 83 | if !isTemplate { |
| 84 | return fmt.Errorf("cannot embed template %#q after not embedding %#q", tmpl.Config.Base[i].URL, baseLocator.URL) |
| 85 | } |
| 86 | } |
| 87 | break |
| 88 | |
| 89 | } |
| 90 | |
| 91 | if seen[baseLocator.URL] { |
| 92 | return fmt.Errorf("base template loop detected: template %#q already included", baseLocator.URL) |
| 93 | } |
| 94 | seen[baseLocator.URL] = true |
| 95 | |
| 96 | |
| 97 | if err := tmpl.embedBase(ctx, baseLocator, embedAll, seen); err != nil { |
| 98 | return err |
| 99 | } |
| 100 | } |
| 101 | if err := tmpl.embedAllScripts(ctx, embedAll); err != nil { |
| 102 | return err |
| 103 | } |
| 104 | if len(tmpl.Bytes) > yBytesLimit { |
| 105 | return fmt.Errorf("template %#q embedding exceeded the size limit (%d bytes)", tmpl.Locator, yBytesLimit) |
| 106 | } |
| 107 | return nil |
| 108 | } |
| 109 | |
| 110 | func (tmpl *Template) embedBase(ctx context.Context, baseLocator limatype.LocatorWithDigest, embedAll bool, seen map[string]bool) error { |
| 111 | logrus.Debugf("Embedding base %#q in template %#q", baseLocator.URL, tmpl.Locator) |
| 112 | if err := tmpl.Unmarshal(); err != nil { |
| 113 | return err |
| 114 | } |
| 115 | base, err := Read(ctx, "", baseLocator.URL) |
| 116 | if err != nil { |
| 117 | return err |
| 118 | } |
| 119 | if err := base.UseAbsLocators(ctx); err != nil { |
| 120 | return err |
| 121 | } |
| 122 | if err := base.embedAllBases(ctx, embedAll, false, seen); err != nil { |
| 123 | return err |
| 124 | } |
| 125 | if err := tmpl.merge(ctx, base); err != nil { |
| 126 | return err |
| 127 | } |
| 128 | if len(tmpl.Bytes) > yBytesLimit { |
| 129 | return fmt.Errorf("template %#q embedding exceeded the size limit (%d bytes)", tmpl.Locator, yBytesLimit) |
| 130 | } |
| 131 | return nil |
| 132 | } |
| 133 | |
| 134 | |
| 135 | |
| 136 | func (tmpl *Template) evalExprImpl(ctx context.Context, prefix string, b []byte) error { |
| 137 | var err error |
| 138 | expr := prefix + tmpl.expr.String() + "| $a" |
| 139 | tmpl.Bytes, err = yqutil.EvaluateExpression(ctx, expr, b) |
| 140 | |
| 141 | tmpl.Bytes = append(bytes.TrimRight(tmpl.Bytes, "\n"), '\n') |
| 142 | tmpl.Config = nil |
| 143 | tmpl.expr.Reset() |
| 144 | return tmpl.ClearOnError(err) |
| 145 | } |
| 146 | |
| 147 | |
| 148 | func (tmpl *Template) evalExpr(ctx context.Context) error { |
| 149 | var err error |
| 150 | if tmpl.expr.Len() > 0 { |
| 151 | |
| 152 | singleDocument := "select(document_index == 0) as $a | $a as $b\n" |
| 153 | err = tmpl.evalExprImpl(ctx, singleDocument, tmpl.Bytes) |
| 154 | } |
| 155 | return err |
| 156 | } |
| 157 | |
| 158 | |
| 159 | func (tmpl *Template) merge(ctx context.Context, base *Template) error { |
| 160 | if err := tmpl.mergeBase(base); err != nil { |
| 161 | return tmpl.ClearOnError(err) |
| 162 | } |
| 163 | documents := fmt.Sprintf("%s\n---\n%s", string(tmpl.Bytes), string(base.Bytes)) |
| 164 | return tmpl.evalExprImpl(ctx, mergeDocuments, []byte(documents)) |
| 165 | } |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | func (tmpl *Template) mergeBase(base *Template) error { |
| 171 | if err := tmpl.Unmarshal(); err != nil { |
| 172 | return err |
| 173 | } |
| 174 | if err := base.Unmarshal(); err != nil { |
| 175 | return err |
| 176 | } |
| 177 | if tmpl.Config.MinimumLimaVersion != nil && base.Config.MinimumLimaVersion != nil { |
| 178 | if versionutil.GreaterThan(*base.Config.MinimumLimaVersion, *tmpl.Config.MinimumLimaVersion) { |
| 179 | const minimumLimaVersion = "minimumLimaVersion" |
| 180 | tmpl.copyField(minimumLimaVersion, minimumLimaVersion) |
| 181 | } |
| 182 | } |
| 183 | var tmplOpts limatype.QEMUOpts |
| 184 | if err := limayaml.Convert(tmpl.Config.VMOpts[limatype.QEMU], &tmplOpts, "vmOpts.qemu"); err != nil { |
| 185 | return err |
| 186 | } |
| 187 | var baseOpts limatype.QEMUOpts |
| 188 | if err := limayaml.Convert(base.Config.VMOpts[limatype.QEMU], &baseOpts, "vmOpts.qemu"); err != nil { |
| 189 | return err |
| 190 | } |
| 191 | if tmplOpts.MinimumVersion != nil && baseOpts.MinimumVersion != nil { |
| 192 | tmplVersion := *semver.New(*tmplOpts.MinimumVersion) |
| 193 | baseVersion := *semver.New(*baseOpts.MinimumVersion) |
| 194 | if tmplVersion.LessThan(baseVersion) { |
| 195 | const minimumQEMUVersion = "vmOpts.qemu.minimumVersion" |
| 196 | tmpl.copyField(minimumQEMUVersion, minimumQEMUVersion) |
| 197 | } |
| 198 | } |
| 199 | return nil |
| 200 | } |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | const mergeDocuments = ` |
| 212 | select(document_index == 0) as $a |
| 213 | | select(document_index == 1) as $b |
| 214 | |
| 215 | # $c will be mutilated to implement our own "merge only new fields" logic. |
| 216 | | $b as $c |
| 217 | |
| 218 | # Delete the base that is being merged right now |
| 219 | | $a | select(.base | tag == "!!seq") | del(.base[0]) |
| 220 | | $a | select(.base | (tag == "!!seq" and length == 0)) | del(.base) |
| 221 | | $a | select(.base | tag == "!!str") | del(.base) |
| 222 | |
| 223 | # If $a.base is a list, then $b.base must be a list as well |
| 224 | # (note $b, not $c, because we merge lists from $b) |
| 225 | | $b | select((.base | tag == "!!str") and ($a.base | tag == "!!seq")) | .base = [ "" + .base ] |
| 226 | |
| 227 | # Delete base DNS entries if the template list is not empty. |
| 228 | | $b | select($a.dns | length > 0) | del(.dns) |
| 229 | | $c | select($a.dns | length > 0) | del(.dns) |
| 230 | |
| 231 | # Mark all new list fields with a custom tag. This is needed to avoid appending |
| 232 | # newly copied lists to themselves again when we merge lists. |
| 233 | | $c | .. | select(tag == "!!seq") tag = "!!tag" |
| 234 | |
| 235 | # Delete all nodes in $c that are in $a and not a map. This is necessary because |
| 236 | # the yq "*n" operator (merge only new fields) does not copy all comments across. |
| 237 | | $c | delpaths([$a | .. | select(tag != "!!map") | path]) |
| 238 | |
| 239 | # Merging with null returns null; use an empty map if $c has only comments |
| 240 | | $a * ($c // {}) as $a |
| 241 | |
| 242 | # Find all elements that are existing lists. This will not match newly |
| 243 | # copied lists because they have a custom !!tag instead of !!seq. |
| 244 | # Append the elements from the same path in $b. |
| 245 | # Exception: base templates, provision scripts and probes are prepended instead. |
| 246 | | $a | (.. | select(tag == "!!seq" and (path[0] | test("^(base|provision|probes)$") | not))) |= |
| 247 | (. + (path[] as $p ireduce ($b; .[$p]))) |
| 248 | | $a | (.. | select(tag == "!!seq" and (path[0] | test("^(base|provision|probes)$")))) |= |
| 249 | ((path[] as $p ireduce ($b; .[$p])) + .) |
| 250 | |
| 251 | # Copy head and line comments for existing lists that do not already have comments. |
| 252 | # New lists and existing maps already have their comments updated by the $a * $c merge. |
| 253 | | $a | (.. | select(tag == "!!seq" and (key | head_comment == "")) | key) head_comment |= |
| 254 | (((path[] as $p ireduce ($b; .[$p])) | key | head_comment) // "") |
| 255 | | $a | (.. | select(tag == "!!seq" and (key | line_comment == "")) | key) line_comment |= |
| 256 | (((path[] as $p ireduce ($b; .[$p])) | key | line_comment) // "") |
| 257 | |
| 258 | # Make sure mountTypesUnsupported elements are unique. |
| 259 | | $a | (select(.mountTypesUnsupported) | .mountTypesUnsupported) |= unique |
| 260 | |
| 261 | # Remove the custom tags again so they do not clutter up the YAML output. |
| 262 | | $a | .. | select(tag == "!!tag") tag = "" |
| 263 | ` |
| 264 | |
| 265 | |
| 266 | func listFields(list string, dstIdx, srcIdx int, field string) (dst, src string) { |
| 267 | dst = fmt.Sprintf("%s[%d]", list, dstIdx) |
| 268 | src = fmt.Sprintf("%s[%d]", list, srcIdx) |
| 269 | if field != "" { |
| 270 | dst += "." + field |
| 271 | src += "." + field |
| 272 | } |
| 273 | return dst, src |
| 274 | } |
| 275 | |
| 276 | |
| 277 | func (tmpl *Template) copyField(dst, src string) { |
| 278 | fmt.Fprintf(&tmpl.expr, "| ($a.%s) = $b.%s\n", dst, src) |
| 279 | |
| 280 | |
| 281 | fmt.Fprintf(&tmpl.expr, "| ($a.%s | key) head_comment = ($b.%s | key | head_comment)\n", dst, src) |
| 282 | } |
| 283 | |
| 284 | |
| 285 | |
| 286 | func (tmpl *Template) copyListEntryField(list string, dstIdx, srcIdx int, field string) { |
| 287 | tmpl.copyField(listFields(list, dstIdx, srcIdx, field)) |
| 288 | } |
| 289 | |
| 290 | type commentType string |
| 291 | |
| 292 | const ( |
| 293 | headComment commentType = "head" |
| 294 | lineComment commentType = "line" |
| 295 | ) |
| 296 | |
| 297 | |
| 298 | func (tmpl *Template) copyComment(dst, src string, commentType commentType, isMapElement bool) { |
| 299 | onKey := "" |
| 300 | if isMapElement { |
| 301 | onKey = " | key" |
| 302 | } |
| 303 | |
| 304 | |
| 305 | fmt.Fprintf(&tmpl.expr, "| $a | (select(.%s) | .%s%s | select(%s_comment == \"\" and ($b.%s%s | %s_comment != \"\"))) %s_comment |= ($b.%s%s | %s_comment)\n", |
| 306 | dst, dst, onKey, commentType, src, onKey, commentType, commentType, src, onKey, commentType) |
| 307 | } |
| 308 | |
| 309 | |
| 310 | func (tmpl *Template) copyComments(dst, src string, isMapElement bool) { |
| 311 | for _, commentType := range []commentType{headComment, lineComment} { |
| 312 | tmpl.copyComment(dst, src, commentType, isMapElement) |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | |
| 317 | func (tmpl *Template) copyListEntryComments(list string, dstIdx, srcIdx int, field string) { |
| 318 | dst, src := listFields(list, dstIdx, srcIdx, field) |
| 319 | isMapElement := field != "" |
| 320 | tmpl.copyComments(dst, src, isMapElement) |
| 321 | } |
| 322 | |
| 323 | func (tmpl *Template) deleteListEntry(list string, idx int) { |
| 324 | fmt.Fprintf(&tmpl.expr, "| del($a.%s[%d], $b.%s[%d])\n", list, idx, list, idx) |
| 325 | } |
| 326 | |
| 327 | |
| 328 | func (tmpl *Template) upgradeListEntryStringToMapField(list string, idx int, field string) { |
| 329 | |
| 330 | fmt.Fprintf(&tmpl.expr, "| ($a.%s[%d] | select(type == \"!!str\")) |= {\"%s\": .}\n", list, idx, field) |
| 331 | } |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | func (tmpl *Template) combineListEntries(ctx context.Context) error { |
| 342 | if err := tmpl.Unmarshal(); err != nil { |
| 343 | return err |
| 344 | } |
| 345 | |
| 346 | tmpl.combineAdditionalDisks() |
| 347 | tmpl.combineMounts() |
| 348 | tmpl.combineNetworks() |
| 349 | |
| 350 | return tmpl.evalExpr(ctx) |
| 351 | } |
| 352 | |
| 353 | TODO: |
| 354 | TODO: |
| 355 | |
| 356 | |
| 357 | func (tmpl *Template) combineAdditionalDisks() { |
| 358 | const additionalDisks = "additionalDisks" |
| 359 | |
| 360 | diskIdx := make(map[string]int, len(tmpl.Config.AdditionalDisks)) |
| 361 | for src := 0; src < len(tmpl.Config.AdditionalDisks); { |
| 362 | disk := tmpl.Config.AdditionalDisks[src] |
| 363 | var from, to int |
| 364 | if disk.Name == "*" { |
| 365 | |
| 366 | from = 0 |
| 367 | to = src - 1 |
| 368 | } else { |
| 369 | if i, ok := diskIdx[disk.Name]; ok { |
| 370 | |
| 371 | from = i |
| 372 | to = i |
| 373 | } else { |
| 374 | |
| 375 | if disk.Name != "" { |
| 376 | diskIdx[disk.Name] = src |
| 377 | } |
| 378 | src++ |
| 379 | continue |
| 380 | } |
| 381 | } |
| 382 | for dst := from; dst <= to; dst++ { |
| 383 | |
| 384 | upgradeDiskToMap := sync.OnceFunc(func() { |
| 385 | tmpl.upgradeListEntryStringToMapField(additionalDisks, dst, "name") |
| 386 | }) |
| 387 | |
| 388 | dest := &tmpl.Config.AdditionalDisks[dst] |
| 389 | if dest.Format == nil && disk.Format != nil { |
| 390 | upgradeDiskToMap() |
| 391 | tmpl.copyListEntryField(additionalDisks, dst, src, "format") |
| 392 | dest.Format = disk.Format |
| 393 | } |
| 394 | TODO: |
| 395 | if dest.FSType == nil && disk.FSType != nil { |
| 396 | upgradeDiskToMap() |
| 397 | tmpl.copyListEntryField(additionalDisks, dst, src, "fsType") |
| 398 | dest.FSType = disk.FSType |
| 399 | } |
| 400 | |
| 401 | if len(dest.FSArgs) == 0 && len(disk.FSArgs) != 0 { |
| 402 | upgradeDiskToMap() |
| 403 | tmpl.copyListEntryField(additionalDisks, dst, src, "fsArgs") |
| 404 | dest.FSArgs = disk.FSArgs |
| 405 | } |
| 406 | TODO: |
| 407 | if disk.Name != "*" { |
| 408 | tmpl.copyListEntryComments(additionalDisks, dst, src, "") |
| 409 | } |
| 410 | } |
| 411 | tmpl.Config.AdditionalDisks = slices.Delete(tmpl.Config.AdditionalDisks, src, src+1) |
| 412 | tmpl.deleteListEntry(additionalDisks, src) |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | |
| 417 | func (tmpl *Template) combineMounts() { |
| 418 | const mounts = "mounts" |
| 419 | |
| 420 | mountPointIdx := make(map[string]int, len(tmpl.Config.Mounts)) |
| 421 | for src := 0; src < len(tmpl.Config.Mounts); { |
| 422 | mount := tmpl.Config.Mounts[src] |
| 423 | |
| 424 | mountPoint := mount.Location |
| 425 | if mount.MountPoint != nil { |
| 426 | mountPoint = *mount.MountPoint |
| 427 | } |
| 428 | var from, to int |
| 429 | if mountPoint == "*" { |
| 430 | from = 0 |
| 431 | to = src - 1 |
| 432 | } else { |
| 433 | if i, ok := mountPointIdx[mountPoint]; ok { |
| 434 | from = i |
| 435 | to = i |
| 436 | } else { |
| 437 | if mountPoint != "" { |
| 438 | mountPointIdx[mountPoint] = src |
| 439 | } |
| 440 | src++ |
| 441 | continue |
| 442 | } |
| 443 | } |
| 444 | for dst := from; dst <= to; dst++ { |
| 445 | dest := &tmpl.Config.Mounts[dst] |
| 446 | |
| 447 | if dest.MountPoint == nil && mount.MountPoint != nil { |
| 448 | tmpl.copyListEntryField(mounts, dst, src, "mountPoint") |
| 449 | dest.MountPoint = mount.MountPoint |
| 450 | } |
| 451 | |
| 452 | if dest.Writable == nil && mount.Writable != nil { |
| 453 | tmpl.copyListEntryField(mounts, dst, src, "writable") |
| 454 | dest.Writable = mount.Writable |
| 455 | } |
| 456 | |
| 457 | if dest.SSHFS.Cache == nil && mount.SSHFS.Cache != nil { |
| 458 | tmpl.copyListEntryField(mounts, dst, src, "sshfs.cache") |
| 459 | dest.SSHFS.Cache = mount.SSHFS.Cache |
| 460 | } |
| 461 | if dest.SSHFS.FollowSymlinks == nil && mount.SSHFS.FollowSymlinks != nil { |
| 462 | tmpl.copyListEntryField(mounts, dst, src, "sshfs.followSymlinks") |
| 463 | dest.SSHFS.FollowSymlinks = mount.SSHFS.FollowSymlinks |
| 464 | } |
| 465 | if dest.SSHFS.SFTPDriver == nil && mount.SSHFS.SFTPDriver != nil { |
| 466 | tmpl.copyListEntryField(mounts, dst, src, "sshfs.sftpDriver") |
| 467 | dest.SSHFS.SFTPDriver = mount.SSHFS.SFTPDriver |
| 468 | } |
| 469 | if dest.SSHFS.ReadonlyNames == nil && mount.SSHFS.ReadonlyNames != nil { |
| 470 | tmpl.copyListEntryField(mounts, dst, src, "sshfs.readonlyNames") |
| 471 | dest.SSHFS.ReadonlyNames = mount.SSHFS.ReadonlyNames |
| 472 | } |
| 473 | |
| 474 | if dest.NineP.SecurityModel == nil && mount.NineP.SecurityModel != nil { |
| 475 | tmpl.copyListEntryField(mounts, dst, src, "9p.securityModel") |
| 476 | dest.NineP.SecurityModel = mount.NineP.SecurityModel |
| 477 | } |
| 478 | if dest.NineP.ProtocolVersion == nil && mount.NineP.ProtocolVersion != nil { |
| 479 | tmpl.copyListEntryField(mounts, dst, src, "9p.protocolVersion") |
| 480 | dest.NineP.ProtocolVersion = mount.NineP.ProtocolVersion |
| 481 | } |
| 482 | if dest.NineP.Msize == nil && mount.NineP.Msize != nil { |
| 483 | tmpl.copyListEntryField(mounts, dst, src, "9p.msize") |
| 484 | dest.NineP.Msize = mount.NineP.Msize |
| 485 | } |
| 486 | if dest.NineP.Cache == nil && mount.NineP.Cache != nil { |
| 487 | tmpl.copyListEntryField(mounts, dst, src, "9p.cache") |
| 488 | dest.NineP.Cache = mount.NineP.Cache |
| 489 | } |
| 490 | |
| 491 | if dest.Virtiofs.QueueSize == nil && mount.Virtiofs.QueueSize != nil { |
| 492 | tmpl.copyListEntryField(mounts, dst, src, "virtiofs.queueSize") |
| 493 | dest.Virtiofs.QueueSize = mount.Virtiofs.QueueSize |
| 494 | } |
| 495 | if mountPoint != "*" { |
| 496 | tmpl.copyListEntryComments(mounts, dst, src, "") |
| 497 | tmpl.copyListEntryComments(mounts, dst, src, "sshfs") |
| 498 | tmpl.copyListEntryComments(mounts, dst, src, "9p") |
| 499 | tmpl.copyListEntryComments(mounts, dst, src, "virtiofs") |
| 500 | } |
| 501 | } |
| 502 | tmpl.Config.Mounts = slices.Delete(tmpl.Config.Mounts, src, src+1) |
| 503 | tmpl.deleteListEntry(mounts, src) |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | |
| 508 | func (tmpl *Template) combineNetworks() { |
| 509 | const networks = "networks" |
| 510 | |
| 511 | interfaceIdx := make(map[string]int, len(tmpl.Config.Networks)) |
| 512 | for src := 0; src < len(tmpl.Config.Networks); { |
| 513 | nw := tmpl.Config.Networks[src] |
| 514 | var from, to int |
| 515 | if nw.Interface == "*" { |
| 516 | from = 0 |
| 517 | to = src - 1 |
| 518 | } else { |
| 519 | if i, ok := interfaceIdx[nw.Interface]; ok { |
| 520 | from = i |
| 521 | to = i |
| 522 | } else { |
| 523 | if nw.Interface != "" { |
| 524 | interfaceIdx[nw.Interface] = src |
| 525 | } |
| 526 | src++ |
| 527 | continue |
| 528 | } |
| 529 | } |
| 530 | for dst := from; dst <= to; dst++ { |
| 531 | dest := &tmpl.Config.Networks[dst] |
| 532 | |
| 533 | if dest.Lima == "" && dest.Socket == "" { |
| 534 | if nw.Lima != "" { |
| 535 | tmpl.copyListEntryField(networks, dst, src, "lima") |
| 536 | dest.Lima = nw.Lima |
| 537 | } |
| 538 | if nw.Socket != "" { |
| 539 | tmpl.copyListEntryField(networks, dst, src, "socket") |
| 540 | dest.Socket = nw.Socket |
| 541 | } |
| 542 | } |
| 543 | if dest.MACAddress == "" && nw.MACAddress != "" { |
| 544 | tmpl.copyListEntryField(networks, dst, src, "macAddress") |
| 545 | dest.MACAddress = nw.MACAddress |
| 546 | } |
| 547 | if dest.VZNAT == nil && nw.VZNAT != nil { |
| 548 | tmpl.copyListEntryField(networks, dst, src, "vzNAT") |
| 549 | dest.VZNAT = nw.VZNAT |
| 550 | } |
| 551 | if dest.Metric == nil && nw.Metric != nil { |
| 552 | tmpl.copyListEntryField(networks, dst, src, "metric") |
| 553 | dest.Metric = nw.Metric |
| 554 | } |
| 555 | if nw.Interface != "*" { |
| 556 | tmpl.copyListEntryComments(networks, dst, src, "") |
| 557 | } |
| 558 | } |
| 559 | tmpl.Config.Networks = slices.Delete(tmpl.Config.Networks, src, src+1) |
| 560 | tmpl.deleteListEntry(networks, src) |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | |
| 565 | |
| 566 | |
| 567 | var maxLineLength = 65000 |
| 568 | |
| 569 | |
| 570 | func encodeScriptReason(script string) string { |
| 571 | start := 0 |
| 572 | line := 1 |
| 573 | for i, r := range script { |
| 574 | if !(unicode.IsPrint(r) || r == '\n') { |
| 575 | return fmt.Sprintf("unprintable character %#q at offset %d", r, i) |
| 576 | } |
| 577 | |
| 578 | if i-start >= maxLineLength { |
| 579 | return fmt.Sprintf("line %d (offset %d) is longer than %d characters", line, start, maxLineLength) |
| 580 | } |
| 581 | if r == '\n' { |
| 582 | line++ |
| 583 | start = i + 1 |
| 584 | } |
| 585 | } |
| 586 | return "" |
| 587 | } |
| 588 | |
| 589 | |
| 590 | |
| 591 | const base64ChunkLength = 76 |
| 592 | |
| 593 | |
| 594 | |
| 595 | func binaryString(s string) string { |
| 596 | encoded := base64.StdEncoding.EncodeToString([]byte(s)) |
| 597 | if len(encoded) <= base64ChunkLength { |
| 598 | return encoded |
| 599 | } |
| 600 | |
| 601 | |
| 602 | lineCount := (len(encoded) + base64ChunkLength - 1) / base64ChunkLength |
| 603 | builder := strings.Builder{} |
| 604 | builder.Grow(len(encoded) + lineCount) |
| 605 | |
| 606 | for i := 0; i < len(encoded); i += base64ChunkLength { |
| 607 | end := min(i+base64ChunkLength, len(encoded)) |
| 608 | builder.WriteString(encoded[i:end]) |
| 609 | builder.WriteByte('\n') |
| 610 | } |
| 611 | |
| 612 | return builder.String() |
| 613 | } |
| 614 | |
| 615 | |
| 616 | func (tmpl *Template) updateScript(field string, idx int, newName, script, file string) { |
| 617 | tag := "" |
| 618 | if reason := encodeScriptReason(script); reason != "" { |
| 619 | logrus.Infof("File %#q is being base64 encoded: %s", file, reason) |
| 620 | script = binaryString(script) |
| 621 | tag = "!!binary" |
| 622 | } |
| 623 | entry := fmt.Sprintf("$a.%s[%d].file", field, idx) |
| 624 | |
| 625 | fmt.Fprintf(&tmpl.expr, "| (%s) = %q | (%s) tag = %q | (%s | key) = %q\n", |
| 626 | entry, script, entry, tag, entry, newName) |
| 627 | } |
| 628 | |
| 629 | |
| 630 | func (tmpl *Template) embedAllScripts(ctx context.Context, embedAll bool) error { |
| 631 | if err := tmpl.Unmarshal(); err != nil { |
| 632 | return err |
| 633 | } |
| 634 | for i, p := range tmpl.Config.Probes { |
| 635 | if p.File == nil { |
| 636 | continue |
| 637 | } |
| 638 | |
| 639 | if p.Script == nil || *p.Script != "" { |
| 640 | continue |
| 641 | } |
| 642 | isTemplate, _ := SeemsTemplateURL(p.File.URL) |
| 643 | if embedAll || !isTemplate { |
| 644 | scriptTmpl, err := Read(ctx, "", p.File.URL) |
| 645 | if err != nil { |
| 646 | return err |
| 647 | } |
| 648 | tmpl.updateScript("probes", i, "script", string(scriptTmpl.Bytes), p.File.URL) |
| 649 | } |
| 650 | } |
| 651 | for i, p := range tmpl.Config.Provision { |
| 652 | if p.File == nil { |
| 653 | continue |
| 654 | } |
| 655 | newName := "script" |
| 656 | switch p.Mode { |
| 657 | case limatype.ProvisionModeData: |
| 658 | newName = "content" |
| 659 | if p.Content != nil { |
| 660 | continue |
| 661 | } |
| 662 | case limatype.ProvisionModeYQ: |
| 663 | newName = "expression" |
| 664 | if p.Expression != nil { |
| 665 | continue |
| 666 | } |
| 667 | default: |
| 668 | if p.Script != nil && *p.Script != "" { |
| 669 | continue |
| 670 | } |
| 671 | } |
| 672 | isTemplate, _ := SeemsTemplateURL(p.File.URL) |
| 673 | if embedAll || !isTemplate { |
| 674 | scriptTmpl, err := Read(ctx, "", p.File.URL) |
| 675 | if err != nil { |
| 676 | return err |
| 677 | } |
| 678 | tmpl.updateScript("provision", i, newName, string(scriptTmpl.Bytes), p.File.URL) |
| 679 | } |
| 680 | } |
| 681 | return tmpl.evalExpr(ctx) |
| 682 | } |