github.com/cloudwego/kitex@v0.9.0/pkg/remote/remotesvr/server.go (about) 1 /* 2 * Copyright 2021 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package remotesvr 18 19 import ( 20 "context" 21 "net" 22 "sync" 23 24 "github.com/cloudwego/kitex/pkg/endpoint" 25 "github.com/cloudwego/kitex/pkg/gofunc" 26 "github.com/cloudwego/kitex/pkg/klog" 27 "github.com/cloudwego/kitex/pkg/remote" 28 ) 29 30 // Server is the interface for remote server. 31 type Server interface { 32 Start() chan error 33 Stop() error 34 Address() net.Addr 35 } 36 37 type server struct { 38 opt *remote.ServerOption 39 listener net.Listener 40 transSvr remote.TransServer 41 42 inkHdlFunc endpoint.Endpoint 43 sync.Mutex 44 } 45 46 // NewServer creates a remote server. 47 func NewServer(opt *remote.ServerOption, inkHdlFunc endpoint.Endpoint, transHdlr remote.ServerTransHandler) (Server, error) { 48 transSvr := opt.TransServerFactory.NewTransServer(opt, transHdlr) 49 s := &server{ 50 opt: opt, 51 inkHdlFunc: inkHdlFunc, 52 transSvr: transSvr, 53 } 54 return s, nil 55 } 56 57 // Start starts the server and return chan, the chan receive means server shutdown or err happen 58 func (s *server) Start() chan error { 59 errCh := make(chan error, 1) 60 ln, err := s.buildListener() 61 if err != nil { 62 errCh <- err 63 return errCh 64 } 65 66 s.Lock() 67 s.listener = ln 68 s.Unlock() 69 70 gofunc.GoFunc(context.Background(), func() { errCh <- s.transSvr.BootstrapServer(ln) }) 71 return errCh 72 } 73 74 func (s *server) buildListener() (ln net.Listener, err error) { 75 if s.opt.Listener != nil { 76 klog.Infof("KITEX: server listen at addr=%s", s.opt.Listener.Addr().String()) 77 return s.opt.Listener, nil 78 } 79 addr := s.opt.Address 80 if ln, err = s.transSvr.CreateListener(addr); err != nil { 81 klog.Errorf("KITEX: server listen failed, addr=%s error=%s", addr.String(), err) 82 } else { 83 klog.Infof("KITEX: server listen at addr=%s", ln.Addr().String()) 84 } 85 return 86 } 87 88 // Stop stops the server gracefully. 89 func (s *server) Stop() (err error) { 90 s.Lock() 91 defer s.Unlock() 92 if s.transSvr != nil { 93 err = s.transSvr.Shutdown() 94 s.listener = nil 95 } 96 return 97 } 98 99 func (s *server) Address() net.Addr { 100 if s.listener != nil { 101 return s.listener.Addr() 102 } 103 return nil 104 }