github.com/cilium/cilium@v1.16.2/pkg/kvstore/heartbeat/cell.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package heartbeat
     5  
     6  import (
     7  	"context"
     8  	"sync"
     9  
    10  	"github.com/cilium/hive/cell"
    11  
    12  	"github.com/cilium/cilium/pkg/kvstore"
    13  	"github.com/cilium/cilium/pkg/promise"
    14  )
    15  
    16  // Cell creates a cell responsible for periodically updating the heartbeat key
    17  // in the kvstore.
    18  var Cell = cell.Module(
    19  	"kvstore-heartbeat-updater",
    20  	"KVStore Heartbeat Updater",
    21  
    22  	cell.Invoke(func(lc cell.Lifecycle, backendPromise promise.Promise[kvstore.BackendOperations]) {
    23  		ctx, cancel := context.WithCancel(context.Background())
    24  		var wg sync.WaitGroup
    25  
    26  		lc.Append(cell.Hook{
    27  			OnStart: func(cell.HookContext) error {
    28  				wg.Add(1)
    29  				go func() {
    30  					defer wg.Done()
    31  
    32  					backend, err := backendPromise.Await(ctx)
    33  					if err != nil {
    34  						// There's nothing we can actually do here. We are already shutting down
    35  						// (either user-requested or caused by the backend initialization failure).
    36  						return
    37  					}
    38  
    39  					Heartbeat(ctx, backend)
    40  				}()
    41  				return nil
    42  			},
    43  
    44  			OnStop: func(ctx cell.HookContext) error {
    45  				cancel()
    46  				wg.Wait()
    47  				return nil
    48  			},
    49  		})
    50  	}),
    51  )