github.com/letsencrypt/trillian@v1.1.2-0.20180615153820-ae375a99d36a/util/process.go (about)

     1  // Copyright 2016 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"context"
    19  	"net"
    20  	"net/http"
    21  	"os"
    22  	"os/signal"
    23  	"syscall"
    24  
    25  	"github.com/golang/glog"
    26  )
    27  
    28  // StartHTTPServer starts an HTTP server on the given address.
    29  func StartHTTPServer(addr, certFile, keyFile string) error {
    30  	sock, err := net.Listen("tcp", addr)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	go func() {
    35  		glog.Info("HTTP server starting")
    36  		// Let http.ServeTLS handle the error case when only one of the flags is set.
    37  		if certFile != "" || keyFile != "" {
    38  			err = http.ServeTLS(sock, nil, certFile, keyFile)
    39  		} else {
    40  			err = http.Serve(sock, nil)
    41  		}
    42  		if err != nil {
    43  			glog.Errorf("HTTP server stopped: %v", err)
    44  		}
    45  	}()
    46  
    47  	return nil
    48  }
    49  
    50  // AwaitSignal waits for standard termination signals, then runs the given
    51  // function. Can early return if the passed in context is canceled, in which
    52  // case the function is not run.
    53  func AwaitSignal(ctx context.Context, doneFn func()) {
    54  	// Subscribe for the standard set of signals used to terminate a server.
    55  	sigs := make(chan os.Signal, 1)
    56  	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    57  	defer signal.Stop(sigs)
    58  
    59  	// Wait for a signal or context cancellation.
    60  	select {
    61  	case sig := <-sigs:
    62  		glog.Warningf("Signal received: %v", sig)
    63  		doneFn()
    64  	case <-ctx.Done():
    65  		glog.Infof("AwaitSignal canceled: %v", ctx.Err())
    66  	}
    67  }