| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 4 | package update |
| 5 | |
| 6 | import ( |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 7 | "bytes" |
| 8 | "context" |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 9 | "crypto/sha256" |
| Lorenz Brun | d14be0e | 2023-07-31 16:46:14 +0200 | [diff] [blame] | 10 | "debug/pe" |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 11 | _ "embed" |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 12 | "errors" |
| 13 | "fmt" |
| 14 | "io" |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 15 | "os" |
| 16 | "path/filepath" |
| 17 | "regexp" |
| Jan Schär | 1a7e1fe | 2025-07-25 16:50:12 +0200 | [diff] [blame] | 18 | "runtime" |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 19 | "strconv" |
| Lorenz Brun | d14be0e | 2023-07-31 16:46:14 +0200 | [diff] [blame] | 20 | "strings" |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 21 | "time" |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 22 | |
| 23 | "github.com/cenkalti/backoff/v4" |
| Jan Schär | 1a7e1fe | 2025-07-25 16:50:12 +0200 | [diff] [blame] | 24 | ocispecv1 "github.com/opencontainers/image-spec/specs-go/v1" |
| Lorenz Brun | d14be0e | 2023-07-31 16:46:14 +0200 | [diff] [blame] | 25 | "golang.org/x/sys/unix" |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 26 | "google.golang.org/grpc/codes" |
| 27 | "google.golang.org/grpc/status" |
| Lorenz Brun | 54a5a05 | 2023-10-02 16:40:11 +0200 | [diff] [blame] | 28 | "google.golang.org/protobuf/proto" |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 29 | |
| Serge Bazanski | 3c5d063 | 2024-09-12 10:49:12 +0000 | [diff] [blame] | 30 | "source.monogon.dev/go/logging" |
| Jan Schär | e19d279 | 2025-06-23 12:37:58 +0000 | [diff] [blame] | 31 | "source.monogon.dev/metropolis/installer/install" |
| Jan Schär | b86917b | 2025-05-14 16:31:08 +0000 | [diff] [blame] | 32 | "source.monogon.dev/metropolis/node/core/productinfo" |
| Tim Windelschmidt | 9f21f53 | 2024-05-07 15:14:20 +0200 | [diff] [blame] | 33 | "source.monogon.dev/osbase/blockdev" |
| 34 | "source.monogon.dev/osbase/efivarfs" |
| 35 | "source.monogon.dev/osbase/gpt" |
| 36 | "source.monogon.dev/osbase/kexec" |
| Jan Schär | 2963b68 | 2025-07-17 17:03:44 +0200 | [diff] [blame] | 37 | "source.monogon.dev/osbase/oci" |
| Jan Schär | e19d279 | 2025-06-23 12:37:58 +0000 | [diff] [blame] | 38 | "source.monogon.dev/osbase/oci/osimage" |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 39 | "source.monogon.dev/osbase/oci/registry" |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 40 | |
| Jan Schär | 69b7687 | 2025-05-14 16:39:47 +0000 | [diff] [blame] | 41 | abloaderpb "source.monogon.dev/metropolis/node/abloader/spec" |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 42 | apb "source.monogon.dev/metropolis/proto/api" |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 43 | ) |
| 44 | |
| 45 | // Service contains data and functionality to perform A/B updates on a |
| 46 | // Metropolis node. |
| 47 | type Service struct { |
| 48 | // Path to the mount point of the EFI System Partition (ESP). |
| 49 | ESPPath string |
| Tim Windelschmidt | 8e87a06 | 2023-07-31 01:33:10 +0000 | [diff] [blame] | 50 | // gpt.Partition of the ESP System Partition. |
| 51 | ESPPart *gpt.Partition |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 52 | // Partition number (1-based) of the ESP in the GPT partitions array. |
| 53 | ESPPartNumber uint32 |
| Tim Windelschmidt | 8e87a06 | 2023-07-31 01:33:10 +0000 | [diff] [blame] | 54 | |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 55 | // Logger service for the update service. |
| Serge Bazanski | 3c5d063 | 2024-09-12 10:49:12 +0000 | [diff] [blame] | 56 | Logger logging.Leveled |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 57 | } |
| 58 | |
| 59 | type Slot int |
| 60 | |
| 61 | const ( |
| 62 | SlotInvalid Slot = 0 |
| 63 | SlotA Slot = 1 |
| 64 | SlotB Slot = 2 |
| 65 | ) |
| 66 | |
| 67 | // Other returns the "other" slot, i.e. returns slot A for B and B for A. |
| 68 | // It returns SlotInvalid for any s which is not SlotA or SlotB. |
| 69 | func (s Slot) Other() Slot { |
| 70 | switch s { |
| 71 | case SlotA: |
| 72 | return SlotB |
| 73 | case SlotB: |
| 74 | return SlotA |
| 75 | default: |
| 76 | return SlotInvalid |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | func (s Slot) String() string { |
| 81 | switch s { |
| 82 | case SlotA: |
| 83 | return "A" |
| 84 | case SlotB: |
| 85 | return "B" |
| 86 | default: |
| 87 | return "<invalid slot>" |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | func (s Slot) EFIBootPath() string { |
| 92 | switch s { |
| 93 | case SlotA: |
| Jan Schär | e19d279 | 2025-06-23 12:37:58 +0000 | [diff] [blame] | 94 | return install.EFIBootAPath |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 95 | case SlotB: |
| Jan Schär | e19d279 | 2025-06-23 12:37:58 +0000 | [diff] [blame] | 96 | return install.EFIBootBPath |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 97 | default: |
| 98 | return "" |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | var slotRegexp = regexp.MustCompile(`PARTLABEL=METROPOLIS-SYSTEM-([AB])`) |
| 103 | |
| 104 | // ProvideESP is a convenience function for providing information about the |
| 105 | // ESP after the update service has been instantiated. |
| Tim Windelschmidt | 8e87a06 | 2023-07-31 01:33:10 +0000 | [diff] [blame] | 106 | func (s *Service) ProvideESP(path string, partNum uint32, part *gpt.Partition) { |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 107 | s.ESPPath = path |
| 108 | s.ESPPartNumber = partNum |
| Tim Windelschmidt | 8e87a06 | 2023-07-31 01:33:10 +0000 | [diff] [blame] | 109 | s.ESPPart = part |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 110 | } |
| 111 | |
| 112 | // CurrentlyRunningSlot returns the slot the current system is booted from. |
| 113 | func (s *Service) CurrentlyRunningSlot() Slot { |
| 114 | cmdline, err := os.ReadFile("/proc/cmdline") |
| 115 | if err != nil { |
| 116 | return SlotInvalid |
| 117 | } |
| 118 | slotMatches := slotRegexp.FindStringSubmatch(string(cmdline)) |
| 119 | if len(slotMatches) != 2 { |
| 120 | return SlotInvalid |
| 121 | } |
| 122 | switch slotMatches[1] { |
| 123 | case "A": |
| 124 | return SlotA |
| 125 | case "B": |
| 126 | return SlotB |
| 127 | default: |
| 128 | panic("unreachable") |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | var bootVarRegexp = regexp.MustCompile(`^Boot([0-9A-Fa-f]{4})$`) |
| 133 | |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 134 | // MarkBootSuccessful must be called after each boot if some implementation- |
| 135 | // defined criteria for a successful boot are met. If an update has been |
| 136 | // installed and booted and this function is called, the updated version is |
| 137 | // marked as default. If an issue occurs during boot and so this function is |
| 138 | // not called the old version will be started again on next boot. |
| 139 | func (s *Service) MarkBootSuccessful() error { |
| 140 | if s.ESPPath == "" { |
| 141 | return errors.New("no ESP information provided to update service, cannot continue") |
| 142 | } |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 143 | if err := s.fixupEFI(); err != nil { |
| 144 | s.Logger.Errorf("Error when checking boot entry configuration: %v", err) |
| 145 | } |
| 146 | if err := s.fixupPreloader(); err != nil { |
| 147 | s.Logger.Errorf("Error when fixing A/B preloader: %v", err) |
| 148 | } |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 149 | activeSlot := s.CurrentlyRunningSlot() |
| Lorenz Brun | 54a5a05 | 2023-10-02 16:40:11 +0200 | [diff] [blame] | 150 | abState, err := s.getABState() |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 151 | if err != nil { |
| Lorenz Brun | 54a5a05 | 2023-10-02 16:40:11 +0200 | [diff] [blame] | 152 | s.Logger.Warningf("Error while getting A/B loader state, recreating: %v", err) |
| 153 | abState = &abloaderpb.ABLoaderData{ |
| 154 | ActiveSlot: abloaderpb.Slot(activeSlot), |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 155 | } |
| Lorenz Brun | 54a5a05 | 2023-10-02 16:40:11 +0200 | [diff] [blame] | 156 | err := s.setABState(abState) |
| 157 | if err != nil { |
| 158 | return fmt.Errorf("while recreating A/B loader state: %w", err) |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 159 | } |
| 160 | } |
| Lorenz Brun | 54a5a05 | 2023-10-02 16:40:11 +0200 | [diff] [blame] | 161 | if Slot(abState.ActiveSlot) != activeSlot { |
| 162 | err := s.setABState(&abloaderpb.ABLoaderData{ |
| 163 | ActiveSlot: abloaderpb.Slot(activeSlot), |
| 164 | }) |
| 165 | if err != nil { |
| 166 | return fmt.Errorf("while setting next A/B slot: %w", err) |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 167 | } |
| 168 | s.Logger.Infof("Permanently activated slot %v", activeSlot) |
| 169 | } else { |
| 170 | s.Logger.Infof("Normal boot from slot %v", activeSlot) |
| 171 | } |
| 172 | |
| 173 | return nil |
| 174 | } |
| 175 | |
| Lorenz Brun | ca6da6a | 2024-09-09 17:55:15 +0200 | [diff] [blame] | 176 | // Rollback sets the currently-inactive slot as the next boot slot. This is |
| 177 | // intended to recover from scenarios where roll-forward fixing is difficult. |
| 178 | // Only the next boot slot is set to make sure that the node is not |
| 179 | // made unbootable accidentally. On successful bootup that code can switch the |
| 180 | // active slot to itself. |
| 181 | func (s *Service) Rollback() error { |
| 182 | if s.ESPPath == "" { |
| 183 | return errors.New("no ESP information provided to update service, cannot continue") |
| 184 | } |
| 185 | activeSlot := s.CurrentlyRunningSlot() |
| 186 | abState, err := s.getABState() |
| 187 | if err != nil { |
| 188 | return fmt.Errorf("no valid A/B loader state, cannot rollback: %w", err) |
| 189 | } |
| 190 | nextSlot := activeSlot.Other() |
| 191 | err = s.setABState(&abloaderpb.ABLoaderData{ |
| 192 | ActiveSlot: abState.ActiveSlot, |
| 193 | NextSlot: abloaderpb.Slot(nextSlot), |
| 194 | }) |
| 195 | if err != nil { |
| 196 | return fmt.Errorf("while setting next A/B slot: %w", err) |
| 197 | } |
| 198 | s.Logger.Warningf("Rollback requested, NextSlot set to %v", nextSlot) |
| 199 | return nil |
| 200 | } |
| 201 | |
| Lorenz Brun | 1640c28 | 2024-09-09 17:50:48 +0200 | [diff] [blame] | 202 | // KexecLoadNext loads the slot to be booted next into the kexec staging area. |
| 203 | // The next slot can then be launched by executing kexec via the reboot |
| 204 | // syscall. Calling this function counts as a next boot for the purposes of |
| 205 | // A/B state tracking, so it should not be called without kexecing afterwards. |
| 206 | func (s *Service) KexecLoadNext() error { |
| 207 | state, err := s.getABState() |
| 208 | if err != nil { |
| 209 | return fmt.Errorf("bad A/B state: %w", err) |
| 210 | } |
| 211 | slotToLoad := Slot(state.ActiveSlot) |
| Tim Windelschmidt | a10d0cb | 2025-01-13 14:44:15 +0100 | [diff] [blame] | 212 | if state.NextSlot != abloaderpb.Slot_SLOT_NONE { |
| Lorenz Brun | 1640c28 | 2024-09-09 17:50:48 +0200 | [diff] [blame] | 213 | slotToLoad = Slot(state.NextSlot) |
| Tim Windelschmidt | a10d0cb | 2025-01-13 14:44:15 +0100 | [diff] [blame] | 214 | state.NextSlot = abloaderpb.Slot_SLOT_NONE |
| Lorenz Brun | 1640c28 | 2024-09-09 17:50:48 +0200 | [diff] [blame] | 215 | err = s.setABState(state) |
| 216 | if err != nil { |
| 217 | return fmt.Errorf("while updating A/B state: %w", err) |
| 218 | } |
| 219 | } |
| 220 | boot, err := os.Open(filepath.Join(s.ESPPath, slotToLoad.EFIBootPath())) |
| 221 | if err != nil { |
| 222 | return fmt.Errorf("failed to open boot file for slot %v: %w", slotToLoad, err) |
| 223 | } |
| 224 | defer boot.Close() |
| 225 | if err := s.stageKexec(boot, slotToLoad); err != nil { |
| 226 | return fmt.Errorf("failed to stage next slot for kexec: %w", err) |
| 227 | } |
| 228 | return nil |
| 229 | } |
| 230 | |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 231 | func openSystemSlot(slot Slot) (*blockdev.Device, error) { |
| 232 | switch slot { |
| 233 | case SlotA: |
| 234 | return blockdev.Open("/dev/system-a") |
| 235 | case SlotB: |
| 236 | return blockdev.Open("/dev/system-b") |
| 237 | default: |
| 238 | return nil, errors.New("invalid slot identifier given") |
| 239 | } |
| 240 | } |
| 241 | |
| Lorenz Brun | 54a5a05 | 2023-10-02 16:40:11 +0200 | [diff] [blame] | 242 | func (s *Service) getABState() (*abloaderpb.ABLoaderData, error) { |
| 243 | abDataRaw, err := os.ReadFile(filepath.Join(s.ESPPath, "EFI/metropolis/loader_state.pb")) |
| 244 | if err != nil { |
| 245 | return nil, err |
| 246 | } |
| 247 | var abData abloaderpb.ABLoaderData |
| 248 | if err := proto.Unmarshal(abDataRaw, &abData); err != nil { |
| 249 | return nil, err |
| 250 | } |
| 251 | return &abData, nil |
| 252 | } |
| 253 | |
| 254 | func (s *Service) setABState(d *abloaderpb.ABLoaderData) error { |
| 255 | abDataRaw, err := proto.Marshal(d) |
| 256 | if err != nil { |
| 257 | return fmt.Errorf("while marshaling: %w", err) |
| 258 | } |
| 259 | if err := os.WriteFile(filepath.Join(s.ESPPath, "EFI/metropolis/loader_state.pb"), abDataRaw, 0666); err != nil { |
| 260 | return err |
| 261 | } |
| 262 | return nil |
| 263 | } |
| 264 | |
| Jan Schär | 1a7e1fe | 2025-07-25 16:50:12 +0200 | [diff] [blame] | 265 | func selectArchitecture(ref oci.Ref, architecture string) (*oci.Image, error) { |
| 266 | switch ref := ref.(type) { |
| 267 | case *oci.Image: |
| 268 | return ref, nil |
| 269 | case *oci.Index: |
| 270 | var found *ocispecv1.Descriptor |
| 271 | for i := range ref.Manifest.Manifests { |
| 272 | descriptor := &ref.Manifest.Manifests[i] |
| 273 | if descriptor.Platform != nil && descriptor.Platform.Architecture == architecture { |
| 274 | if found != nil { |
| 275 | return nil, fmt.Errorf("invalid index, found multiple matching entries") |
| 276 | } |
| 277 | found = descriptor |
| 278 | } |
| 279 | } |
| 280 | if found == nil { |
| 281 | return nil, fmt.Errorf("no matching entry found in index for architecture %s", architecture) |
| 282 | } |
| 283 | return oci.AsImage(ref.Ref(found)) |
| 284 | default: |
| 285 | return nil, fmt.Errorf("unknown manifest media type %q", ref.MediaType()) |
| 286 | } |
| 287 | } |
| 288 | |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 289 | // InstallImage fetches the given image, installs it into the currently inactive |
| 290 | // slot and sets that slot to boot next. If it doesn't return an error, a reboot |
| 291 | // boots into the new slot. |
| 292 | func (s *Service) InstallImage(ctx context.Context, imageRef *apb.OSImageRef, withKexec bool) error { |
| 293 | if imageRef == nil { |
| 294 | return fmt.Errorf("missing OS image in OS installation request") |
| 295 | } |
| 296 | if imageRef.Digest == "" { |
| 297 | return fmt.Errorf("missing digest in OS installation request") |
| 298 | } |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 299 | if s.ESPPath == "" { |
| 300 | return errors.New("no ESP information provided to update service, cannot continue") |
| 301 | } |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 302 | |
| 303 | downloadCtx, cancel := context.WithTimeout(ctx, 15*time.Minute) |
| 304 | defer cancel() |
| 305 | |
| 306 | client := ®istry.Client{ |
| 307 | GetBackOff: func() backoff.BackOff { |
| 308 | return backoff.NewExponentialBackOff() |
| 309 | }, |
| 310 | RetryNotify: func(err error, d time.Duration) { |
| 311 | s.Logger.Warningf("Error while fetching OS image, retrying in %v: %v", d, err) |
| 312 | }, |
| Jan Schär | b86917b | 2025-05-14 16:31:08 +0000 | [diff] [blame] | 313 | UserAgent: "MonogonOS/" + productinfo.Get().VersionString, |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 314 | Scheme: imageRef.Scheme, |
| 315 | Host: imageRef.Host, |
| 316 | Repository: imageRef.Repository, |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 317 | } |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 318 | |
| Jan Schär | 1a7e1fe | 2025-07-25 16:50:12 +0200 | [diff] [blame] | 319 | ref, err := client.Read(downloadCtx, imageRef.Tag, imageRef.Digest) |
| 320 | if err != nil { |
| 321 | return fmt.Errorf("failed to fetch OS image: %w", err) |
| 322 | } |
| 323 | image, err := selectArchitecture(ref, runtime.GOARCH) |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 324 | if err != nil { |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 325 | return fmt.Errorf("failed to fetch OS image: %w", err) |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 326 | } |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 327 | |
| Jan Schär | e19d279 | 2025-06-23 12:37:58 +0000 | [diff] [blame] | 328 | osImage, err := osimage.Read(image) |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 329 | if err != nil { |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 330 | return fmt.Errorf("failed to fetch OS image: %w", err) |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 331 | } |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 332 | |
| 333 | efiPayload, err := osImage.Payload("kernel.efi") |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 334 | if err != nil { |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 335 | return fmt.Errorf("cannot open EFI payload in OS image: %w", err) |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 336 | } |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 337 | systemImage, err := osImage.Payload("system") |
| 338 | if err != nil { |
| 339 | return fmt.Errorf("cannot open system image in OS image: %w", err) |
| 340 | } |
| 341 | |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 342 | activeSlot := s.CurrentlyRunningSlot() |
| 343 | if activeSlot == SlotInvalid { |
| 344 | return errors.New("unable to determine active slot, cannot continue") |
| 345 | } |
| 346 | targetSlot := activeSlot.Other() |
| 347 | |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 348 | systemPart, err := openSystemSlot(targetSlot) |
| 349 | if err != nil { |
| 350 | return status.Errorf(codes.Internal, "Inactive system slot unavailable: %v", err) |
| 351 | } |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 352 | systemImageContent, err := systemImage.Open() |
| 353 | if err != nil { |
| 354 | systemPart.Close() |
| 355 | return fmt.Errorf("failed to open system image: %w", err) |
| 356 | } |
| 357 | _, err = io.Copy(blockdev.NewRWS(systemPart), systemImageContent) |
| 358 | systemImageContent.Close() |
| 359 | closeErr := systemPart.Close() |
| 360 | if err == nil { |
| 361 | err = closeErr |
| 362 | } |
| 363 | if err != nil { |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 364 | return status.Errorf(codes.Unavailable, "Failed to copy system image: %v", err) |
| 365 | } |
| 366 | |
| 367 | bootFile, err := os.Create(filepath.Join(s.ESPPath, targetSlot.EFIBootPath())) |
| 368 | if err != nil { |
| 369 | return fmt.Errorf("failed to open boot file: %w", err) |
| 370 | } |
| 371 | defer bootFile.Close() |
| Jan Schär | 62cecde | 2025-04-16 15:24:04 +0000 | [diff] [blame] | 372 | efiPayloadContent, err := efiPayload.Open() |
| 373 | if err != nil { |
| 374 | return fmt.Errorf("failed to open EFI payload: %w", err) |
| 375 | } |
| 376 | _, err = io.Copy(bootFile, efiPayloadContent) |
| 377 | efiPayloadContent.Close() |
| 378 | if err != nil { |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 379 | return fmt.Errorf("failed to write boot file: %w", err) |
| 380 | } |
| 381 | |
| Lorenz Brun | d14be0e | 2023-07-31 16:46:14 +0200 | [diff] [blame] | 382 | if withKexec { |
| 383 | if err := s.stageKexec(bootFile, targetSlot); err != nil { |
| 384 | return fmt.Errorf("while kexec staging: %w", err) |
| 385 | } |
| 386 | } else { |
| Lorenz Brun | 54a5a05 | 2023-10-02 16:40:11 +0200 | [diff] [blame] | 387 | err := s.setABState(&abloaderpb.ABLoaderData{ |
| 388 | ActiveSlot: abloaderpb.Slot(activeSlot), |
| 389 | NextSlot: abloaderpb.Slot(targetSlot), |
| 390 | }) |
| 391 | if err != nil { |
| 392 | return fmt.Errorf("while setting next A/B slot: %w", err) |
| Lorenz Brun | d14be0e | 2023-07-31 16:46:14 +0200 | [diff] [blame] | 393 | } |
| Lorenz Brun | 35fcf03 | 2023-06-29 04:15:58 +0200 | [diff] [blame] | 394 | } |
| 395 | |
| 396 | return nil |
| 397 | } |
| 398 | |
| Lorenz Brun | d14be0e | 2023-07-31 16:46:14 +0200 | [diff] [blame] | 399 | // newMemfile creates a new file which is not located on a specific filesystem, |
| 400 | // but is instead backed by anonymous memory. |
| 401 | func newMemfile(name string, flags int) (*os.File, error) { |
| 402 | fd, err := unix.MemfdCreate(name, flags) |
| 403 | if err != nil { |
| 404 | return nil, fmt.Errorf("memfd_create: %w", err) |
| 405 | } |
| 406 | return os.NewFile(uintptr(fd), name), nil |
| 407 | } |
| 408 | |
| 409 | // stageKexec stages the kernel, command line and initramfs if available for |
| 410 | // a future kexec. It extracts the relevant data from the EFI boot executable. |
| 411 | func (s *Service) stageKexec(bootFile io.ReaderAt, targetSlot Slot) error { |
| 412 | bootPE, err := pe.NewFile(bootFile) |
| 413 | if err != nil { |
| 414 | return fmt.Errorf("unable to open bootFile as PE: %w", err) |
| 415 | } |
| 416 | var cmdlineRaw []byte |
| 417 | cmdlineSection := bootPE.Section(".cmdline") |
| 418 | if cmdlineSection == nil { |
| 419 | return fmt.Errorf("no .cmdline section in boot PE") |
| 420 | } |
| 421 | cmdlineRaw, err = cmdlineSection.Data() |
| 422 | if err != nil { |
| 423 | return fmt.Errorf("while reading .cmdline PE section: %w", err) |
| 424 | } |
| 425 | cmdline := string(bytes.TrimRight(cmdlineRaw, "\x00")) |
| 426 | cmdline = strings.ReplaceAll(cmdline, "METROPOLIS-SYSTEM-X", fmt.Sprintf("METROPOLIS-SYSTEM-%s", targetSlot)) |
| 427 | kernelFile, err := newMemfile("kernel", 0) |
| 428 | if err != nil { |
| 429 | return fmt.Errorf("failed to create kernel memfile: %w", err) |
| 430 | } |
| 431 | defer kernelFile.Close() |
| 432 | kernelSection := bootPE.Section(".linux") |
| 433 | if kernelSection == nil { |
| 434 | return fmt.Errorf("no .linux section in boot PE") |
| 435 | } |
| 436 | if _, err := io.Copy(kernelFile, kernelSection.Open()); err != nil { |
| 437 | return fmt.Errorf("while copying .linux PE section: %w", err) |
| 438 | } |
| 439 | |
| 440 | initramfsSection := bootPE.Section(".initrd") |
| 441 | var initramfsFile *os.File |
| 442 | if initramfsSection != nil && initramfsSection.Size > 0 { |
| 443 | initramfsFile, err = newMemfile("initramfs", 0) |
| 444 | if err != nil { |
| 445 | return fmt.Errorf("failed to create initramfs memfile: %w", err) |
| 446 | } |
| 447 | defer initramfsFile.Close() |
| 448 | if _, err := io.Copy(initramfsFile, initramfsSection.Open()); err != nil { |
| 449 | return fmt.Errorf("while copying .initrd PE section: %w", err) |
| 450 | } |
| 451 | } |
| 452 | if err := kexec.FileLoad(kernelFile, initramfsFile, cmdline); err != nil { |
| 453 | return fmt.Errorf("while staging new kexec kernel: %w", err) |
| 454 | } |
| 455 | return nil |
| 456 | } |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 457 | |
| Jan Schär | 2b9a0a0 | 2025-07-09 07:54:12 +0000 | [diff] [blame] | 458 | //go:embed metropolis/node/abloader/abloader.efi |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 459 | var abloader []byte |
| 460 | |
| 461 | func (s *Service) fixupPreloader() error { |
| Jan Schär | e19d279 | 2025-06-23 12:37:58 +0000 | [diff] [blame] | 462 | efiBootPath, err := install.EFIBootPath(productinfo.Get().Info.Architecture()) |
| Jan Schär | 4b88826 | 2025-05-13 09:12:03 +0000 | [diff] [blame] | 463 | if err != nil { |
| 464 | return err |
| 465 | } |
| 466 | efiBootFilePath := filepath.Join(s.ESPPath, efiBootPath) |
| 467 | abLoaderFile, err := os.Open(efiBootFilePath) |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 468 | if err != nil { |
| 469 | s.Logger.Warningf("A/B preloader not available, attempting to restore: %v", err) |
| 470 | } else { |
| 471 | expectedSum := sha256.Sum256(abloader) |
| 472 | h := sha256.New() |
| 473 | _, err := io.Copy(h, abLoaderFile) |
| 474 | abLoaderFile.Close() |
| 475 | if err == nil { |
| 476 | if bytes.Equal(h.Sum(nil), expectedSum[:]) { |
| 477 | // A/B Preloader is present and has correct hash |
| 478 | return nil |
| 479 | } else { |
| 480 | s.Logger.Infof("Replacing A/B preloader with current version: %x %x", h.Sum(nil), expectedSum[:]) |
| 481 | } |
| 482 | } else { |
| 483 | s.Logger.Warningf("Error while reading A/B preloader, restoring: %v", err) |
| 484 | } |
| 485 | } |
| 486 | preloader, err := os.Create(filepath.Join(s.ESPPath, "preloader.swp")) |
| 487 | if err != nil { |
| 488 | return fmt.Errorf("while creating preloader swap file: %w", err) |
| 489 | } |
| 490 | if _, err := preloader.Write(abloader); err != nil { |
| 491 | return fmt.Errorf("while writing preloader swap file: %w", err) |
| 492 | } |
| 493 | if err := preloader.Sync(); err != nil { |
| 494 | return fmt.Errorf("while sync'ing preloader swap file: %w", err) |
| 495 | } |
| 496 | preloader.Close() |
| Jan Schär | 4b88826 | 2025-05-13 09:12:03 +0000 | [diff] [blame] | 497 | if err := os.Rename(filepath.Join(s.ESPPath, "preloader.swp"), efiBootFilePath); err != nil { |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 498 | return fmt.Errorf("while swapping preloader: %w", err) |
| 499 | } |
| 500 | s.Logger.Info("Successfully wrote current preloader") |
| 501 | return nil |
| 502 | } |
| 503 | |
| 504 | // fixupEFI checks for the existence and correctness of the EFI boot entry |
| 505 | // repairs/recreates it if needed. |
| 506 | func (s *Service) fixupEFI() error { |
| Jan Schär | e19d279 | 2025-06-23 12:37:58 +0000 | [diff] [blame] | 507 | efiBootPath, err := install.EFIBootPath(productinfo.Get().Info.Architecture()) |
| Jan Schär | 4b88826 | 2025-05-13 09:12:03 +0000 | [diff] [blame] | 508 | if err != nil { |
| 509 | return err |
| 510 | } |
| 511 | efiBootVarPath := "/" + efiBootPath |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 512 | varNames, err := efivarfs.List(efivarfs.ScopeGlobal) |
| 513 | if err != nil { |
| 514 | return fmt.Errorf("failed to list EFI variables: %w", err) |
| 515 | } |
| Tim Windelschmidt | 5e460a9 | 2024-04-11 01:33:09 +0200 | [diff] [blame] | 516 | var validBootEntryIdx = -1 |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 517 | for _, varName := range varNames { |
| 518 | m := bootVarRegexp.FindStringSubmatch(varName) |
| 519 | if m == nil { |
| 520 | continue |
| 521 | } |
| 522 | idx, err := strconv.ParseUint(m[1], 16, 16) |
| 523 | if err != nil { |
| 524 | // This cannot be hit as all regexp matches are parseable. |
| 525 | panic(err) |
| 526 | } |
| 527 | e, err := efivarfs.GetBootEntry(int(idx)) |
| 528 | if err != nil { |
| 529 | s.Logger.Warningf("Unable to get boot entry %d, skipping: %v", idx, err) |
| 530 | continue |
| 531 | } |
| 532 | if len(e.FilePath) != 2 { |
| 533 | // Not our entry, ours always have two parts |
| 534 | continue |
| 535 | } |
| 536 | switch p := e.FilePath[0].(type) { |
| 537 | case *efivarfs.HardDrivePath: |
| 538 | gptMatch, ok := p.PartitionMatch.(*efivarfs.PartitionGPT) |
| 539 | if ok && gptMatch.PartitionUUID != s.ESPPart.ID { |
| 540 | // Not related to our ESP |
| 541 | continue |
| 542 | } |
| 543 | default: |
| 544 | continue |
| 545 | } |
| 546 | switch p := e.FilePath[1].(type) { |
| 547 | case efivarfs.FilePath: |
| Jan Schär | 4b88826 | 2025-05-13 09:12:03 +0000 | [diff] [blame] | 548 | if string(p) == efiBootVarPath { |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 549 | if validBootEntryIdx == -1 { |
| 550 | validBootEntryIdx = int(idx) |
| 551 | } else { |
| 552 | // Another valid boot entry already exists, delete this one |
| 553 | err := efivarfs.DeleteBootEntry(int(idx)) |
| 554 | if err == nil { |
| 555 | s.Logger.Infof("Deleted duplicate boot entry %q", e.Description) |
| 556 | } else { |
| 557 | s.Logger.Warningf("Error while deleting duplicate boot entry %q: %v", e.Description, err) |
| 558 | } |
| 559 | } |
| 560 | } else if strings.Contains(e.Description, "Metropolis") { |
| 561 | err := efivarfs.DeleteBootEntry(int(idx)) |
| 562 | if err == nil { |
| 563 | s.Logger.Infof("Deleted orphaned boot entry %q", e.Description) |
| 564 | } else { |
| 565 | s.Logger.Warningf("Error while deleting orphaned boot entry %q: %v", e.Description, err) |
| 566 | } |
| 567 | } |
| 568 | default: |
| 569 | continue |
| 570 | } |
| 571 | } |
| 572 | if validBootEntryIdx == -1 { |
| 573 | validBootEntryIdx, err = efivarfs.AddBootEntry(&efivarfs.LoadOption{ |
| 574 | Description: "Metropolis", |
| 575 | FilePath: efivarfs.DevicePath{ |
| 576 | &efivarfs.HardDrivePath{ |
| 577 | PartitionNumber: 1, |
| 578 | PartitionStartBlock: s.ESPPart.FirstBlock, |
| 579 | PartitionSizeBlocks: s.ESPPart.SizeBlocks(), |
| 580 | PartitionMatch: efivarfs.PartitionGPT{ |
| 581 | PartitionUUID: s.ESPPart.ID, |
| 582 | }, |
| 583 | }, |
| Jan Schär | 4b88826 | 2025-05-13 09:12:03 +0000 | [diff] [blame] | 584 | efivarfs.FilePath(efiBootVarPath), |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 585 | }, |
| 586 | }) |
| 587 | if err == nil { |
| 588 | s.Logger.Infof("Restored missing EFI boot entry for Metropolis") |
| 589 | } else { |
| Tim Windelschmidt | 5f1a7de | 2024-09-19 02:00:14 +0200 | [diff] [blame] | 590 | return fmt.Errorf("while restoring missing EFI boot entry for Metropolis: %w", err) |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 591 | } |
| 592 | } |
| 593 | bootOrder, err := efivarfs.GetBootOrder() |
| 594 | if err != nil { |
| Tim Windelschmidt | 5f1a7de | 2024-09-19 02:00:14 +0200 | [diff] [blame] | 595 | return fmt.Errorf("failed to get EFI boot order: %w", err) |
| Lorenz Brun | d79881d | 2023-11-30 19:02:06 +0100 | [diff] [blame] | 596 | } |
| 597 | for _, bentry := range bootOrder { |
| 598 | if bentry == uint16(validBootEntryIdx) { |
| 599 | // Our boot entry is in the boot order, everything's ok |
| 600 | return nil |
| 601 | } |
| 602 | } |
| 603 | newBootOrder := append(efivarfs.BootOrder{uint16(validBootEntryIdx)}, bootOrder...) |
| 604 | if err := efivarfs.SetBootOrder(newBootOrder); err != nil { |
| 605 | return fmt.Errorf("while setting EFI boot order: %w", err) |
| 606 | } |
| 607 | return nil |
| 608 | } |