endless.go 13.8 KB
Newer Older
E
eoLinker API Management 已提交
1
package endless
E
V2.1.0  
eoLinker API Management 已提交
2 3 4 5 6

import (
	"crypto/tls"
	"errors"
	"fmt"
黄孟柱 已提交
7 8
	log "github.com/eolinker/goku-api-gateway/goku-log"
	cmd2 "github.com/eolinker/goku-api-gateway/goku-node/cmd"
E
eoLinker API Management 已提交
9

E
V2.1.0  
eoLinker API Management 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22
	"net"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"runtime"
	"strings"
	"sync"
	"syscall"
	"time"
)

const (
Y
Your Name 已提交
23
	//PRE_SIGNAL pre signal
E
V2.1.0  
eoLinker API Management 已提交
24
	PRE_SIGNAL = iota
Y
Your Name 已提交
25 26

	//POST_SIGNAL post signal
E
V2.1.0  
eoLinker API Management 已提交
27 28
	POST_SIGNAL

Y
Your Name 已提交
29
	//STATE_INIT state init
E
V2.1.0  
eoLinker API Management 已提交
30
	STATE_INIT
Y
Your Name 已提交
31
	//STATE_RUNNING state running
E
V2.1.0  
eoLinker API Management 已提交
32
	STATE_RUNNING
Y
Your Name 已提交
33
	//STATE_SHUTTING_DOWN state shutting down
E
V2.1.0  
eoLinker API Management 已提交
34
	STATE_SHUTTING_DOWN
Y
Your Name 已提交
35
	//STATE_TERMINATE state terminate
E
V2.1.0  
eoLinker API Management 已提交
36 37 38 39 40 41 42 43 44 45
	STATE_TERMINATE
)

var (
	runningServerReg     sync.RWMutex
	runningServers       map[string]*endlessServer
	runningServersOrder  []string
	socketPtrOffsetMap   map[string]uint
	runningServersForked bool

Y
Your Name 已提交
46 47 48 49 50
	//DefaultReadTimeOut 默认读超时时间
	DefaultReadTimeOut time.Duration
	//DefaultWriteTimeOut 默认写超时时间
	DefaultWriteTimeOut time.Duration
	//DefaultMaxHeaderBytes 默认请求头最大字节数
E
V2.1.0  
eoLinker API Management 已提交
51
	DefaultMaxHeaderBytes int
Y
Your Name 已提交
52 53
	//DefaultHammerTime default hammer time
	DefaultHammerTime time.Duration
E
V2.1.0  
eoLinker API Management 已提交
54 55 56 57 58 59 60

	isChild     bool
	socketOrder string

	hookableSignals []os.Signal
)

Y
Your Name 已提交
61
var isStop = true
E
eoLinker API Management 已提交
62

E
V2.1.0  
eoLinker API Management 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
func init() {
	runningServerReg = sync.RWMutex{}
	runningServers = make(map[string]*endlessServer)
	runningServersOrder = []string{}
	socketPtrOffsetMap = make(map[string]uint)

	DefaultMaxHeaderBytes = 0 // use http.DefaultMaxHeaderBytes - which currently is 1 << 20 (1MB)

	// after a restart the parent will finish ongoing requests before
	// shutting down. set to a negative value to disable
	DefaultHammerTime = 60 * time.Second

	hookableSignals = []os.Signal{
		syscall.SIGHUP,
		syscall.SIGUSR1,
		syscall.SIGUSR2,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGTSTP,
	}
}

type endlessServer struct {
	http.Server
	EndlessListener  net.Listener
	SignalHooks      map[int]map[os.Signal][]func()
	tlsInnerListener *endlessListener
	wg               sync.WaitGroup
	sigChan          chan os.Signal
	isChild          bool
	state            uint8
	lock             *sync.RWMutex
	BeforeBegin      func(add string)
}

