github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/app/log/command/command.go (about)

     1  package command
     2  
     3  //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
     4  
     5  import (
     6  	"context"
     7  
     8  	grpc "google.golang.org/grpc"
     9  
    10  	core "github.com/v2fly/v2ray-core/v5"
    11  	"github.com/v2fly/v2ray-core/v5/app/log"
    12  	"github.com/v2fly/v2ray-core/v5/common"
    13  	cmlog "github.com/v2fly/v2ray-core/v5/common/log"
    14  )
    15  
    16  // LoggerServer is the implemention of LoggerService
    17  type LoggerServer struct {
    18  	V *core.Instance
    19  }
    20  
    21  // RestartLogger implements LoggerService.
    22  func (s *LoggerServer) RestartLogger(ctx context.Context, request *RestartLoggerRequest) (*RestartLoggerResponse, error) {
    23  	logger := s.V.GetFeature((*log.Instance)(nil))
    24  	if logger == nil {
    25  		return nil, newError("unable to get logger instance")
    26  	}
    27  	if err := logger.Close(); err != nil {
    28  		return nil, newError("failed to close logger").Base(err)
    29  	}
    30  	if err := logger.Start(); err != nil {
    31  		return nil, newError("failed to start logger").Base(err)
    32  	}
    33  	return &RestartLoggerResponse{}, nil
    34  }
    35  
    36  // FollowLog implements LoggerService.
    37  func (s *LoggerServer) FollowLog(_ *FollowLogRequest, stream LoggerService_FollowLogServer) error {
    38  	logger := s.V.GetFeature((*log.Instance)(nil))
    39  	if logger == nil {
    40  		return newError("unable to get logger instance")
    41  	}
    42  	follower, ok := logger.(cmlog.Follower)
    43  	if !ok {
    44  		return newError("logger not support following")
    45  	}
    46  	ctx, cancel := context.WithCancel(stream.Context())
    47  	defer cancel()
    48  	f := func(msg cmlog.Message) {
    49  		err := stream.Send(&FollowLogResponse{
    50  			Message: msg.String(),
    51  		})
    52  		if err != nil {
    53  			cancel()
    54  		}
    55  	}
    56  	follower.AddFollower(f)
    57  	defer follower.RemoveFollower(f)
    58  	<-ctx.Done()
    59  	return nil
    60  }
    61  
    62  func (s *LoggerServer) mustEmbedUnimplementedLoggerServiceServer() {}
    63  
    64  type service struct {
    65  	v *core.Instance
    66  }
    67  
    68  func (s *service) Register(server *grpc.Server) {
    69  	RegisterLoggerServiceServer(server, &LoggerServer{
    70  		V: s.v,
    71  	})
    72  }
    73  
    74  func init() {
    75  	common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
    76  		s := core.MustFromContext(ctx)
    77  		return &service{v: s}, nil
    78  	}))
    79  }