istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/uds/listener.go (about)

     1  // Copyright Istio Authors
     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 uds
    16  
    17  import (
    18  	"fmt"
    19  	"net"
    20  	"os"
    21  	"path/filepath"
    22  
    23  	"istio.io/istio/pkg/log"
    24  )
    25  
    26  func NewListener(path string) (net.Listener, error) {
    27  	// Remove unix socket before use.
    28  	if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
    29  		// Anything other than "file not found" is an error.
    30  		return nil, fmt.Errorf("failed to remove unix://%s: %v", path, err)
    31  	}
    32  
    33  	// Attempt to create the folder in case it doesn't exist
    34  	if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
    35  		// If we cannot create it, just warn here - we will fail later if there is a real error
    36  		log.Warnf("Failed to create directory for %v: %v", path, err)
    37  	}
    38  
    39  	var err error
    40  	listener, err := net.Listen("unix", path)
    41  	if err != nil {
    42  		return nil, fmt.Errorf("failed to listen on unix socket %q: %v", path, err)
    43  	}
    44  
    45  	// Update file permission so that istio-proxy has permission to access it.
    46  	if _, err := os.Stat(path); err != nil {
    47  		return nil, fmt.Errorf("uds file %q doesn't exist", path)
    48  	}
    49  	if err := os.Chmod(path, 0o666); err != nil {
    50  		return nil, fmt.Errorf("failed to update %q permission", path)
    51  	}
    52  
    53  	return listener, nil
    54  }