// openNew opens a new log file for writing, moving any old log file out of the
// way.  This methods assumes the file has already been closed.
969782
func (l *Logger) openNew() error {
	err := os.MkdirAll(l.dir(), 0755)
	if err != nil {
		return fmt.Errorf("can't make directories for new logfile: %s", err)
	}

	name := l.filename()
	mode := os.FileMode(0600)
	info, err := os_Stat(name)
	if err == nil {
		// Copy the mode off the old logfile.
		mode = info.Mode()
		// move the existing file
		newname := backupName(name, l.LocalTime)
		if err := os.Rename(name, newname); err != nil {
			return fmt.Errorf("can't rename log file: %s", err)
		}

		// this is a no-op anywhere but linux
		if err := chown(name, info); err != nil {
			return err
		}
	}

	// we use truncate here because this should only get called when we've moved
	// the file ourselves. if someone else creates the file in the meantime,
	// just wipe out the contents.
	f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
	if err != nil {
		return fmt.Errorf("can't open new logfile: %s", err)
	}
	l.file = f
	l.size = 0
	return nil
}
1276521
func ReadConfigOrNew(filename string) (*api.Config, error) {
	data, err := ioutil.ReadFile(filename)
	if os.IsNotExist(err) {
		return api.NewConfig(), nil
	} else if err != nil {
		return nil, errors.Wrapf(err, "Error reading file %q", filename)
	}

	// decode config, empty if no bytes
	config, err := decode(data)
	if err != nil {
		return nil, errors.Errorf("could not read config: %v", err)
	}

	// initialize nil maps
	if config.AuthInfos == nil {
		config.AuthInfos = map[string]*api.AuthInfo{}
	}
	if config.Clusters == nil {
		config.Clusters = map[string]*api.Cluster{}
	}
	if config.Contexts == nil {
		config.Contexts = map[string]*api.Context{}
	}

	return config, nil
}
190033
func (f *Logfile) Reopen() error {
	f.Lock()
	defer f.Unlock()

	if f.opened {
		if err := f.closeLog(); err != nil {
			return err
		}
	}

	if err := f.openLog(); err != nil {
		return err
	}

	return nil
}
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
}
802228
func (e *EncryptedRaftLogger) BootstrapNew(metadata []byte) error {
	e.encoderMu.Lock()
	defer e.encoderMu.Unlock()
	encrypter, decrypter := encryption.Defaults(e.EncryptionKey, e.FIPS)
	walFactory := NewWALFactory(encrypter, decrypter)

	for _, dirpath := range []string{filepath.Dir(e.walDir()), e.snapDir()} {
		if err := os.MkdirAll(dirpath, 0700); err != nil {
			return errors.Wrapf(err, "failed to create %s", dirpath)
		}
	}
	var err error
	// the wal directory must not already exist upon creation
	e.wal, err = walFactory.Create(e.walDir(), metadata)
	if err != nil {
		return errors.Wrap(err, "failed to create WAL")
	}

	e.snapshotter = NewSnapFactory(encrypter, decrypter).New(e.snapDir())
	return nil
}
426872
func (bw *BufferedFileWriter) Reopen() error {
	bw.mu.Lock()
	bw.bufWriter.Flush()

	// use non-mutex version since we are using this one
	err := bw.origWriter.reopen()

	bw.bufWriter.Reset(io.Writer(bw.origWriter))
	bw.mu.Unlock()

	return err
}
636751
func (f *FileWriter) Reopen() error {
	f.mu.Lock()
	err := f.reopen()
	f.mu.Unlock()
	return err
}
1287720
func (l *localFileSystem) OpenFile(filePath string) (io.ReadCloser, error) {
	f, err := os.Open(filePath)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return f, nil
}
566269
func NewFileLog(cfg FileLogConfig) (*FileLog, error) {
	if err := cfg.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}
	f := &FileLog{
		FileLogConfig: cfg,
		Entry: log.WithFields(log.Fields{
			trace.Component: teleport.ComponentAuditLog,
		}),
	}
	return f, nil
}
1332781
func (l *LogFS) Open(ctx context.Context, path string) (*File, error) {
	l.logger.Printf("%v: open: %v", l.name, path)
	f, err := l.fs.Open(ctx, path)
	if err != nil {
		l.logger.Printf("%v: open error: %v: %v", l.name, path, err)
	}
	return f, err
}
234255
func OpenLogfile(lf string) error {
	logMutex.Lock()
	defer logMutex.Unlock()

	return openLogfileLocked(lf)
}
534855
func OpenLog(file string) (*Log, error) {

	f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE, 0666)
	if err != nil {
		return nil, err
	}

	log := Log{f, true}

	return &log, nil
}
195790
func Open(filename string) (*os.File, error) {
	return OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
}
104770
func (file File) NewWriter(out output) (wr *Writer, err error) {
	if file.Channels != 1 {
		err = fmt.Errorf("sorry, only mono currently")
		return
	}

	wr = &Writer{}
	wr.output = out
	wr.sampleBuf = bufio.NewWriter(out)
	wr.options = file

	// write header when close to get correct number of samples
	_, err = wr.Seek(12, os.SEEK_SET)
	if err != nil {
		return
	}

	// fmt.Fprintf(wr, "%s", tokenChunkFmt)
	n, err := wr.output.Write(tokenChunkFmt[:])
	if err != nil {
		return
	}
	wr.bytesWritten += n

	chunkFmt := riffChunkFmt{
		LengthOfHeader: 16,
		AudioFormat:    1,
		NumChannels:    file.Channels,
		SampleRate:     file.SampleRate,
		BytesPerSec:    uint32(file.Channels) * file.SampleRate * uint32(file.SignificantBits) / 8,
		BytesPerBloc:   file.SignificantBits / 8 * file.Channels,
		BitsPerSample:  file.SignificantBits,
	}

	err = binary.Write(wr.output, binary.LittleEndian, chunkFmt)
	if err != nil {
		return
	}
	wr.bytesWritten += 20 //sizeof riffChunkFmt

	n, err = wr.output.Write(tokenData[:])
	if err != nil {
		return
	}
	wr.bytesWritten += n

	// leave space for the data size
	_, err = wr.Seek(4, os.SEEK_CUR)
	if err != nil {
		return
	}

	return
}
40484
func NewReopenWriter(opener Opener, sig ...os.Signal) (io.Writer, error) {
	w, err := opener.Open()
	if err != nil {
		return nil, err
	}
	c := make(chan os.Signal, 1)
	signal.Notify(c, sig...)
	r := &reopenWriter{
		writer: w,
	}
	reopen := func() {
		r.lock.Lock()
		defer r.lock.Unlock()
		if r.writer != nil {
			err := r.writer.Close()
			// io.Closer does not guarantee that it is safe to call it twice.
			r.writer = nil
			if err != nil {
				r.lastErr = err
				return
			}
		}
		w, err := opener.Open()
		if err != nil {
			r.lastErr = err
			return
		}
		r.writer = w
		r.lastErr = nil
	}
	go func() {
		for range c {
			reopen()
		}
	}()
	return r, nil
}
1177992
func NewOut(logFile string) (*Tee, error) {
	if logFile == "" {
		return &Tee{}, nil
	}

	f, err := os.Create(logFile)
	if err != nil {
		return nil, err
	}
	return &Tee{f: f}, nil
}
1098803
func NewWriter(filepath, sep string, replaceSeparator bool, alt string) (Writer, error) {
	w := Writer{
		Separator:        sep,
		StripRepeatedSep: false,
		ReplaceSeparator: replaceSeparator,
		SeparatorAlt:     alt}
	return w, w.open(filepath)
}