Golang's Httpserver graceful reboot

Source: Internet
Author: User
Tags semaphore
This is a creation in Article, where the information may have evolved or changed.

Last year, when doing golangserver, the internal comparison of the headache is the online service release, a large number of users of the request will be re-linked at the time of release, in the then also think of n more methods, and finally fell on a GitHub project, One of Facebook's Golang projects, Grace, was a simple research test that could be used directly in the interior, a time that suddenly came to mind and wanted to study the project carefully.
In principle, this is a process:

    1) Release the new bin file to overwrite the old bin file    2) Send a semaphore that tells the running process to restart    3) after the running process receives the signal, the new bin file is started as a child process    4) New process accepts new requests and handles    5) The old process no longer accepts the request, but waits for the processing of the requested processing to complete, and automatically exits after the processing of the request has been processed (    6) The new process is adopted by the INIT process after the old process exits, but continues to serve.

So step by step, the key is to start from the beginning of the 2nd step, so we first look at the implementation of the 2nd step, this should be said to be very simple, send the semaphore to a process, using the KILL command, on Facebook This project sent a semaphore of 3: Sigint,sigterm, SIGUSR2, the first two signals received after the program will exit directly, the latter signal SIGUSR2 will perform the so-called graceful restart.
3rd, after the running process receives the SIGUSR2 signal, the new bin file is started as a child process. First directly on the code to see: Https://github.com/facebookgo/grace/blob/master/gracehttp/http.go

Func (a *app) Signalhandler (WG *sync. Waitgroup) {ch: = make (chan os. Signal, Signal. Notify (CH, syscall. SIGINT, Syscall. SIGTERM, Syscall. SIGUSR2) for {sig: = <-ch switch sig {case Syscall. SIGINT, Syscall. SIGTERM://This ensures a subsequent int/term would trigger standard go behaviour of//Terminatin G. Executing the standard go termination behavior, the program ends the signal. Stop (CH) a.term (WG) return case Syscall. SIGUSR2://Here begins graceful Restart err: = a.prestartprocess ()//This function is not implemented in the source code, just reserved a hook function, the user can register their own functions, you can Do some custom things before restarting.            In general, there is nothing to do, unless there is a special service environment or State preservation and so on, at least for now, our server has not encountered if err! = Nil {a.errors <-err  }//We only have return here if there's an error, otherwise the new process//would send us a term            When it's ready to trigger the actual shutdown. If _, Err: = A.net.startprocess ();                        Err! = Nil {//here begins the formal so-called graceful reboot    A.errors <-Err}}}} 

A.net.startprocess The process we'll look at the basic process:

Func (n *net) startprocess (int, error) {listeners, err: = N.activelisteners ()//Get current on the listening port, this block is also the focus, the following highlights if Err  ! = Nil {return 0, err}//Extract the FDS from the listeners. Extract the file descriptor from the listener port files: = Make ([]*os. File, Len (listeners)) for I, L: = range listeners {Files[i], err = L. (filer). File () if err! = Nil {return 0, err} defer files[i]. Close ()}//use of the original binary location.    This works with symlinks such that if//the file it points to have been changed we'll use the updated symlink. Gets the path to the executable bin file, or it can be link path, using the latest link paths as the argv0 to start the file path, err: = Exec. Lookpath (OS.  Args[0]) If err! = Nil {return 0, err}//Pass on the environment and replace the old count key with the    New one. Get Listen_fds Variable value var env []string for _, V: = Range os. Environ () {if!strings. Hasprefix (V, envcountkeyprefix) {env = append (env, v)}} env = Append (env, Fmt. Sprintf ("%s%d", Envcountkeyprefix, Len (listeners))) Allfiles: = Append ([]*os. File{os. Stdin, OS. Stdout, OS.    Stderr}, files ...) Here call a Golang the underlying process startup function, to specify that the above parameters to get started process, err: = OS. StartProcess (argv0, OS. Args, &os. procattr{DIR:ORIGINALWD, Env:env, Files:allfiles,}) if err! = Nil {return 0, E    RR}//Returns the new process ID. return process. Pid, nil}

The above is the process of starting a new process, and take over the listening port, the general situation is not allowed to repeat monitoring, so it is necessary to use a more special method, from the above code to read the listener port file descriptor, and the listener port file descriptor passed to the child process, Sub-process from this file descriptor to implement the port monitoring

There is also a more special place is the old interface how to shut down the problem, the shutdown must be received request processing completed before closing. To this end of the Facebook students opened another project Httpdown, inherited the original httpserver, but many of the various link state maintenance and processing, this part of the analysis behind.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.