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