github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/helper/containercenter/mount_others.go (about)

     1  // Copyright 2021 iLogtail 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  //go:build !windows
    16  // +build !windows
    17  
    18  package containercenter
    19  
    20  import (
    21  	"io/fs"
    22  	"os"
    23  	"strings"
    24  )
    25  
    26  var DefaultLogtailMountPath string
    27  
    28  func GetMountedFilePath(logPath string) string {
    29  	return GetMountedFilePathWithBasePath(DefaultLogtailMountPath, logPath)
    30  }
    31  
    32  func GetMountedFilePathWithBasePath(basePath, logPath string) string {
    33  	return basePath + logPath
    34  }
    35  
    36  func TryGetRealPath(path string) (string, fs.FileInfo) {
    37  	sepLen := len(string(os.PathSeparator))
    38  	if len(path) < sepLen {
    39  		return "", nil
    40  	}
    41  
    42  	index := 0 // assume path is absolute
    43  	for i := 0; i < 10; i++ {
    44  		if f, err := os.Stat(path); err == nil {
    45  			return path, f
    46  		}
    47  		for {
    48  			j := strings.IndexRune(path[index+sepLen:], os.PathSeparator)
    49  			if j == -1 {
    50  				index = len(path)
    51  			} else {
    52  				index += j + sepLen
    53  			}
    54  
    55  			f, err := os.Lstat(path[:index])
    56  			if err != nil {
    57  				return "", nil
    58  			}
    59  			if f.Mode()&os.ModeSymlink != 0 {
    60  				// path[:index] is a symlink
    61  				target, _ := os.Readlink(path[:index])
    62  				partialPath := GetMountedFilePath(target)
    63  				path = partialPath + path[index:]
    64  				if _, err := os.Stat(partialPath); err != nil {
    65  					// path referenced by partialPath does not exist or has symlink
    66  					index = 0
    67  				} else {
    68  					index = len(partialPath)
    69  				}
    70  				break
    71  			}
    72  		}
    73  	}
    74  	return "", nil
    75  }
    76  
    77  func init() {
    78  	defaultPath := "/logtail_host"
    79  	_, err := os.Stat(defaultPath)
    80  	// only change default mount path when `/logtail_host` path exists.
    81  	if err == nil {
    82  		DefaultLogtailMountPath = defaultPath
    83  	}
    84  }