/*
NewServer returns an intialized endlessServer Object. Calling Serve on it will
actually "start" the server.
*/
func NewServer(addr string, handler http.Handler) (srv *endlessServer) {
	runningServerReg.Lock()
	defer runningServerReg.Unlock()

	socketOrder = os.Getenv("ENDLESS_SOCKET_ORDER")
	isChild = os.Getenv("ENDLESS_CONTINUE") != ""

	if len(socketOrder) > 0 {
		for i, addr := range strings.Split(socketOrder, ",") {
E
eoLinker API Management 已提交
111

E
V2.1.0  
eoLinker API Management 已提交
112 113 114
			socketPtrOffsetMap[addr] = uint(i)
		}
	} else {
E
eoLinker API Management 已提交
115

E
V2.1.0  
eoLinker API Management 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
		socketPtrOffsetMap[addr] = uint(len(runningServersOrder))
	}

	srv = &endlessServer{
		wg:      sync.WaitGroup{},
		sigChan: make(chan os.Signal),
		isChild: isChild,
		SignalHooks: map[int]map[os.Signal][]func(){
			PRE_SIGNAL: map[os.Signal][]func(){
				syscall.SIGHUP:  []func(){},
				syscall.SIGUSR1: []func(){},
				syscall.SIGUSR2: []func(){},
				syscall.SIGINT:  []func(){},
				syscall.SIGTERM: []func(){},
				syscall.SIGTSTP: []func(){},
			},
			POST_SIGNAL: map[os.Signal][]func(){
				syscall.SIGHUP:  []func(){},
				syscall.SIGUSR1: []func(){},
				syscall.SIGUSR2: []func(){},
				syscall.SIGINT:  []func(){},
				syscall.SIGTERM: []func(){},
				syscall.SIGTSTP: []func(){},
			},
		},
		state: STATE_INIT,
		lock:  &sync.RWMutex{},
	}
	srv.Server.Addr = addr
	srv.Server.ReadTimeout = DefaultReadTimeOut
	srv.Server.WriteTimeout = DefaultWriteTimeOut
	srv.Server.MaxHeaderBytes = DefaultMaxHeaderBytes
	srv.Server.Handler = handler

	srv.BeforeBegin = func(addr string) {
Y
Your Name 已提交
151
		log.Info("start service:", syscall.Getpid(), addr)
E
V2.1.0  
eoLinker API Management 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	}

	runningServersOrder = append(runningServersOrder, addr)
	runningServers[addr] = srv

	return
}

/*
ListenAndServe listens on the TCP network address addr and then calls Serve
with handler to handle requests on incoming connections. Handler is typically
nil, in which case the DefaultServeMux is used.
*/
func ListenAndServe(addr string, handler http.Handler) error {
	server := NewServer(addr, handler)
	return server.ListenAndServe()
}

/*
ListenAndServeTLS acts identically to ListenAndServe, except that it expects
HTTPS connections. Additionally, files containing a certificate and matching
private key for the server must be provided. If the certificate is signed by a
certificate authority, the certFile should be the concatenation of the server's
certificate followed by the CA's certificate.
*/
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler http.Handler) error {
	server := NewServer(addr, handler)
	return server.ListenAndServeTLS(certFile, keyFile)
}

func (srv *endlessServer) getState() uint8 {
	srv.lock.RLock()
	defer srv.lock.RUnlock()

	return srv.state
}

func (srv *endlessServer) setState(st uint8) {
	srv.lock.Lock()
	defer srv.lock.Unlock()

	srv.state = st
}

/*
Serve accepts incoming HTTP connections on the listener l, creating a new
service goroutine for each. The service goroutines read requests and then call
handler to reply to them. Handler is typically nil, in which case the
DefaultServeMux is used.

In addition to the stl Serve behaviour each connection is added to a
sync.Waitgroup so that all outstanding connections can be served before shutting
down the server.
*/
func (srv *endlessServer) Serve() (err error) {
E
eoLinker API Management 已提交
207
	defer log.Info(syscall.Getpid(), "Serve() returning...")
E
V2.1.0  
eoLinker API Management 已提交
208 209
	srv.setState(STATE_RUNNING)
	err = srv.Server.Serve(srv.EndlessListener)
E
eoLinker API Management 已提交
210
	log.Info(syscall.Getpid(), "Waiting for connections to finish...")
E
V2.1.0  
eoLinker API Management 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
	srv.wg.Wait()
	srv.setState(STATE_TERMINATE)
	return
}

