1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
|
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemon
import (
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/containerd/containerd/log"
"github.com/containerd/nydus-snapshotter/config"
"github.com/containerd/nydus-snapshotter/config/daemonconfig"
"github.com/containerd/nydus-snapshotter/pkg/daemon/types"
"github.com/containerd/nydus-snapshotter/pkg/errdefs"
"github.com/containerd/nydus-snapshotter/pkg/rafs"
"github.com/containerd/nydus-snapshotter/pkg/supervisor"
"github.com/containerd/nydus-snapshotter/pkg/utils/erofs"
"github.com/containerd/nydus-snapshotter/pkg/utils/mount"
"github.com/containerd/nydus-snapshotter/pkg/utils/retry"
)
const (
APISocketFileName = "api.sock"
SharedNydusDaemonID = "shared_daemon"
)
type NewDaemonOpt func(d *Daemon) error
// Fields in this structure should be write-once, and caller should hold `Daemon.mu` when updating fields.
type ConfigState struct {
// A unique ID generated by daemon manager to identify the nydusd instance.
ID string
ProcessID int
APISocket string
DaemonMode config.DaemonMode
FsDriver string
LogDir string
LogLevel string
LogRotationSize int
LogToStdout bool
Mountpoint string
SupervisorPath string
ThreadNum int
// Where the configuration file resides, all rafs instances share the same configuration template
ConfigDir string
}
// TODO: Record queried nydusd state
type Daemon struct {
States ConfigState
mu sync.Mutex
// Host all RAFS filesystems managed by this daemon:
// fusedev dedicated mode: one and only one RAFS instance
// fusedev shared mode: zero, one or more RAFS instances
// fscache shared mode: zero, one or more RAFS instances
RafsCache rafs.Cache
// Protect nydusd http client
cmu sync.Mutex
// client will be rebuilt on Reconnect, skip marshal/unmarshal
client NydusdClient
// Nil means this daemon object has no supervisor
Supervisor *supervisor.Supervisor
Config daemonconfig.DaemonConfig
// How much CPU nydusd is utilizing when starts since full prefetch might
// consume many CPU cycles
StartupCPUUtilization float64
Version types.BuildTimeInfo
ref int32
// Cache the nydusd daemon state to avoid frequently querying nydusd by API.
state types.DaemonState
}
func (d *Daemon) Lock() {
d.mu.Lock()
}
func (d *Daemon) Unlock() {
d.mu.Unlock()
}
func (d *Daemon) ID() string {
return d.States.ID
}
func (d *Daemon) Pid() int {
return d.States.ProcessID
}
func (d *Daemon) IncRef() {
atomic.AddInt32(&d.ref, 1)
}
func (d *Daemon) DecRef() int32 {
return atomic.AddInt32(&d.ref, -1)
}
func (d *Daemon) GetRef() int32 {
return atomic.LoadInt32(&d.ref)
}
func (d *Daemon) HostMountpoint() (mnt string) {
mnt = d.States.Mountpoint
return
}
// Each nydusd daemon has a copy of configuration json file.
func (d *Daemon) ConfigFile(instanceID string) string {
if instanceID == "" {
return filepath.Join(d.States.ConfigDir, "config.json")
}
return filepath.Join(d.States.ConfigDir, instanceID, "config.json")
}
// NydusdThreadNum returns how many working threads are needed of a single nydusd
func (d *Daemon) NydusdThreadNum() int {
return d.States.ThreadNum
}
func (d *Daemon) GetAPISock() string {
return d.States.APISocket
}
func (d *Daemon) LogFile() string {
return filepath.Join(d.States.LogDir, "nydusd.log")
}
func (d *Daemon) AddRafsInstance(r *rafs.Rafs) {
d.RafsCache.Add(r)
d.IncRef()
r.DaemonID = d.ID()
}
func (d *Daemon) RemoveRafsInstance(snapshotID string) {
d.RafsCache.Remove(snapshotID)
d.DecRef()
}
// Get and cache daemon current working state by querying nydusd:
// 1. INIT
// 2. READY: All needed resources are ready.
// 3. RUNNING
func (d *Daemon) GetState() (types.DaemonState, error) {
c, err := d.GetClient()
if err != nil {
return types.DaemonStateUnknown, errors.Wrapf(err, "get daemon state")
}
info, err := c.GetDaemonInfo()
if err != nil {
return types.DaemonStateUnknown, err
}
st := info.DaemonState()
d.Lock()
d.state = st
d.Version = info.DaemonVersion()
d.Unlock()
return st, nil
}
// Return the cached nydusd working status, no API is invoked.
func (d *Daemon) State() types.DaemonState {
d.Lock()
defer d.Unlock()
return d.state
}
// Reset the cached nydusd working status
func (d *Daemon) ResetState() {
d.Lock()
defer d.Unlock()
d.state = types.DaemonStateUnknown
}
// Wait for the nydusd daemon to reach specified state with timeout.
func (d *Daemon) WaitUntilState(expected types.DaemonState) error {
return retry.Do(func() error {
if expected == d.State() {
return nil
}
state, err := d.GetState()
if err != nil {
return errors.Wrapf(err, "wait until daemon is %s", expected)
}
if state != expected {
return errors.Errorf("daemon %s is not %s yet, current state %s",
d.ID(), expected, state)
}
return nil
},
retry.LastErrorOnly(true),
retry.Attempts(20), // totally wait for 2 seconds, should be enough
retry.Delay(100*time.Millisecond),
)
}
func (d *Daemon) IsSharedDaemon() bool {
if d.States.DaemonMode != "" {
return d.States.DaemonMode == config.DaemonModeShared
}
return d.HostMountpoint() == config.GetRootMountpoint()
}
func (d *Daemon) SharedMount(rafs *rafs.Rafs) error {
defer d.SendStates()
switch d.States.FsDriver {
case config.FsDriverFscache:
if err := d.sharedErofsMount(rafs); err != nil {
return errors.Wrapf(err, "mount erofs")
}
return nil
case config.FsDriverFusedev:
return d.sharedFusedevMount(rafs)
default:
return errors.Errorf("unsupported fs driver %s", d.States.FsDriver)
}
}
func (d *Daemon) sharedFusedevMount(rafs *rafs.Rafs) error {
client, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "mount instance %s", rafs.SnapshotID)
}
bootstrap, err := rafs.BootstrapFile()
if err != nil {
return err
}
c, err := daemonconfig.NewDaemonConfig(d.States.FsDriver, d.ConfigFile(rafs.SnapshotID))
if err != nil {
return errors.Wrapf(err, "Failed to reload instance configuration %s",
d.ConfigFile(rafs.SnapshotID))
}
cfg, err := c.DumpString()
if err != nil {
return errors.Wrap(err, "dump instance configuration")
}
err = client.Mount(rafs.RelaMountpoint(), bootstrap, cfg)
if err != nil {
return errors.Wrapf(err, "mount rafs instance")
}
return nil
}
func (d *Daemon) sharedErofsMount(ra *rafs.Rafs) error {
client, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "bind blob %s", d.ID())
}
// TODO: Why fs cache needing this work dir?
if err := os.MkdirAll(ra.FscacheWorkDir(), 0755); err != nil {
return errors.Wrapf(err, "failed to create fscache work dir %s", ra.FscacheWorkDir())
}
c, err := daemonconfig.NewDaemonConfig(d.States.FsDriver, d.ConfigFile(ra.SnapshotID))
if err != nil {
log.L.Errorf("Failed to reload daemon configuration %s, %s", d.ConfigFile(ra.SnapshotID), err)
return err
}
cfgStr, err := c.DumpString()
if err != nil {
return err
}
if err := client.BindBlob(cfgStr); err != nil {
return errors.Wrapf(err, "request to bind fscache blob")
}
mountPoint := ra.GetMountpoint()
if err := os.MkdirAll(mountPoint, 0755); err != nil {
return errors.Wrapf(err, "create mountpoint %s", mountPoint)
}
bootstrapPath, err := ra.BootstrapFile()
if err != nil {
return err
}
fscacheID := erofs.FscacheID(ra.SnapshotID)
cfg := c.(*daemonconfig.FscacheDaemonConfig)
ra.AddAnnotation(rafs.AnnoFsCacheDomainID, cfg.DomainID)
ra.AddAnnotation(rafs.AnnoFsCacheID, fscacheID)
if err := erofs.Mount(bootstrapPath, cfg.DomainID, fscacheID, mountPoint); err != nil {
if !errdefs.IsErofsMounted(err) {
return errors.Wrapf(err, "mount erofs to %s", mountPoint)
}
// When snapshotter exits (either normally or abnormally), it will not have a
// chance to umount erofs mountpoint, so if snapshotter resumes running and mount
// again (by a new request to create container), it will need to ignore the mount
// error `device or resource busy`.
log.L.Warnf("erofs mountpoint %s has been mounted", mountPoint)
}
return nil
}
func (d *Daemon) SharedUmount(rafs *rafs.Rafs) error {
defer d.SendStates()
switch d.States.FsDriver {
case config.FsDriverFscache:
if err := d.sharedErofsUmount(rafs); err != nil {
return errors.Wrapf(err, "failed to erofs mount")
}
return nil
case config.FsDriverFusedev:
c, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "umount instance %s", rafs.SnapshotID)
}
return c.Umount(rafs.RelaMountpoint())
default:
return errors.Errorf("unsupported fs driver %s", d.States.FsDriver)
}
}
func (d *Daemon) sharedErofsUmount(ra *rafs.Rafs) error {
c, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "unbind blob %s", d.ID())
}
domainID := ra.Annotations[rafs.AnnoFsCacheDomainID]
fscacheID := ra.Annotations[rafs.AnnoFsCacheID]
if err := c.UnbindBlob(domainID, fscacheID); err != nil {
return errors.Wrapf(err, "request to unbind fscache blob, domain %s, fscache %s", domainID, fscacheID)
}
mountpoint := ra.GetMountpoint()
if err := erofs.Umount(mountpoint); err != nil {
return errors.Wrapf(err, "umount erofs %s mountpoint, %s", err, mountpoint)
}
// delete fscache bootstrap cache file
// erofs generate fscache cache file for bootstrap with fscacheID
if err := c.UnbindBlob("", fscacheID); err != nil {
log.L.Warnf("delete bootstrap %s err %s", fscacheID, err)
}
return nil
}
func (d *Daemon) UmountRafsInstance(r *rafs.Rafs) error {
if d.IsSharedDaemon() {
if err := d.SharedUmount(r); err != nil {
return errors.Wrapf(err, "umount fs instance %s", r.SnapshotID)
}
}
return nil
}
func (d *Daemon) UmountRafsInstances() error {
if d.IsSharedDaemon() {
d.RafsCache.Lock()
defer d.RafsCache.Unlock()
instances := d.RafsCache.ListLocked()
for _, r := range instances {
if err := d.SharedUmount(r); err != nil {
return errors.Wrapf(err, "umount fs instance %s", r.SnapshotID)
}
}
}
return nil
}
func (d *Daemon) SendStates() {
su := d.Supervisor
if su != nil {
// TODO: This should be optional by checking snapshotter's configuration.
// FIXME: Is it possible the states are overwritten during two API mounts.
// FIXME: What if nydusd does not support sending states.
err := su.FetchDaemonStates(func() error {
if err := d.doSendStates(); err != nil {
return errors.Wrapf(err, "send daemon %s states", d.ID())
}
return nil
})
if err != nil {
log.L.Warnf("Daemon %s does not support sending states, %v", d.ID(), err)
}
}
}
func (d *Daemon) doSendStates() error {
c, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "send states %s", d.ID())
}
if err := c.SendFd(); err != nil {
return errors.Wrap(err, "request to send states")
}
return nil
}
func (d *Daemon) TakeOver() error {
c, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "takeover daemon %s", d.ID())
}
if err := c.TakeOver(); err != nil {
return errors.Wrap(err, "request to take over")
}
return nil
}
func (d *Daemon) Start() error {
c, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "start service")
}
if err := c.Start(); err != nil {
return errors.Wrap(err, "request to start service")
}
return nil
}
func (d *Daemon) Exit() error {
c, err := d.GetClient()
if err != nil {
return errors.Wrapf(err, "start service")
}
if err := c.Exit(); err != nil {
return errors.Wrap(err, "request to exit service")
}
return nil
}
func (d *Daemon) GetDaemonInfo() (*types.DaemonInfo, error) {
c, err := d.GetClient()
if err != nil {
return nil, errors.Wrapf(err, "get daemon information")
}
return c.GetDaemonInfo()
}
func (d *Daemon) GetFsMetrics(sid string) (*types.FsMetrics, error) {
c, err := d.GetClient()
if err != nil {
return nil, errors.Wrapf(err, "get fs metrics")
}
return c.GetFsMetrics(sid)
}
func (d *Daemon) GetInflightMetrics() (*types.InflightMetrics, error) {
c, err := d.GetClient()
if err != nil {
return nil, errors.Wrapf(err, "get inflight metrics")
}
return c.GetInflightMetrics()
}
func (d *Daemon) GetCacheMetrics(sid string) (*types.CacheMetrics, error) {
c, err := d.GetClient()
if err != nil {
return nil, errors.Wrapf(err, "get cache metrics")
}
return c.GetCacheMetrics(sid)
}
func (d *Daemon) GetClient() (NydusdClient, error) {
d.cmu.Lock()
defer d.cmu.Unlock()
if d.client == nil {
sock := d.GetAPISock()
// The socket file may be residual from a dead nydusd
err := WaitUntilSocketExisted(sock, d.Pid())
if err != nil {
return nil, errors.Wrapf(errdefs.ErrNotFound, "daemon socket %s", sock)
}
client, err := NewNydusClient(sock)
if err != nil {
return nil, errors.Wrapf(err, "create daemon %s client", d.ID())
}
d.client = client
}
return d.client, nil
}
func (d *Daemon) ResetClient() {
d.cmu.Lock()
d.client = nil
d.cmu.Unlock()
}
func (d *Daemon) Terminate() error {
// if we found pid here, we need to kill and wait process to exit, Pid=0 means somehow we lost
// the daemon pid, so that we can't kill the process, just roughly umount the mountpoint
d.Lock()
defer d.Unlock()
if d.Pid() > 0 {
p, err := os.FindProcess(d.Pid())
if err != nil {
return errors.Wrapf(err, "find process %d", d.Pid())
}
if err = p.Signal(syscall.SIGTERM); err != nil {
return errors.Wrapf(err, "send SIGTERM signal to process %d", d.Pid())
}
}
return nil
}
func (d *Daemon) Wait() error {
// if we found pid here, we need to kill and wait process to exit, Pid=0 means somehow we lost
// the daemon pid, so that we can't kill the process, just roughly umount the mountpoint
d.Lock()
defer d.Unlock()
if d.Pid() > 0 {
p, err := os.FindProcess(d.Pid())
if err != nil {
return errors.Wrapf(err, "find process %d", d.Pid())
}
// if nydus-snapshotter restarts, it will break the relationship between nydusd and
// nydus-snapshotter, p.Wait() will return err, so here should exclude this case
if _, err = p.Wait(); err != nil && !errors.Is(err, syscall.ECHILD) {
log.L.Errorf("failed to process wait, %v", err)
} else if d.HostMountpoint() != "" && config.GetFsDriver() == config.FsDriverFusedev {
// No need to umount if the nydusd never performs mount. In other word, it does not
// associate with a host mountpoint.
if err := mount.WaitUntilUnmounted(d.HostMountpoint()); err != nil {
log.L.WithError(err).Errorf("umount %s", d.HostMountpoint())
}
}
}
return nil
}
// When daemon dies, clean up its vestige before start a new one.
func (d *Daemon) ClearVestige() {
mounter := mount.Mounter{}
if d.States.FsDriver == config.FsDriverFscache {
instances := d.RafsCache.List()
for _, i := range instances {
if err := mounter.Umount(i.GetMountpoint()); err != nil {
log.L.Warnf("Can't umount %s, %v", d.States.Mountpoint, err)
}
}
} else {
log.L.Infof("Unmounting %s when clear vestige", d.HostMountpoint())
if err := mounter.Umount(d.HostMountpoint()); err != nil {
log.L.Warnf("Can't umount %s, %v", d.States.Mountpoint, err)
}
}
// Nydusd judges if it should enter failover phrase by checking
// if unix socket is existed and it can't be connected.
if err := os.Remove(d.GetAPISock()); err != nil {
log.L.Warnf("Can't delete residual unix socket %s, %v", d.GetAPISock(), err)
}
// `CheckStatus->ensureClient` only checks if socket file is existed when building http client.
// But the socket file may be residual and will be cleared before starting a new nydusd.
// So clear the client by assigning nil
d.ResetClient()
}
func (d *Daemon) CloneRafsInstances(src *Daemon) {
instances := src.RafsCache.List()
d.RafsCache.SetIntances(instances)
}
// Daemon must be started and reach RUNNING state before call this method
func (d *Daemon) RecoverRafsInstances() error {
if d.IsSharedDaemon() {
d.RafsCache.Lock()
defer d.RafsCache.Unlock()
instances := make([]*rafs.Rafs, 0, 16)
for _, r := range d.RafsCache.ListLocked() {
instances = append(instances, r)
}
sort.Slice(instances, func(i, j int) bool {
return instances[i].Seq < instances[j].Seq
})
for _, i := range instances {
if d.HostMountpoint() != i.GetMountpoint() {
log.L.Infof("Recovered mount instance %s", i.SnapshotID)
if err := d.SharedMount(i); err != nil {
return err
}
}
}
}
return nil
}
// Instantiate a daemon object
func NewDaemon(opt ...NewDaemonOpt) (*Daemon, error) {
d := &Daemon{}
d.States.ID = newID()
d.States.DaemonMode = config.DaemonModeDedicated
d.RafsCache = rafs.NewRafsCache()
for _, o := range opt {
err := o(d)
if err != nil {
return nil, err
}
}
return d, nil
}
|