vitess.io/vitess@v0.16.2/go/vt/servenv/run.go (about)

     1  /*
     2  Copyright 2019 The Vitess 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 servenv
    18  
    19  import (
    20  	"fmt"
    21  	"net"
    22  	"net/http"
    23  	"net/url"
    24  	"os"
    25  	"os/signal"
    26  	"syscall"
    27  	"time"
    28  
    29  	"vitess.io/vitess/go/event"
    30  	"vitess.io/vitess/go/vt/log"
    31  )
    32  
    33  var (
    34  	onCloseHooks event.Hooks
    35  	// ExitChan waits for a signal that tells the process to terminate
    36  	ExitChan chan os.Signal
    37  )
    38  
    39  // Run starts listening for RPC and HTTP requests,
    40  // and blocks until it the process gets a signal.
    41  func Run(port int) {
    42  	populateListeningURL(int32(port))
    43  	createGRPCServer()
    44  	onRunHooks.Fire()
    45  	serveGRPC()
    46  	serveSocketFile()
    47  
    48  	l, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
    49  	if err != nil {
    50  		log.Exit(err)
    51  	}
    52  	go http.Serve(l, nil)
    53  
    54  	ExitChan = make(chan os.Signal, 1)
    55  	signal.Notify(ExitChan, syscall.SIGTERM, syscall.SIGINT)
    56  	// Wait for signal
    57  	<-ExitChan
    58  	l.Close()
    59  
    60  	startTime := time.Now()
    61  	log.Infof("Entering lameduck mode for at least %v", lameduckPeriod)
    62  	log.Infof("Firing asynchronous OnTerm hooks")
    63  	go onTermHooks.Fire()
    64  
    65  	fireOnTermSyncHooks(onTermTimeout)
    66  	if remain := lameduckPeriod - time.Since(startTime); remain > 0 {
    67  		log.Infof("Sleeping an extra %v after OnTermSync to finish lameduck period", remain)
    68  		time.Sleep(remain)
    69  	}
    70  
    71  	log.Info("Shutting down gracefully")
    72  	fireOnCloseHooks(onCloseTimeout)
    73  }
    74  
    75  // Close runs any registered exit hooks in parallel.
    76  func Close() {
    77  	onCloseHooks.Fire()
    78  	ListeningURL = url.URL{}
    79  }
    80  
    81  // OnClose registers f to be run at the end of the app lifecycle.
    82  // This happens after the lameduck period just before the program exits.
    83  // All hooks are run in parallel.
    84  func OnClose(f func()) {
    85  	onCloseHooks.Add(f)
    86  }