/*
ListenAndServe listens on the TCP network address srv.Addr and then calls Serve
to handle requests on incoming connections. If srv.Addr is blank, ":http" is
used.
*/
func (srv *endlessServer) ListenAndServe() (err error) {
	addr := srv.Addr
	if addr == "" {
		addr = ":http"
	}

	go srv.handleSignals()

	l, err := srv.getListener(addr)
	if err != nil {
E
eoLinker API Management 已提交
231
		return err
E
V2.1.0  
eoLinker API Management 已提交
232
	}
E
eoLinker API Management 已提交
233

E
V2.1.0  
eoLinker API Management 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
	srv.EndlessListener = newEndlessListener(l, srv)

	if srv.isChild {
		syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
	}

	srv.BeforeBegin(srv.Addr)

	return srv.Serve()
}

/*
ListenAndServeTLS listens on the TCP network address srv.Addr and then calls
Serve to handle requests on incoming TLS connections.

Filenames containing a certificate and matching private key for the server must
be provided. If the certificate is signed by a certificate authority, the
certFile should be the concatenation of the server's certificate followed by the
CA's certificate.

If srv.Addr is blank, ":https" is used.
*/
func (srv *endlessServer) ListenAndServeTLS(certFile, keyFile string) (err error) {
	addr := srv.Addr
	if addr == "" {
		addr = ":https"
	}

	config := &tls.Config{}
	if srv.TLSConfig != nil {
		*config = *srv.TLSConfig
	}
	if config.NextProtos == nil {
		config.NextProtos = []string{"http/1.1"}
	}

	config.Certificates = make([]tls.Certificate, 1)
	config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return
	}

	go srv.handleSignals()

	l, err := srv.getListener(addr)
	if err != nil {
E
eoLinker API Management 已提交
280
		log.Info(err)
E
V2.1.0  
eoLinker API Management 已提交
281 282
		return
	}
E
eoLinker API Management 已提交
283

E
V2.1.0  
eoLinker API Management 已提交
284 285 286 287 288 289 290
	srv.tlsInnerListener = newEndlessListener(l, srv)
	srv.EndlessListener = tls.NewListener(srv.tlsInnerListener, config)

	if srv.isChild {
		syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
	}

E
eoLinker API Management 已提交
291
	log.Info(syscall.Getpid(), srv.Addr)
E
V2.1.0  
eoLinker API Management 已提交
292 293 294 295 296 297 298 299 300 301
	return srv.Serve()
}

func (srv *endlessServer) getListener(laddr string) (l net.Listener, err error) {
	if srv.isChild {
		var ptrOffset uint = 0
		runningServerReg.RLock()
		defer runningServerReg.RUnlock()
		if len(socketPtrOffsetMap) > 0 {
			ptrOffset = socketPtrOffsetMap[laddr]
E
eoLinker API Management 已提交
302
			log.Info("laddr", laddr, "ptr offset", socketPtrOffsetMap[laddr])
E
V2.1.0  
eoLinker API Management 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
		}

		f := os.NewFile(uintptr(3+ptrOffset), "")
		l, err = net.FileListener(f)
		if err != nil {
			err = fmt.Errorf("net.FileListener error: %v", err)
			return
		}
	} else {
		l, err = net.Listen("tcp", laddr)
		if err != nil {
			err = fmt.Errorf("net.Listen error: %v", err)
			return
		}
	}
	return
}

