// OpenWAL opens a file to log all consensus messages and timeouts for deterministic accountability
348661
func (cs *ConsensusState) OpenWAL(walFile string) (WAL, error) {
	wal, err := NewWAL(walFile)
	if err != nil {
		cs.Logger.Error("Failed to open WAL for consensus state", "wal", walFile, "err", err)
		return nil, err
	}
	wal.SetLogger(cs.Logger.With("wal", walFile))
	if err := wal.Start(); err != nil {
		return nil, err
	}
	return wal, nil
}
473276
func OpenShimStdoutLog(ctx context.Context, logDirPath string) (io.ReadWriteCloser, error) {
	return fifo.OpenFifo(ctx, filepath.Join(logDirPath, "shim.stdout.log"), unix.O_RDWR|unix.O_CREAT, 0700)
}
912178
func Openlog(ident string, o Option, p Priority) {
	cs := C.CString(ident)

	mu.Lock()
	defer mu.Unlock()
	C.go_openlog(cs, C.int(o), C.int(p))
	C.free(unsafe.Pointer(cs))
}
30344
func (d Dir) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
	if name = d.resolve(name); name == "" {
		return nil, os.ErrNotExist
	}
	f, err := os.OpenFile(name, flag, perm)
	if err != nil {
		return nil, err
	}
	return f, nil
}
574744
func OpenFile(u *user.User, name string, flags int, perm uint32) (*os.File, error) {
	uid, gid, err := getIds(u)
	if err != nil {
		return nil, err
	}
	args := C.au_open_args_t{
		ids:   C.au_ids_t{uid: uid, gid: gid},
		path:  C.CString(name),
		flags: C.uint(flags),
		mode:  C.uint(perm),
	}

	fd, err := C.au_open(&args)
	if fd < 0 {
		return nil, err
	}
	return os.NewFile(uintptr(fd), name), nil
}
1278045
func OpenFile(path string, perm os.FileMode, size int64) (*LogFile, error) {
	l := LogFile{}
	l.path = path
	l.perm = perm
	l.size = size
	l.rate = DefaultRotationRate

	// Search for the first available path
	err := l.searchFirstAvPath()
	if err != nil {
		return nil, err
	}
	// Open the file descriptor
	f, err := os.OpenFile(l.Path(), os.O_APPEND|os.O_CREATE|os.O_RDWR, l.perm)
	if err != nil {
		return nil, err
	}
	l.file = f
	l.writer = gzip.NewWriter(f)
	// We start the rotate routine
	l.rotateRoutine()
	return &l, nil
}
138670
func (c *Client) openWriter(resp *Response) stateFunc {
	if !resp.Request.NoCreateDirectories {
		resp.err = mkdirp(resp.Filename)
		if resp.err != nil {
			return c.closeResponse
		}
	}

	// compute write flags
	flag := os.O_CREATE | os.O_WRONLY
	if resp.fi != nil {
		if resp.DidResume {
			flag = os.O_APPEND | os.O_WRONLY
		} else {
			flag = os.O_TRUNC | os.O_WRONLY
		}
	}

	// open file
	f, err := os.OpenFile(resp.Filename, flag, 0644)
	if err != nil {
		resp.err = err
		return c.closeResponse
	}
	resp.writer = f

	// seek to start or end
	whence := os.SEEK_SET
	if resp.bytesResumed > 0 {
		whence = os.SEEK_END
	}
	_, resp.err = f.Seek(0, whence)
	if resp.err != nil {
		return c.closeResponse
	}

	// init transfer
	if resp.bufferSize < 1 {
		resp.bufferSize = 32 * 1024
	}
	b := make([]byte, resp.bufferSize)
	resp.transfer = newTransfer(
		resp.Request.Context(),
		resp.Request.RateLimiter,
		resp.writer,
		resp.HTTPResponse.Body,
		b)

	// next step is copyFile, but this will be called later in another goroutine
	return nil
}
1194651
func (r *runtimeOCI) ReopenContainerLog(c *Container) error {
	controlPath := filepath.Join(c.BundlePath(), "ctl")
	controlFile, err := os.OpenFile(controlPath, os.O_WRONLY, 0)
	if err != nil {
		return fmt.Errorf("failed to open container ctl file: %v", err)
	}
	defer controlFile.Close()

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return fmt.Errorf("failed to create new watch: %v", err)
	}
	defer watcher.Close()

	done := make(chan struct{})
	errorCh := make(chan error)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				logrus.Debugf("event: %v", event)
				if event.Op&fsnotify.Create == fsnotify.Create || event.Op&fsnotify.Write == fsnotify.Write {
					logrus.Debugf("file created %s", event.Name)
					if event.Name == c.LogPath() {
						logrus.Debugf("expected log file created")
						close(done)
						return
					}
				}
			case err := <-watcher.Errors:
				errorCh <- fmt.Errorf("watch error for container log reopen %v: %v", c.ID(), err)
				return
			}
		}
	}()
	cLogDir := filepath.Dir(c.LogPath())
	if err := watcher.Add(cLogDir); err != nil {
		logrus.Errorf("watcher.Add(%q) failed: %s", cLogDir, err)
		close(done)
	}

	if _, err = fmt.Fprintf(controlFile, "%d %d %d\n", 2, 0, 0); err != nil {
		logrus.Debugf("Failed to write to control file to reopen log file: %v", err)
	}

	select {
	case err := <-errorCh:
		return err
	case <-done:
		break
	}

	return nil
}
707469
func (s *StanLogger) ReopenLogFile() {
	s.mu.Lock()
	if s.lfile == "" {
		s.mu.Unlock()
		s.Noticef("File log re-open ignored, not a file logger")
		return
	}
	if l, ok := s.log.(io.Closer); ok {
		if err := l.Close(); err != nil {
			s.mu.Unlock()
			s.Errorf("Unable to close logger: %v", err)
			return
		}
	}
	fileLog := natsdLogger.NewFileLogger(s.lfile, s.ltime, s.debug, s.trace, true)
	s.log = fileLog
	s.mu.Unlock()
	s.Noticef("File log re-opened")
}
1000490
func OpenWriter(path string) (io.WriteCloser, error) {
	return winio.DialPipe(path, nil)
}
304373
func (fs *MockFilesystem) OpenFile(name string, flag int, perm os.FileMode) (file File, err error) {
	f, ok := fs.Files[name]
	if ok {
		f.Opened = true
		f.Closed = false
		return f, nil
	}
	return (*MockFile)(nil), &os.PathError{Err: errors.New(name + ": No such file.")}
}
1165256
func makeOpenFiles(hs []syscall.Handle) (_ []io.ReadWriteCloser, err error) {
	fs := make([]io.ReadWriteCloser, len(hs))
	for i, h := range hs {
		if h != syscall.Handle(0) {
			if err == nil {
				fs[i], err = winio.MakeOpenFile(h)
			}
			if err != nil {
				syscall.Close(h)
			}
		}
	}
	if err != nil {
		for _, f := range fs {
			if f != nil {
				f.Close()
			}
		}
		return nil, err
	}
	return fs, nil
}
583933
func OpenBlock(logger log.Logger, dir string, pool chunkenc.Pool) (pb *Block, err error) {
	if logger == nil {
		logger = log.NewNopLogger()
	}
	var closers []io.Closer
	defer func() {
		if err != nil {
			var merr tsdb_errors.MultiError
			merr.Add(err)
			merr.Add(closeAll(closers))
			err = merr.Err()
		}
	}()
	meta, err := readMetaFile(dir)
	if err != nil {
		return nil, err
	}

	cr, err := chunks.NewDirReader(chunkDir(dir), pool)
	if err != nil {
		return nil, err
	}
	closers = append(closers, cr)

	ir, err := index.NewFileReader(filepath.Join(dir, indexFilename))
	if err != nil {
		return nil, err
	}
	closers = append(closers, ir)

	tr, tsr, err := readTombstones(dir)
	if err != nil {
		return nil, err
	}
	closers = append(closers, tr)

	// TODO refactor to set this at block creation time as
	// that would be the logical place for a block size to be calculated.
	bs := blockSize(cr, ir, tsr)
	meta.Stats.NumBytes = bs
	err = writeMetaFile(logger, dir, meta)
	if err != nil {
		level.Warn(logger).Log("msg", "couldn't write the meta file for the block size", "block", dir, "err", err)
	}

	pb = &Block{
		dir:             dir,
		meta:            *meta,
		chunkr:          cr,
		indexr:          ir,
		tombstones:      tr,
		symbolTableSize: ir.SymbolTableSize(),
		logger:          logger,
	}
	return pb, nil
}
920935
func OpenStatePool(args OpenParams) (*StatePool, error) {
	logger.Tracef("opening state pool")
	if err := args.Validate(); err != nil {
		return nil, errors.Annotate(err, "validating args")
	}

	pool := &StatePool{
		pool: make(map[string]*PoolItem),
		hub:  pubsub.NewSimpleHub(nil),
	}

	session := args.MongoSession.Copy()
	st, err := open(
		args.ControllerModelTag,
		session,
		args.InitDatabaseFunc,
		nil,
		args.NewPolicy,
		args.Clock,
		args.RunTransactionObserver,
	)
	if err != nil {
		session.Close()
		return nil, errors.Trace(err)
	}
	defer func() {
		if err != nil {
			if closeErr := st.Close(); closeErr != nil {
				logger.Errorf("closing State for %s: %v", args.ControllerModelTag, closeErr)
			}
		}
	}()
	// If the InitDatabaseFunc is set, then we are initializing the
	// database, and the model won't be there. So we only look for the model
	// if we aren't initializing.
	if args.InitDatabaseFunc == nil {
		if _, err = st.Model(); err != nil {
			return nil, errors.Trace(mongo.MaybeUnauthorizedf(err, "cannot read model %s", args.ControllerModelTag.Id()))
		}
	}
	if err = st.start(args.ControllerTag, pool.hub); err != nil {
		return nil, errors.Trace(err)
	}
	pool.systemState = st
	// When creating the txn watchers and the worker to keep it running
	// we really want to use wall clocks. Otherwise the events never get
	// noticed. The clocks in the runner and the txn watcher are used to
	// control polling, and never return the actual times.
	pool.watcherRunner = worker.NewRunner(worker.RunnerParams{
		// TODO add a Logger parameter to RunnerParams:
		// Logger: loggo.GetLogger(logger.Name() + ".txnwatcher"),
		IsFatal:      func(err error) bool { return errors.Cause(err) == errPoolClosed },
		RestartDelay: time.Second,
		Clock:        args.Clock,
	})
	pool.watcherRunner.StartWorker(txnLogWorker, func() (worker.Worker, error) {
		return watcher.NewTxnWatcher(
			watcher.TxnWatcherConfig{
				ChangeLog: st.getTxnLogCollection(),
				Hub:       pool.hub,
				Clock:     args.Clock,
				Logger:    loggo.GetLogger("juju.state.pool.txnwatcher"),
			})
	})
	return pool, nil
}
1159224
func (f Firewall) OpenPorts(ctx context.ProviderCallContext, rules []network.IngressRule) error {
	mode := f.environ.Config().FirewallMode()
	if mode != config.FwGlobal {
		return fmt.Errorf(
			"invalid firewall mode %q for opening ports on model",
			mode,
		)
	}

	globalGroupName := f.globalGroupName()
	seclist, err := f.ensureSecList(f.client.ComposeName(globalGroupName))
	if err != nil {
		return errors.Trace(err)
	}
	err = f.ensureSecRules(seclist, rules)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
46231
func (p *Pod) openFile(path string, flags int) (*os.File, error) {
	cdirfd, err := p.Fd()
	if err != nil {
		return nil, err
	}

	fd, err := syscall.Openat(cdirfd, path, flags, 0)
	if err != nil {
		return nil, err
	}

	return os.NewFile(uintptr(fd), path), nil
}
16458
func MigrateWAL(logger log.Logger, dir string) (err error) {
	if logger == nil {
		logger = log.NewNopLogger()
	}
	if exists, err := deprecatedWALExists(logger, dir); err != nil || !exists {
		return err
	}
	level.Info(logger).Log("msg", "migrating WAL format")

	tmpdir := dir + ".tmp"
	if err := os.RemoveAll(tmpdir); err != nil {
		return errors.Wrap(err, "cleanup replacement dir")
	}
	repl, err := wal.New(logger, nil, tmpdir)
	if err != nil {
		return errors.Wrap(err, "open new WAL")
	}

	// It should've already been closed as part of the previous finalization.
	// Do it once again in case of prior errors.
	defer func() {
		if err != nil {
			repl.Close()
		}
	}()

	w, err := OpenSegmentWAL(dir, logger, time.Minute, nil)
	if err != nil {
		return errors.Wrap(err, "open old WAL")
	}
	defer w.Close()

	rdr := w.Reader()

	var (
		enc RecordEncoder
		b   []byte
	)
	decErr := rdr.Read(
		func(s []RefSeries) {
			if err != nil {
				return
			}
			err = repl.Log(enc.Series(s, b[:0]))
		},
		func(s []RefSample) {
			if err != nil {
				return
			}
			err = repl.Log(enc.Samples(s, b[:0]))
		},
		func(s []Stone) {
			if err != nil {
				return
			}
			err = repl.Log(enc.Tombstones(s, b[:0]))
		},
	)
	if decErr != nil {
		return errors.Wrap(err, "decode old entries")
	}
	if err != nil {
		return errors.Wrap(err, "write new entries")
	}
	// We explicitly close even when there is a defer for Windows to be
	// able to delete it. The defer is in place to close it in-case there
	// are errors above.
	if err := w.Close(); err != nil {
		return errors.Wrap(err, "close old WAL")
	}
	if err := repl.Close(); err != nil {
		return errors.Wrap(err, "close new WAL")
	}
	if err := fileutil.Replace(tmpdir, dir); err != nil {
		return errors.Wrap(err, "replace old WAL")
	}
	return nil
}