github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/app/instman/instman.go (about) 1 package instman 2 3 import ( 4 "context" 5 6 core "github.com/v2fly/v2ray-core/v5" 7 "github.com/v2fly/v2ray-core/v5/common" 8 "github.com/v2fly/v2ray-core/v5/features/extension" 9 ) 10 11 //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen 12 13 type InstanceMgr struct { 14 config *Config // nolint: structcheck 15 instances map[string]*core.Instance 16 } 17 18 func (i InstanceMgr) Type() interface{} { 19 return extension.InstanceManagementType() 20 } 21 22 func (i InstanceMgr) Start() error { 23 return nil 24 } 25 26 func (i InstanceMgr) Close() error { 27 return nil 28 } 29 30 func (i InstanceMgr) ListInstance(ctx context.Context) ([]string, error) { 31 var instanceNames []string 32 for k := range i.instances { 33 instanceNames = append(instanceNames, k) 34 } 35 return instanceNames, nil 36 } 37 38 func (i InstanceMgr) AddInstance(ctx context.Context, name string, config []byte, configType string) error { 39 coreConfig, err := core.LoadConfig(configType, config) 40 if err != nil { 41 return newError("unable to load config").Base(err) 42 } 43 instance, err := core.New(coreConfig) 44 if err != nil { 45 return newError("unable to create instance").Base(err) 46 } 47 i.instances[name] = instance 48 return nil 49 } 50 51 func (i InstanceMgr) StartInstance(ctx context.Context, name string) error { 52 err := i.instances[name].Start() 53 if err != nil { 54 return newError("failed to start instance").Base(err) 55 } 56 return nil 57 } 58 59 func (i InstanceMgr) StopInstance(ctx context.Context, name string) error { 60 err := i.instances[name].Close() 61 if err != nil { 62 return newError("failed to stop instance").Base(err) 63 } 64 return nil 65 } 66 67 func (i InstanceMgr) UntrackInstance(ctx context.Context, name string) error { 68 delete(i.instances, name) 69 return nil 70 } 71 72 func NewInstanceMgr(ctx context.Context, config *Config) (extension.InstanceManagement, error) { 73 return InstanceMgr{instances: map[string]*core.Instance{}}, nil 74 } 75 76 func init() { 77 common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 78 var f extension.InstanceManagement 79 var err error 80 if f, err = NewInstanceMgr(ctx, config.(*Config)); err != nil { 81 return nil, err 82 } 83 return f, nil 84 })) 85 }