instman.go 2.1 KB

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