github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/hud/server/serving.go (about)

     1  package server
     2  
     3  /*
     4  Copyright 2016 The Kubernetes Authors.
     5  
     6  Licensed under the Apache License, Version 2.0 (the "License");
     7  you may not use this file except in compliance with the License.
     8  You may obtain a copy of the License at
     9  
    10      http://www.apache.org/licenses/LICENSE-2.0
    11  
    12  Unless required by applicable law or agreed to in writing, software
    13  distributed under the License is distributed on an "AS IS" BASIS,
    14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15  See the License for the specific language governing permissions and
    16  limitations under the License.
    17  */
    18  
    19  import (
    20  	"context"
    21  	"crypto/tls"
    22  	"fmt"
    23  	"net"
    24  	"net/http"
    25  	"time"
    26  
    27  	"k8s.io/apimachinery/pkg/util/runtime"
    28  
    29  	"github.com/tilt-dev/tilt/pkg/logger"
    30  )
    31  
    32  // This code has been adapted from
    33  // https://github.com/kubernetes/apiserver/blob/master/pkg/server/secure_serving.go
    34  
    35  // RunServer spawns a go-routine continuously serving
    36  func runServer(
    37  	ctx context.Context,
    38  	server *http.Server,
    39  	ln net.Listener,
    40  ) {
    41  	go func() {
    42  		defer runtime.HandleCrash()
    43  
    44  		var listener net.Listener = tcpKeepAliveListener{ln}
    45  		if server.TLSConfig != nil {
    46  			listener = tls.NewListener(listener, server.TLSConfig)
    47  		}
    48  		err := server.Serve(listener)
    49  		msg := fmt.Sprintf("Stopped listening on %s", ln.Addr().String())
    50  		select {
    51  		case <-ctx.Done():
    52  		default:
    53  			logger.Get(ctx).Errorf("%s due to error: %v", msg, err)
    54  		}
    55  	}()
    56  }
    57  
    58  // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
    59  // connections. It's used by ListenAndServe and ListenAndServeTLS so
    60  // dead TCP connections (e.g. closing laptop mid-download) eventually
    61  // go away.
    62  //
    63  // Copied from Go 1.7.2 net/http/server.go
    64  const (
    65  	defaultKeepAlivePeriod = 3 * time.Minute
    66  )
    67  
    68  type tcpKeepAliveListener struct {
    69  	net.Listener
    70  }
    71  
    72  func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {
    73  	c, err := ln.Listener.Accept()
    74  	if err != nil {
    75  		return nil, err
    76  	}
    77  	if tc, ok := c.(*net.TCPConn); ok {
    78  		_ = tc.SetKeepAlive(true)
    79  		_ = tc.SetKeepAlivePeriod(defaultKeepAlivePeriod)
    80  	}
    81  	return c, nil
    82  }