github.com/dolthub/go-mysql-server@v0.18.0/internal/sockstate/sockstate.go (about)

     1  // Copyright 2020-2021 Dolthub, Inc.
     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 sockstate
    16  
    17  import (
    18  	"strconv"
    19  
    20  	"gopkg.in/src-d/go-errors.v1"
    21  )
    22  
    23  type SockState uint8
    24  
    25  const (
    26  	Broken = iota
    27  	Other
    28  	Error
    29  )
    30  
    31  var ErrNoSocketLink = errors.NewKind("couldn't resolve file descriptor link to socket")
    32  
    33  // ErrMultipleSocketsForInode is returned when more than one socket is found for an inode
    34  var ErrMultipleSocketsForInode = errors.NewKind("more than one socket found for inode")
    35  
    36  func GetInodeSockState(port int, inode uint64) (SockState, error) {
    37  	socks, err := tcpSocks(func(s *sockTabEntry) bool {
    38  		if s.LocalAddr.Port != uint16(port) {
    39  			return false
    40  		}
    41  
    42  		si, err := strconv.ParseUint(s.Ino, 10, 64)
    43  		if err != nil {
    44  			return false
    45  		}
    46  		return inode == si
    47  	})
    48  	if err != nil {
    49  		return Error, err
    50  	}
    51  
    52  	switch len(socks) {
    53  	case 0:
    54  		return Broken, nil
    55  	case 1:
    56  		switch socks[0].State {
    57  		case CloseWait:
    58  			fallthrough
    59  		case TimeWait:
    60  			fallthrough
    61  		case FinWait1:
    62  			fallthrough
    63  		case FinWait2:
    64  			fallthrough
    65  		case Close:
    66  			fallthrough
    67  		case Closing:
    68  			return Broken, nil
    69  		default:
    70  			return Other, nil
    71  		}
    72  	default: // more than one sock for inode, impossible?
    73  		return Error, ErrMultipleSocketsForInode.New()
    74  	}
    75  }