endless.go 13.9 KB
Newer Older
E
eoLinker API Management 已提交
1
package endless
E
V2.1.0  
eoLinker API Management 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

import (
	"crypto/tls"
	"errors"
	"fmt"
	"net"
	"net/http"
	"os"
	"os/exec"
	"os/signal"
	"runtime"
	"strings"
	"sync"
	"syscall"
	"time"
Y
Your Name 已提交
17 18

	log "github.com/eolinker/goku-api-gateway/goku-log"
E
V2.1.0  
eoLinker API Management 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
)

const (
	PRE_SIGNAL = iota
	POST_SIGNAL

	STATE_INIT
	STATE_RUNNING
	STATE_SHUTTING_DOWN
	STATE_TERMINATE
)

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

Y
Your Name 已提交
38 39
	DefaultReadTimeOut    time.Duration
	DefaultWriteTimeOut   time.Duration
E
V2.1.0  
eoLinker API Management 已提交
40
	DefaultMaxHeaderBytes int
Y
Your Name 已提交
41
	DefaultHammerTime     time.Duration
E
V2.1.0  
eoLinker API Management 已提交
42

Y
Your Name 已提交
43 44 45 46
	isChild         bool
	socketOrder     string
	adminServer     *endlessServer
	nodeServer      *endlessServer
E
V2.1.0  
eoLinker API Management 已提交
47 48 49
	hookableSignals []os.Signal
)

Y
Your Name 已提交
50
var isStop bool = true
E
eoLinker API Management 已提交
51

E
V2.1.0  
eoLinker API Management 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
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
Y
Your Name 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
	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)
	runningServersForked bool
}

func SetAdminServer(server *endlessServer) {
	adminServer = server
}

func SetNodeServer(server *endlessServer) {
	nodeServer = server
E
V2.1.0  
eoLinker API Management 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
}