/*
handleSignals listens for os Signals and calls any hooked in function that the
user had registered with the signal.
*/
func (srv *endlessServer) handleSignals() {
	var sig os.Signal

	signal.Notify(
		srv.sigChan,
		hookableSignals...,
	)

	pid := syscall.Getpid()
	for {
		sig = <-srv.sigChan
		srv.signalHooks(PRE_SIGNAL, sig)
		switch sig {
		case syscall.SIGHUP:
E
eoLinker API Management 已提交
339
			log.Info(pid, "Received SIGHUP. forking.")
E
V2.1.0  
eoLinker API Management 已提交
340 341
			err := srv.fork()
			if err != nil {
E
eoLinker API Management 已提交
342
				log.Info("Fork err:", err)
E
V2.1.0  
eoLinker API Management 已提交
343
			}
E
eoLinker API Management 已提交
344
			isStop = false
E
V2.1.0  
eoLinker API Management 已提交
345
		case syscall.SIGUSR1:
E
eoLinker API Management 已提交
346
			log.Info(pid, "Received SIGUSR1.")
E
V2.1.0  
eoLinker API Management 已提交
347
		case syscall.SIGUSR2:
E
eoLinker API Management 已提交
348
			log.Info(pid, "Received SIGUSR2.")
E
V2.1.0  
eoLinker API Management 已提交
349 350
			srv.hammerTime(0 * time.Second)
		case syscall.SIGINT:
E
eoLinker API Management 已提交
351
			log.Info(pid, "Received SIGINT.")
E
V2.1.0  
eoLinker API Management 已提交
352 353
			srv.shutdown()
		case syscall.SIGTERM:
E
eoLinker API Management 已提交
354
			log.Info(pid, "Received SIGTERM.")
E
V2.1.0  
eoLinker API Management 已提交
355 356
			srv.shutdown()
		case syscall.SIGTSTP:
E
eoLinker API Management 已提交
357
			log.Info(pid, "Received SIGTSTP.")
E
V2.1.0  
eoLinker API Management 已提交
358
		default:
E
eoLinker API Management 已提交
359
			log.Infof("Received %v: nothing i care about...\n", sig)
E
V2.1.0  
eoLinker API Management 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
		}
		srv.signalHooks(POST_SIGNAL, sig)
	}
}

func (srv *endlessServer) signalHooks(ppFlag int, sig os.Signal) {
	if _, notSet := srv.SignalHooks[ppFlag][sig]; !notSet {
		return
	}
	for _, f := range srv.SignalHooks[ppFlag][sig] {
		f()
	}
	return
}

/*
shutdown closes the listener so that no new connections are accepted. it also
starts a goroutine that will hammer (stop all running requests) the server
after DefaultHammerTime.
*/
func (srv *endlessServer) shutdown() {
E
eoLinker API Management 已提交
381

E
V2.1.0  
eoLinker API Management 已提交
382 383 384 385 386 387 388 389 390 391 392 393
	if srv.getState() != STATE_RUNNING {
		return
	}

	srv.setState(STATE_SHUTTING_DOWN)
	if DefaultHammerTime >= 0 {
		go srv.hammerTime(DefaultHammerTime)
	}
	// disable keep-alives on existing connections
	srv.SetKeepAlivesEnabled(false)
	err := srv.EndlessListener.Close()
	if err != nil {
E
eoLinker API Management 已提交
394
		log.Info(syscall.Getpid(), "Listener.Close() error:", err)
E
V2.1.0  
eoLinker API Management 已提交
395
	} else {
E
eoLinker API Management 已提交
396
		log.Info(syscall.Getpid(), srv.EndlessListener.Addr(), "Listener closed.")
E
V2.1.0  
eoLinker API Management 已提交
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
	}
}

/*
hammerTime forces the server to shutdown in a given timeout - whether it
finished outstanding requests or not. if Read/WriteTimeout are not set or the
max header size is very big a connection could hang...

srv.Serve() will not return until all connections are served. this will
unblock the srv.wg.Wait() in Serve() thus causing ListenAndServe(TLS) to
return.
*/
func (srv *endlessServer) hammerTime(d time.Duration) {
	defer func() {
		// we are calling srv.wg.Done() until it panics which means we called
		// Done() when the counter was already at 0 and we're done.
		// (and thus Serve() will return and the parent will exit)
		if r := recover(); r != nil {
E
eoLinker API Management 已提交
415
			log.Info("WaitGroup at 0", r)
E
V2.1.0  
eoLinker API Management 已提交
416 417 418 419 420 421
		}
	}()
	if srv.getState() != STATE_SHUTTING_DOWN {
		return
	}
	time.Sleep(d)
E
eoLinker API Management 已提交
422
	log.Info("[STOP - Hammer Time] Forcefully shutting down parent")
E
V2.1.0  
eoLinker API Management 已提交
423 424 425 426 427 428 429 430 431 432
	for {
		if srv.getState() == STATE_TERMINATE {
			break
		}
		srv.wg.Done()
		runtime.Gosched()
	}
}

