// RotateFile closes and reopens the log file to allow for rotation
// by an external source.  If the log isn't backed by a file then
// it does nothing.
518289
func RotateFile() error {
	logger := FromContext(context.Background())

	if logFile == nil && logFilePath == "" {
		logger.Debug("Traefik log is not writing to a file, ignoring rotate request")
		return nil
	}

	if logFile != nil {
		defer func(f *os.File) {
			_ = f.Close()
		}(logFile)
	}

	if err := OpenFile(logFilePath); err != nil {
		return fmt.Errorf("error opening log file: %s", err)
	}

	return nil
}
30938
func CloseFile(err error, f io.Closer) error {
	if lerr := f.Close(); lerr != nil && err == nil {
		err = lerr
	}
	return err
}
1284656
func (f *LogFile) Close() error {
	// Wait until the file has no more references.
	f.wg.Wait()

	if f.w != nil {
		f.w.Flush()
		f.w = nil
	}

	if f.file != nil {
		f.file.Close()
		f.file = nil
	}

	if f.data != nil {
		mmap.Unmap(f.data)
	}

	f.mms = make(logMeasurements)
	return nil
}
990226
func LoadFile(path string) error {
	return Load(file.NewSource(
		file.WithPath(path),
	))
}
1303564
func (journal *txJournal) rotate(all map[common.Address]types.Transactions) error {
	// Close the current journal (if any is open)
	if journal.writer != nil {
		if err := journal.writer.Close(); err != nil {
			return err
		}
		journal.writer = nil
	}
	// Generate a new journal with the contents of the current pool
	replacement, err := os.OpenFile(journal.path+".new", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		return err
	}
	journaled := 0
	for _, txs := range all {
		for _, tx := range txs {
			if err = rlp.Encode(replacement, tx); err != nil {
				replacement.Close()
				return err
			}
		}
		journaled += len(txs)
	}
	replacement.Close()

	// Replace the live journal with the newly generated one
	if err = os.Rename(journal.path+".new", journal.path); err != nil {
		return err
	}
	sink, err := os.OpenFile(journal.path, os.O_WRONLY|os.O_APPEND, 0755)
	if err != nil {
		return err
	}
	journal.writer = sink
	log.Info("Regenerated local transaction journal", "transactions", journaled, "accounts", len(all))

	return nil
}
222728
func writeFile(fs utilfs.Filesystem, path string, data []byte) (retErr error) {
	// Create a temporary file in the base directory of `path` with a prefix.
	tmpFile, err := fs.TempFile(filepath.Dir(path), tmpPrefix)
	if err != nil {
		return err
	}

	tmpPath := tmpFile.Name()
	shouldClose := true

	defer func() {
		// Close the file.
		if shouldClose {
			if err := tmpFile.Close(); err != nil {
				if retErr == nil {
					retErr = fmt.Errorf("close error: %v", err)
				} else {
					retErr = fmt.Errorf("failed to close temp file after error %v; close error: %v", retErr, err)
				}
			}
		}

		// Clean up the temp file on error.
		if retErr != nil && tmpPath != "" {
			if err := removePath(fs, tmpPath); err != nil {
				retErr = fmt.Errorf("failed to remove the temporary file (%q) after error %v; remove error: %v", tmpPath, retErr, err)
			}
		}
	}()

	// Write data.
	if _, err := tmpFile.Write(data); err != nil {
		return err
	}

	// Sync file.
	if err := tmpFile.Sync(); err != nil {
		return err
	}

	// Closing the file before renaming.
	err = tmpFile.Close()
	shouldClose = false
	if err != nil {
		return err
	}

	return fs.Rename(tmpPath, path)
}
1176147
func LoadFile(config interface{}, file string, opts Options) error {
	return LoadFiles(config, []string{file}, opts)
}
347097
func LockFile(filelockpath string) (*os.File, error) {

	if true {
		// take advantage of Open and O_EXCL (man creat for more info)
		// the downside of this approach is that killing the application
		// will prevent file lockfile cleanup even if there is a defer os.Remove(lockfile)
	WAIT_FOR_LOCK:
		for {
			glog.V(2).Infof("locking file: %s", filelockpath)
			fp, err := os.OpenFile(filelockpath, syscall.O_RDWR|syscall.O_CREAT|syscall.O_EXCL, 0600)
			if err != nil {
				if !strings.Contains(err.Error(), syscall.EEXIST.Error()) {
					return nil, err
				}
			} else {
				glog.V(2).Infof("locked file: %s", filelockpath)
				return fp, nil
			}

			glog.Infof("waiting to lock file: %s", filelockpath)
			select {
			case <-time.After(1 * time.Second):
				continue WAIT_FOR_LOCK
			}
		}

		//return nil, fmt.Errorf("timed out waiting to lock file %s", filelockpath)
	} else {

		// other failed attempts to lock file using fcntl/flock/...
		fp, err := os.OpenFile(filelockpath, syscall.O_RDWR|syscall.O_CREAT, 0600)
		if err != nil {
			return nil, err
		}

		glog.V(2).Infof("locking file: %s", filelockpath)
		if false {
			// FIXME: this is not working from GO, but works from C - thread issue even when sync mutex is used
			var flp = C.CString(filelockpath)
			defer C.free(unsafe.Pointer(flp))
			rc := C.fd_lock(C.int(fp.Fd()), flp)
			if 0 != rc {
				return nil, fmt.Errorf("unable to lock file %s", filelockpath)
			}
			/*
				} else if false {
					// BEWARE: flock does not work when two hosts are NFS locking
					// flock tested and works on ubuntu: ext4, btrfs, NFS (same host)
					// flock tested on centos: tmpfs, ext4, btrfs, NFS (same host)
					if err := unix.Flock(int(fp.Fd()), unix.LOCK_EX); err != nil {
						return nil, err
					}
				} else if false {
					// FIXME: unix.FcntlFlock is not working - thread issue and NFS issue
					ft := unix.Flock_t{
						Type:   syscall.F_WRLCK,         //Type of lock: F_RDLCK, F_WRLCK, F_UNLCK
						Whence: int16(os.SEEK_SET),      // How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END
						Start:  0,                       // Starting offset for lock
						Len:    0,                       // Number of bytes to lock
						Pid:    int32(syscall.Getpid()), // PID of process blocking our lock (F_GETLK only)
					}
					glog.V(2).Infof("syscall.Flock_t %#v", ft)

					if err := unix.FcntlFlock(fp.Fd(), syscall.F_SETLKW, &ft); err != nil {
						return nil, err
					}
			*/
		} else if false {
			// FIXME: flock does not work when two hosts are NFS locking
			// flock tested and works on ubuntu: ext4, btrfs, NFS (same host)
			// flock tested on centos: tmpfs, ext4, btrfs, NFS (same host)
			if err := syscall.Flock(int(fp.Fd()), syscall.LOCK_EX); err != nil {
				return nil, err
			}
		} else if false {
			// FIXME: syscall.FcntlFlock is not working - thread issue and syscall issue and NFS issue
			ft := syscall.Flock_t{
				Type:   syscall.F_WRLCK,         //Type of lock: F_RDLCK, F_WRLCK, F_UNLCK
				Whence: int16(os.SEEK_SET),      // How to interpret l_start: SEEK_SET, SEEK_CUR, SEEK_END
				Start:  0,                       // Starting offset for lock
				Len:    0,                       // Number of bytes to lock
				Pid:    int32(syscall.Getpid()), // PID of process blocking our lock (F_GETLK only)
			}
			glog.V(2).Infof("syscall.Flock_t %#v", ft)

			if err := syscall.FcntlFlock(fp.Fd(), syscall.F_SETLKW /* F_GETLK, F_SETLK, F_SETLKW */, &ft); err != nil {
				return nil, err
			}
		} else if false {
			// FIXME: syscall.FcntlFlock is not working - thread issue and syscall issue and NFS issue
			// This type matches C's "struct flock" defined in /usr/include/x86_64-linux-gnu/bits/fcntl.h
			k := struct {
				Type   uint32
				Whence uint32
				Start  uint64
				Len    uint64
				Pid    uint32
			}{
				Type:   syscall.F_WRLCK,
				Whence: uint32(os.SEEK_SET),
				Start:  0,
				Len:    0, // 0 means to lock the entire file.
				Pid:    uint32(os.Getpid()),
			}

			glog.V(2).Infof("mimic /usr/include/x86_64-linux-gnu/bits/fcntl.h syscall.Flock_t %#v", k)
			_, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fp.Fd(), uintptr(syscall.F_SETLK), uintptr(unsafe.Pointer(&k)))
			if errno != 0 {
				fp.Close()
				return nil, fmt.Errorf("syscall.Syscall error: %s", errno)
			}
		} else {
			return nil, fmt.Errorf("all filelocking implementations fail")
		}

		glog.V(2).Infof("locked  file: %s", filelockpath)
		return fp, nil
	}
}
1012698
func NewLogFile(name string, file *os.File) (*LogFile, error) {
	rw := &LogFile{
		file: file,
		name: name,
	}
	if file == nil {
		if err := rw.Rotate(); err != nil {
			return nil, err
		}
	}
	return rw, nil
}
76354
func (g *Group) RotateFile() {
	g.mtx.Lock()
	defer g.mtx.Unlock()

	headPath := g.Head.Path

	if err := g.headBuf.Flush(); err != nil {
		panic(err)
	}

	if err := g.Head.Sync(); err != nil {
		panic(err)
	}

	if err := g.Head.closeFile(); err != nil {
		panic(err)
	}

	indexPath := filePathForIndex(headPath, g.maxIndex, g.maxIndex+1)
	if err := os.Rename(headPath, indexPath); err != nil {
		panic(err)
	}

	g.maxIndex++
}
746586
func ExpandFile(dest, src string) error {
	h, err := os.Open(src)
	if err != nil {
		return err
	}
	defer h.Close()
	return Expand(dest, h)
}
1290559
func LoadFile(filename string) (*File, error) {
	// check if the file exists, return a new file if it doesn't
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		file := NewFile()
		file.Filename = filename
		return file, nil
	}

	// if file exists, read and parse it
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return Parse(filename, filename, f)
}
1280627
func (rl *RotateLogs) Close() error {
	rl.mutex.Lock()
	defer rl.mutex.Unlock()

	if rl.outFh == nil {
		return nil
	}

	rl.outFh.Close()
	rl.outFh = nil
	return nil
}
1021559
func initLogRotator(logFile string) {
	logDir, _ := filepath.Split(logFile)
	err := os.MkdirAll(logDir, 0700)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create log directory: %v\n", err)
		os.Exit(1)
	}
	r, err := rotator.New(logFile, 10*1024, false, 3)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create file rotator: %v\n", err)
		os.Exit(1)
	}

	pr, pw := io.Pipe()
	go r.Run(pr)

	logRotator = r
	logRotatorPipe = pw
}
1248946
func OpenFile(path string) error {
	logFilePath = path

	var err error
	logFile, err = os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		return err
	}

	SetOutput(logFile)
	return nil
}
858275
func Rotate(cfg *config.Config) (io.Writer, error) {
	format, found := cfg.Attrs["filename"]
	if !found {
		return nil, argNotFoundErr("rotate", "filename")
	}

	dir, found := cfg.Attrs["dir"]
	if !found {
		return nil, argNotFoundErr("rotate", "dir")
	}

	sizeStr, found := cfg.Attrs["size"]
	if !found {
		return nil, argNotFoundErr("rotate", "size")
	}

	size, err := toByte(sizeStr)
	if err != nil {
		return nil, err
	}

	return rotate.New(format, dir, size)
}
2957
func OpenLockFile(name string, perm os.FileMode) (lock *LockFile, err error) {
	var file *os.File
	if file, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm); err == nil {
		lock = &LockFile{file}
	}
	return
}