DockerEngineInfo.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Text.Json;
  2. namespace RackPeek.Domain.Discovery;
  3. /// <summary>
  4. /// The engine host's own account of itself, from <c>GET /info</c>. This is what makes
  5. /// a remote engine discoverable without user intervention: the daemon id gives the
  6. /// services an identity seed that does not depend on which machine ran the command,
  7. /// and the name is the hostname <c>rpk discover system</c> would report on that box.
  8. /// </summary>
  9. public sealed record DockerEngineInfo {
  10. /// <summary>
  11. /// The daemon's persisted unique id (kept under <c>/var/lib/docker</c>). Survives
  12. /// reboots; changes only on an engine reinstall — the same failure mode
  13. /// <c>/etc/machine-id</c> has for local discovery.
  14. /// </summary>
  15. public string? Id { get; init; }
  16. /// <summary>The engine host's hostname.</summary>
  17. public string? Hostname { get; init; }
  18. }
  19. /// <summary>Parses the Docker Engine <c>GET /info</c> response. Pure, so it tests from a fixture.</summary>
  20. public static class DockerEngineInfoParser {
  21. public static DockerEngineInfo? Parse(string json) {
  22. try {
  23. using var document = JsonDocument.Parse(json);
  24. if (document.RootElement.ValueKind != JsonValueKind.Object)
  25. return null;
  26. return new DockerEngineInfo {
  27. Id = GetString(document.RootElement, "ID"),
  28. Hostname = GetString(document.RootElement, "Name")
  29. };
  30. }
  31. catch (JsonException) {
  32. return null;
  33. }
  34. }
  35. private static string? GetString(JsonElement element, string property) =>
  36. element.TryGetProperty(property, out JsonElement value)
  37. && value.ValueKind == JsonValueKind.String
  38. && !string.IsNullOrWhiteSpace(value.GetString())
  39. ? value.GetString()
  40. : null;
  41. }