func (srv *endlessServer) fork() (err error) {
E
eoLinker API Management 已提交
433 434

	cmd2.StopNode()
E
V2.1.0  
eoLinker API Management 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
	runningServerReg.Lock()
	defer runningServerReg.Unlock()
	// only one server instance should fork!
	if runningServersForked {
		return errors.New("Another process already forked. Ignoring this one.")
	}

	runningServersForked = true

	var files = make([]*os.File, len(runningServers))
	var orderArgs = make([]string, len(runningServers))
	// get the accessor socket fds for _all_ server instances
	for _, srvPtr := range runningServers {
		// introspect.PrintTypeDump(srvPtr.EndlessListener)
		switch srvPtr.EndlessListener.(type) {
		case *endlessListener:
			// normal listener
			files[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.EndlessListener.(*endlessListener).File()
		default:
			// tls listener
			files[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.tlsInnerListener.File()
		}
		orderArgs[socketPtrOffsetMap[srvPtr.Server.Addr]] = srvPtr.Server.Addr
	}

	env := append(
		os.Environ(),
		"ENDLESS_CONTINUE=1",
	)
	if len(runningServers) > 1 {
		env = append(env, fmt.Sprintf(`ENDLESS_SOCKET_ORDER=%s`, strings.Join(orderArgs, ",")))
	}

E
eoLinker API Management 已提交
468
	// log.Info(files)
E
V2.1.0  
eoLinker API Management 已提交
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
	path := os.Args[0]
	var args []string
	if len(os.Args) > 1 {
		args = os.Args[1:]
	}

	cmd := exec.Command(path, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.ExtraFiles = files
	cmd.Env = env

	// cmd.SysProcAttr = &syscall.SysProcAttr{
	// 	Setsid:  true,
	// 	Setctty: true,
	// 	Ctty:    ,
	// }

	err = cmd.Start()
	if err != nil {
		log.Fatalf("Restart: Failed to launch, error: %v", err)
	}

	return
}

type endlessListener struct {
	net.Listener
	stopped bool
	server  *endlessServer
}

func (el *endlessListener) Accept() (c net.Conn, err error) {
	tc, err := el.Listener.(*net.TCPListener).AcceptTCP()
	if err != nil {
		return
	}

	tc.SetKeepAlive(true)                  // see http.tcpKeepAliveListener
	tc.SetKeepAlivePeriod(3 * time.Minute) // see http.tcpKeepAliveListener

	c = endlessConn{
		Conn:   tc,
		server: el.server,
	}

	el.server.wg.Add(1)
	return
}

func newEndlessListener(l net.Listener, srv *endlessServer) (el *endlessListener) {
	el = &endlessListener{
		Listener: l,
		server:   srv,
	}

	return
}

func (el *endlessListener) Close() error {
	if el.stopped {
		return syscall.EINVAL
	}

	el.stopped = true
	return el.Listener.Close()
}

func (el *endlessListener) File() *os.File {
	// returns a dup(2) - FD_CLOEXEC flag *not* set
	tl := el.Listener.(*net.TCPListener)
	fl, _ := tl.File()
	return fl
}

type endlessConn struct {
	net.Conn
	server *endlessServer
}

func (w endlessConn) Close() error {
	err := w.Conn.Close()
	if err == nil {
		w.server.wg.Done()
	}
	return err
}

/*
RegisterSignalHook registers a function to be run PRE_SIGNAL or POST_SIGNAL for
a given signal. PRE or POST in this case means before or after the signal
related code endless itself runs
*/
func (srv *endlessServer) RegisterSignalHook(prePost int, sig os.Signal, f func()) (err error) {
	if prePost != PRE_SIGNAL && prePost != POST_SIGNAL {
		err = fmt.Errorf("Cannot use %v for prePost arg. Must be endless.PRE_SIGNAL or endless.POST_SIGNAL.", sig)
		return
	}
	for _, s := range hookableSignals {
		if s == sig {
			srv.SignalHooks[prePost][sig] = append(srv.SignalHooks[prePost][sig], f)
			return
		}
	}
	err = fmt.Errorf("Signal %v is not supported.", sig)
	return
}