/*
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 已提交
109

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

E
V2.1.0  
eoLinker API Management 已提交
114 115 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
		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 已提交
149
		log.Info("start service:", syscall.Getpid(), addr)
E
V2.1.0  
eoLinker API Management 已提交
150 151 152 153 154 155 156
	}

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

Y
Your Name 已提交
157 158 159 160 161 162 163 164 165
func RestartServer() {
	nodeServer.sigChan <- syscall.SIGHUP
}

func StopServer() {
	nodeServer.sigChan <- syscall.SIGTERM
}

/*F
E
V2.1.0  
eoLinker API Management 已提交
166 167 168 169 170 171
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)
Y
Your Name 已提交
172
	nodeServer = server
E
V2.1.0  
eoLinker API Management 已提交
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 207 208 209 210 211 212
	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 已提交
213
	defer log.Info(syscall.Getpid(), "Serve() returning...")
E
V2.1.0  
eoLinker API Management 已提交
214 215
	srv.setState(STATE_RUNNING)
	err = srv.Server.Serve(srv.EndlessListener)
E
eoLinker API Management 已提交
216
	log.Info(syscall.Getpid(), "Waiting for connections to finish...")
E
V2.1.0  
eoLinker API Management 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	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 已提交
237
		return err
E
V2.1.0  
eoLinker API Management 已提交
238
	}
E
eoLinker API Management 已提交
239

E
V2.1.0  
eoLinker API Management 已提交
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 280 281 282 283 284 285
	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 已提交
286
		log.Info(err)
E
V2.1.0  
eoLinker API Management 已提交
287 288
		return
	}
E
eoLinker API Management 已提交
289

E
V2.1.0  
eoLinker API Management 已提交
290 291 292 293 294 295 296
	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 已提交
297
	log.Info(syscall.Getpid(), srv.Addr)
E
V2.1.0  
eoLinker API Management 已提交
298 299 300 301 302 303 304 305 306 307
	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 已提交
308
			log.Info("laddr", laddr, "ptr offset", socketPtrOffsetMap[laddr])
E
V2.1.0  
eoLinker API Management 已提交
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 339 340 341 342 343 344
		}

		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 已提交
345
			log.Info(pid, "Received SIGHUP. forking.")
E
V2.1.0  
eoLinker API Management 已提交
346 347
			err := srv.fork()
			if err != nil {
E
eoLinker API Management 已提交
348
				log.Info("Fork err:", err)
E
V2.1.0  
eoLinker API Management 已提交
349
			}
E
eoLinker API Management 已提交
350
			isStop = false
E
V2.1.0  
eoLinker API Management 已提交
351
		case syscall.SIGUSR1:
E
eoLinker API Management 已提交
352
			log.Info(pid, "Received SIGUSR1.")
E
V2.1.0  
eoLinker API Management 已提交
353
		case syscall.SIGUSR2:
E
eoLinker API Management 已提交
354
			log.Info(pid, "Received SIGUSR2.")
E
V2.1.0  
eoLinker API Management 已提交
355 356
			srv.hammerTime(0 * time.Second)
		case syscall.SIGINT:
E
eoLinker API Management 已提交
357
			log.Info(pid, "Received SIGINT.")
E
V2.1.0  
eoLinker API Management 已提交
358 359
			srv.shutdown()
		case syscall.SIGTERM:
Y
Your Name 已提交
360
			log.Info(``, "Received SIGTERM.")
E
V2.1.0  
eoLinker API Management 已提交
361 362
			srv.shutdown()
		case syscall.SIGTSTP:
E
eoLinker API Management 已提交
363
			log.Info(pid, "Received SIGTSTP.")
E
V2.1.0  
eoLinker API Management 已提交
364
		default:
E
eoLinker API Management 已提交
365
			log.Infof("Received %v: nothing i care about...\n", sig)
E
V2.1.0  
eoLinker API Management 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
		}
		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 已提交
387

E
V2.1.0  
eoLinker API Management 已提交
388 389 390 391 392 393 394 395 396 397 398 399
	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 已提交
400
		log.Info(syscall.Getpid(), "Listener.Close() error:", err)
E
V2.1.0  
eoLinker API Management 已提交
401
	} else {
E
eoLinker API Management 已提交
402
		log.Info(syscall.Getpid(), srv.EndlessListener.Addr(), "Listener closed.")
E
V2.1.0  
eoLinker API Management 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	}
}

/*
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 已提交
421
			log.Info("WaitGroup at 0", r)
E
V2.1.0  
eoLinker API Management 已提交
422 423 424 425 426 427
		}
	}()
	if srv.getState() != STATE_SHUTTING_DOWN {
		return
	}
	time.Sleep(d)
E
eoLinker API Management 已提交
428
	log.Info("[STOP - Hammer Time] Forcefully shutting down parent")
E
V2.1.0  
eoLinker API Management 已提交
429 430 431 432 433 434 435 436 437 438
	for {
		if srv.getState() == STATE_TERMINATE {
			break
		}
		srv.wg.Done()
		runtime.Gosched()
	}
}

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

E
V2.1.0  
eoLinker API Management 已提交
440 441
	runningServerReg.Lock()
	defer runningServerReg.Unlock()
Y
Your Name 已提交
442
	log.Info(1234)
E
V2.1.0  
eoLinker API Management 已提交
443
	// only one server instance should fork!
Y
Your Name 已提交
444
	if srv.runningServersForked {
E
V2.1.0  
eoLinker API Management 已提交
445 446
		return errors.New("Another process already forked. Ignoring this one.")
	}
Y
Your Name 已提交
447 448
	log.Info(5456)
	srv.runningServersForked = true
E
V2.1.0  
eoLinker API Management 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

	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
	}
Y
Your Name 已提交
465
	log.Info(123)
E
V2.1.0  
eoLinker API Management 已提交
466 467 468 469 470 471 472 473
	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 已提交
474
	// log.Info(files)
E
V2.1.0  
eoLinker API Management 已提交
475 476 477 478 479
	path := os.Args[0]
	var args []string
	if len(os.Args) > 1 {
		args = os.Args[1:]
	}
Y
Your Name 已提交
480
	log.Info(path, args)
E
V2.1.0  
eoLinker API Management 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
	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)
	}

Y
Your Name 已提交
498
	srv.runningServersForked = false
E
V2.1.0  
eoLinker API Management 已提交
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 576 577 578 579 580 581 582
	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
}