github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/cluster/clusterproviders/k8s/k8s_cluster_monitor.go (about)

     1  package k8s
     2  
     3  import (
     4  	"log/slog"
     5  	"time"
     6  
     7  	"github.com/asynkron/protoactor-go/actor"
     8  	"github.com/asynkron/protoactor-go/scheduler"
     9  )
    10  
    11  type k8sClusterMonitorActor struct {
    12  	*Provider
    13  	actor.Behavior
    14  
    15  	refreshCanceller scheduler.CancelFunc
    16  }
    17  
    18  func (kcm *k8sClusterMonitorActor) Receive(ctx actor.Context) { kcm.Behavior.Receive(ctx) }
    19  
    20  func (kcm *k8sClusterMonitorActor) init(ctx actor.Context) {
    21  	switch r := ctx.Message().(type) {
    22  	case *RegisterMember:
    23  		// make sure timeout is set to some meaningful value
    24  		timeout := getTimeout(ctx, kcm)
    25  
    26  		if err := kcm.registerMember(timeout); err != nil {
    27  			ctx.Logger().Error("Failed to register service to k8s, will retry", slog.Any("error", err))
    28  			ctx.Send(ctx.Self(), r)
    29  			return
    30  		}
    31  		ctx.Logger().Info("Registered service to k8s")
    32  	case *DeregisterMember:
    33  		ctx.Logger().Debug("Deregistering service from k8s")
    34  		timeout := getTimeout(ctx, kcm)
    35  
    36  		if err := kcm.deregisterMember(timeout); err != nil {
    37  			ctx.Logger().Error("Failed to deregister service from k8s, proceeding with shutdown", slog.Any("error", err))
    38  		} else {
    39  			ctx.Logger().Info("Deregistered service from k8s")
    40  		}
    41  		ctx.Respond(&DeregisterMemberResponse{})
    42  	case *StartWatchingCluster:
    43  		if err := kcm.startWatchingCluster(); err != nil {
    44  			ctx.Logger().Error("Failed to start watching k8s cluster, will retry", slog.Any("error", err))
    45  			ctx.Send(ctx.Self(), r)
    46  			return
    47  		}
    48  		ctx.Logger().Info("k8s cluster started to being watched")
    49  	case *StopWatchingCluster:
    50  		if kcm.cancelWatch != nil {
    51  			kcm.cancelWatch()
    52  		}
    53  		ctx.Respond(&StopWatchingClusterResponse{})
    54  	}
    55  }
    56  
    57  func getTimeout(ctx actor.Context, kcm *k8sClusterMonitorActor) time.Duration {
    58  	timeout := ctx.ReceiveTimeout()
    59  	if timeout.Microseconds() == 0 {
    60  		timeout = kcm.Provider.cluster.Config.RequestTimeoutTime
    61  		if timeout.Microseconds() == 0 {
    62  			timeout = time.Second * 5 // default to 5 seconds
    63  		}
    64  	}
    65  
    66  	return timeout
    67  }
    68  
    69  // creates and initializes a new k8sClusterMonitorActor in the heap and
    70  // returns a reference to its memory address
    71  func newClusterMonitor(provider *Provider) actor.Actor {
    72  	kcm := k8sClusterMonitorActor{
    73  		Behavior: actor.NewBehavior(),
    74  		Provider: provider,
    75  	}
    76  	kcm.Become(kcm.init)
    77  	return &kcm
    78  }