GetFd go through this method to get fd.
(path string)
| 62 | |
| 63 | // GetFd go through this method to get fd. |
| 64 | func (fdm *FdManager) GetFd(path string) (fd *os.File, err error) { |
| 65 | fdm.lock.Lock() |
| 66 | defer fdm.lock.Unlock() |
| 67 | cleanPath := filepath.Clean(path) |
| 68 | if fdInfo := fdm.Cache[cleanPath]; fdInfo == nil { |
| 69 | fd, err = openFile(cleanPath, os.O_CREATE|os.O_RDWR, 0o644) |
| 70 | if err == nil { |
| 71 | // if the numbers of fd in cache larger than the cleanThreshold in config, we will clean useless fd in cache |
| 72 | if fdm.size >= fdm.cleanThresholdNums { |
| 73 | err = fdm.cleanUselessFd() |
| 74 | } |
| 75 | // if the numbers of fd in cache larger than the max numbers of fd in config, we will not add this fd to cache |
| 76 | if fdm.size >= fdm.maxFdNums { |
| 77 | return fd, nil |
| 78 | } |
| 79 | // add this fd to cache |
| 80 | fdm.AddToCache(fd, cleanPath) |
| 81 | return fd, nil |
| 82 | } else { |
| 83 | // determine if there are too many open files, we will first clean useless fd in cache and try open this file again |
| 84 | if strings.HasSuffix(err.Error(), TooManyFileOpenErrSuffix) { |
| 85 | cleanErr := fdm.cleanUselessFd() |
| 86 | // if something wrong in cleanUselessFd, we will return "open too many files" err, because we want user not the main err is that |
| 87 | if cleanErr != nil { |
| 88 | return nil, err |
| 89 | } |
| 90 | // try open this file again,if it still returns err, we will show this error to user |
| 91 | fd, err = openFile(cleanPath, os.O_CREATE|os.O_RDWR, 0o644) |
| 92 | if err != nil { |
| 93 | return nil, err |
| 94 | } |
| 95 | // add to cache if open this file successfully |
| 96 | fdm.AddToCache(fd, cleanPath) |
| 97 | } |
| 98 | return fd, err |
| 99 | } |
| 100 | } else { |
| 101 | fdInfo.using++ |
| 102 | fdm.fdList.moveNodeToFront(fdInfo) |
| 103 | return fdInfo.fd, nil |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // addToCache add fd to cache |
| 108 | func (fdm *FdManager) AddToCache(fd *os.File, cleanPath string) { |