github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/client/cli/connect/init_command.go (about) 1 package connect 2 3 import ( 4 "context" 5 6 "github.com/spf13/cobra" 7 8 "github.com/telepresenceio/telepresence/v2/pkg/client/cli/ann" 9 "github.com/telepresenceio/telepresence/v2/pkg/client/cli/daemon" 10 "github.com/telepresenceio/telepresence/v2/pkg/client/cli/flags" 11 "github.com/telepresenceio/telepresence/v2/pkg/client/cli/global" 12 "github.com/telepresenceio/telepresence/v2/pkg/errcat" 13 ) 14 15 type cmdInitKey struct{} 16 17 func WithCommandInitializer(ctx context.Context, cmdInit func(cmd *cobra.Command) error) context.Context { 18 return context.WithValue(ctx, cmdInitKey{}, cmdInit) 19 } 20 21 func InitCommand(cmd *cobra.Command) (err error) { 22 cmdInit, ok := cmd.Context().Value(cmdInitKey{}).(func(cmd *cobra.Command) error) 23 if !ok { 24 panic("no registered command initializer") 25 } 26 return cmdInit(cmd) 27 } 28 29 func CommandInitializer(cmd *cobra.Command) (err error) { 30 ctx := cmd.Context() 31 as := cmd.Annotations 32 33 if v, ok := as[ann.Session]; ok { 34 as[ann.UserDaemon] = v 35 as[ann.VersionCheck] = ann.Required 36 } 37 if v := as[ann.UserDaemon]; v == ann.Optional || v == ann.Required { 38 if cr := daemon.GetRequest(ctx); cr == nil { 39 if ctx, err = daemon.WithDefaultRequest(ctx, cmd); err != nil { 40 return err 41 } 42 flags.DeprecationIfChanged(cmd, global.FlagDocker, "use telepresence connect to initiate the connection") 43 flags.DeprecationIfChanged(cmd, global.FlagContext, "use telepresence connect to initiate the connection") 44 } 45 if ctx, err = EnsureUserDaemon(ctx, v == ann.Required); err != nil { 46 if v == ann.Optional && (err == ErrNoUserDaemon || errcat.GetCategory(err) == errcat.Config) { 47 // This is OK, but further initialization is not possible 48 err = nil 49 } 50 return err 51 } 52 cmd.SetContext(ctx) 53 } else { 54 // The rest requires a user daemon 55 return nil 56 } 57 if as[ann.VersionCheck] == ann.Required { 58 if err = ensureDaemonVersion(ctx); err != nil { 59 return err 60 } 61 } 62 63 if v := as[ann.Session]; v == ann.Optional || v == ann.Required { 64 ctx, err = EnsureSession(ctx, cmd.UseLine(), v == ann.Required) 65 if err != nil { 66 return err 67 } 68 cmd.SetContext(ctx) 69 } 70 return nil 71 } 72 73 // Initializer ensures that the context is initialized with connection to the user daemon, and that 74 // the root daemon is running if necessary. 75 func Initializer(ctx context.Context) (context.Context, error) { 76 var err error 77 if cr := daemon.GetRequest(ctx); cr == nil { 78 cr = daemon.NewDefaultRequest() 79 ctx = daemon.WithRequest(ctx, cr) 80 } 81 if ctx, err = EnsureUserDaemon(ctx, true); err != nil { 82 return ctx, err 83 } 84 if err = ensureDaemonVersion(ctx); err != nil { 85 return ctx, err 86 } 87 return ctx, nil 88 }