// NewFS creates an FS
165331
func NewFS(ctx context.Context, config libkbfs.Config, log logger.Logger) (*FS, error) {
	if currentUserSIDErr != nil {
		return nil, currentUserSIDErr
	}
	quLog := config.MakeLogger(libkbfs.QuotaUsageLogModule("FS"))
	f := &FS{
		config:        config,
		log:           log,
		vlog:          config.MakeVLogger(log),
		notifications: libfs.NewFSNotifications(log),
		quotaUsage: libkbfs.NewEventuallyConsistentQuotaUsage(
			config, quLog, config.MakeVLogger(quLog)),
	}

	f.root = &Root{
		private: &FolderList{
			fs:         f,
			tlfType:    tlf.Private,
			folders:    make(map[string]fileOpener),
			aliasCache: map[string]string{},
		},
		public: &FolderList{
			fs:         f,
			tlfType:    tlf.Public,
			folders:    make(map[string]fileOpener),
			aliasCache: map[string]string{},
		},
		team: &FolderList{
			fs:         f,
			tlfType:    tlf.SingleTeam,
			folders:    make(map[string]fileOpener),
			aliasCache: map[string]string{},
		}}

	ctx = wrapContext(ctx, f)

	f.remoteStatus.Init(ctx, f.log, f.config, f)
	f.notifications.LaunchProcessor(ctx)
	go clearFolderListCacheLoop(ctx, f.root)

	return f, nil
}
23621
func NewFS(config libkbfs.Config, conn *fuse.Conn, debug bool,
	platformParams PlatformParams) *FS {
	log := config.MakeLogger("kbfsfuse")
	// We need extra depth for errors, so that we can report the line
	// number for the caller of processError, not processError itself.
	errLog := log.CloneWithAddedDepth(1)
	if debug {
		// Turn on debugging.  TODO: allow a proper log file and
		// style to be specified.
		log.Configure("", true, "")
		errLog.Configure("", true, "")
	}

	serveMux := http.NewServeMux()

	// Replicate the default endpoints from pprof's init function.
	serveMux.HandleFunc("/debug/pprof/", pprof.Index)
	serveMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	serveMux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	serveMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	serveMux.HandleFunc("/debug/pprof/trace", pprof.Trace)

	// Replicate the default endpoints from net/trace's init function.
	serveMux.HandleFunc("/debug/requests", makeTraceHandler(func(w http.ResponseWriter, req *http.Request, sensitive bool) {
		trace.Render(w, req, sensitive)
	}))
	serveMux.HandleFunc("/debug/events", makeTraceHandler(trace.RenderEvents))

	// Leave Addr blank to be set in enableDebugServer() and
	// disableDebugServer().
	debugServer := &http.Server{
		Handler:      serveMux,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	quLog := config.MakeLogger(libkbfs.QuotaUsageLogModule("FS"))
	fs := &FS{
		config:         config,
		conn:           conn,
		log:            log,
		errLog:         errLog,
		vlog:           config.MakeVLogger(log),
		errVlog:        config.MakeVLogger(errLog),
		debugServer:    debugServer,
		notifications:  libfs.NewFSNotifications(log),
		platformParams: platformParams,
		quotaUsage: libkbfs.NewEventuallyConsistentQuotaUsage(
			config, quLog, config.MakeVLogger(quLog)),
		nextInode: 2, // root is 1
	}
	fs.root.private = &FolderList{
		fs:      fs,
		tlfType: tlf.Private,
		folders: make(map[string]*TLF),
		inode:   fs.assignInode(),
	}
	fs.root.public = &FolderList{
		fs:      fs,
		tlfType: tlf.Public,
		folders: make(map[string]*TLF),
		inode:   fs.assignInode(),
	}
	fs.root.team = &FolderList{
		fs:      fs,
		tlfType: tlf.SingleTeam,
		folders: make(map[string]*TLF),
		inode:   fs.assignInode(),
	}
	fs.execAfterDelay = func(d time.Duration, f func()) {
		time.AfterFunc(d, f)
	}
	return fs
}
563242
func (fs *FileStore) newFileMsgStore(channelDirName, channel string, limits *MsgStoreLimits, doRecover bool) (*FileMsgStore, error) {
	// Create an instance and initialize
	ms := &FileMsgStore{
		fm:           fs.fm,
		hasFDsLimit:  fs.opts.FileDescriptorsLimit > 0,
		fstore:       fs,
		wOffset:      int64(4), // The very first record starts after the file version record
		files:        make(map[int]*fileSlice),
		channelName:  channel,
		bkgTasksDone: make(chan bool, 1),
		bkgTasksWake: make(chan bool, 1),
	}
	ms.init(channel, fs.log, limits)

	ms.setSliceLimits()
	ms.initCache()

	maxBufSize := fs.opts.BufferSize
	if maxBufSize > 0 {
		ms.bw = newBufferWriter(msgBufMinShrinkSize, maxBufSize)
		ms.bufferedSeqs = make([]uint64, 0, 1)
		ms.bufferedMsgs = make(map[uint64]*bufferedMsg)
	}

	// Use this variable for all errors below so we can do the cleanup
	var err error

	// Recovery case
	if doRecover {
		var dirFiles []os.FileInfo
		var fseq int64
		var datFile, idxFile *file
		var useIdxFile bool

		dirFiles, err = ioutil.ReadDir(channelDirName)
		for _, file := range dirFiles {
			if file.IsDir() {
				continue
			}
			fileName := file.Name()
			if !strings.HasPrefix(fileName, msgFilesPrefix) || !strings.HasSuffix(fileName, datSuffix) {
				continue
			}
			// Remove suffix
			fileNameWithoutSuffix := strings.TrimSuffix(fileName, datSuffix)
			// Remove prefix
			fileNameWithoutPrefixAndSuffix := strings.TrimPrefix(fileNameWithoutSuffix, msgFilesPrefix)
			// Get the file sequence number
			fseq, err = strconv.ParseInt(fileNameWithoutPrefixAndSuffix, 10, 64)
			if err != nil {
				err = fmt.Errorf("message log has an invalid name: %v", fileName)
				break
			}
			idxFName := fmt.Sprintf("%s%v%s", msgFilesPrefix, fseq, idxSuffix)
			useIdxFile = false
			if s, statErr := os.Stat(filepath.Join(channelDirName, idxFName)); s != nil && statErr == nil {
				useIdxFile = true
			}
			datFile, err = ms.fm.createFile(filepath.Join(channel, fileName), defaultFileFlags, nil)
			if err != nil {
				break
			}
			idxFile, err = ms.fm.createFile(filepath.Join(channel, idxFName), defaultFileFlags, nil)
			if err != nil {
				ms.fm.unlockFile(datFile)
				break
			}
			// Create the slice
			fslice := &fileSlice{file: datFile, idxFile: idxFile, lastUsed: time.Now().UnixNano()}
			// Recover the file slice
			err = ms.recoverOneMsgFile(fslice, int(fseq), useIdxFile)
			if err != nil {
				break
			}
		}
		if err == nil && ms.lastFSlSeq > 0 {
			// Now that all file slices have been recovered, we know which
			// one is the last, so use it as the write slice.
			ms.writeSlice = ms.files[ms.lastFSlSeq]
			// Need to set the writer, etc..
			ms.fm.lockFile(ms.writeSlice.file)
			err = ms.setFile(ms.writeSlice, -1)
			ms.fm.unlockFile(ms.writeSlice.file)
			if err == nil {
				// Set the beforeFileClose callback to the slices now that
				// we are done recovering.
				for _, fslice := range ms.files {
					ms.fm.setBeforeCloseCb(fslice.file, ms.beforeDataFileCloseCb(fslice))
					ms.fm.setBeforeCloseCb(fslice.idxFile, ms.beforeIndexFileCloseCb(fslice))
				}
				ms.checkSlices = 1
			}
		}
		if err == nil {
			// Apply message limits (no need to check if there are limits
			// defined, the call won't do anything if they aren't).
			err = ms.enforceLimits(false, true)
		}
	}
	if err == nil {
		ms.Lock()
		ms.allDone.Add(1)
		// Capture the time here first, it will then be captured
		// in the go routine we are about to start.
		ms.timeTick = time.Now().UnixNano()
		// On recovery, if there is age limit set and at least one message...
		if doRecover {
			if ms.limits.MaxAge > 0 && ms.totalCount > 0 {
				// Force the execution of the expireMsgs method.
				// This will take care of expiring messages that should have
				// expired while the server was stopped.
				ms.expireMsgs(ms.timeTick, int64(ms.limits.MaxAge))
			}
			// Now that we are done with recovery, close the write slice
			if ms.writeSlice != nil {
				ms.fm.closeFileIfOpened(ms.writeSlice.file)
				ms.fm.closeFileIfOpened(ms.writeSlice.idxFile)
			}
		}
		// Start the background tasks go routine
		go ms.backgroundTasks()
		ms.Unlock()
	}
	// Cleanup on error
	if err != nil {
		// The buffer writer may not be fully set yet
		if ms.bw != nil && ms.bw.buf == nil {
			ms.bw = nil
		}
		ms.Close()
		ms = nil
		action := "create"
		if doRecover {
			action = "recover"
		}
		err = fmt.Errorf("unable to %s message store for [%s]: %v", action, channel, err)
		return nil, err
	}

	return ms, nil
}
369544
func New(name string) *Folder {
	f := newFolder(name)
	f.Root = true
	return f
}
478506
func NewFiles(file string, files ...string) Files {
	return Files{
		first:     file,
		list:      files,
		mapKeyStr: strings.Join(files, ","),
	}
}
331682
func New() (http.FileSystem, error) {
	if zipData == "" {
		return nil, errors.New("statik/fs: no zip data registered")
	}
	zipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))
	if err != nil {
		return nil, err
	}
	files := make(map[string]file, len(zipReader.File))
	dirs := make(map[string][]string)
	fs := &statikFS{files: files, dirs: dirs}
	for _, zipFile := range zipReader.File {
		fi := zipFile.FileInfo()
		f := file{FileInfo: fi, fs: fs}
		f.data, err = unzip(zipFile)
		if err != nil {
			return nil, fmt.Errorf("statik/fs: error unzipping file %q: %s", zipFile.Name, err)
		}
		files["/"+zipFile.Name] = f
	}
	for fn := range files {
		// go up directories recursively in order to care deep directory
		for dn := path.Dir(fn); dn != fn; {
			if _, ok := files[dn]; !ok {
				files[dn] = file{FileInfo: dirInfo{dn}, fs: fs}
			} else {
				break
			}
			fn, dn = dn, path.Dir(dn)
		}
	}
	for fn := range files {
		dn := path.Dir(fn)
		if fn != dn {
			fs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))
		}
	}
	for _, s := range fs.dirs {
		sort.Strings(s)
	}
	return fs, nil
}
1335164
func NewFilespace() (*Filespace, error) {
	return &Filespace{
		root: &Dir{
			nodes: []os.FileInfo{},
		},
	}, nil
}
112876
func NewNFS(values *CreateNFSValue) *NFS {

	return &NFS{
		Appliance: &Appliance{
			Class:           "nfs",
			propName:        propName{Name: values.Name},
			propDescription: propDescription{Description: values.Description},
			propTags:        propTags{Tags: values.Tags},
			//propPlanID:      propPlanID{Plan: &Resource{ID: int64(values.Plan)}},
			propIcon: propIcon{
				&Icon{
					Resource: values.Icon,
				},
			},
		},
		Remark: &NFSRemark{
			ApplianceRemarkBase: &ApplianceRemarkBase{
				Switch: &ApplianceRemarkSwitch{
					ID: values.SwitchID,
				},
				Network: &ApplianceRemarkNetwork{
					NetworkMaskLen: values.MaskLen,
					DefaultRoute:   values.DefaultRoute,
				},
				Servers: []interface{}{
					map[string]interface{}{"IPAddress": values.IPAddress},
				},
			},
			//propPlanID: propPlanID{Plan: &Resource{ID: int64(values.Plan)}},
		},
	}

}
316472
func NewVFSCache(fs vfs.VFS) Cache {
	return &cache{fs: fs, stale: map[string]time.Time{}}
}
1368513
func NewRootMappingFs(fs afero.Fs, fromTo ...string) (*RootMappingFs, error) {
	rootMapToReal := radix.New().Txn()
	var virtualRoots []string

	for i := 0; i < len(fromTo); i += 2 {
		vr := filepath.Clean(fromTo[i])
		rr := filepath.Clean(fromTo[i+1])

		// We need to preserve the original order for Readdir
		virtualRoots = append(virtualRoots, vr)

		rootMapToReal.Insert([]byte(vr), rr)
	}

	return &RootMappingFs{Fs: fs,
		virtualRoots:  virtualRoots,
		rootMapToReal: rootMapToReal.Commit().Root()}, nil
}
1107473
func Newf(cause error, format string, args ...interface{}) Error {
	return makeErrorf(UnknownErrorError, cause, format, args...)
}
527835
func newFsBlockStore(id string, conf *Conf, indexConfig *blkstorage.IndexConfig,
	dbHandle *leveldbhelper.DBHandle) *fsBlockStore {
	return &fsBlockStore{id, conf, newBlockfileMgr(id, conf, indexConfig, dbHandle)}
}
945120
func NewFilespace(path string) (filesystem.Filespace, error) {
	varutil.FixDirPath(&path)
	return filesystem.Filespace(&Filespace{
		path: path,
	}), nil
}
1088733
func New(fn AssetFunc, aliases map[string]string) *Assets {
	return &Assets{
		assetFn: fn,
		aliases: aliases,
		cache:   make(map[string][]byte),
	}
}
536252
func fsNew(path string) (Client, *probe.Error) {
	if strings.TrimSpace(path) == "" {
		return nil, probe.NewError(EmptyPath{})
	}
	return &fsClient{
		PathURL: newClientURL(normalizePath(path)),
	}, nil
}
1892
func NewFileSystemAPIServer(store store.GroupStore) *FileSystemAPIServer {
	s := new(FileSystemAPIServer)
	s.gstore = store
	return s
}
289237
func newCache(config CacheConfig) (*diskCache, error) {
	var cfsObjects []*cacheFSObjects
	ctx := logger.SetReqInfo(context.Background(), &logger.ReqInfo{})
	formats, err := loadAndValidateCacheFormat(ctx, config.Drives)
	if err != nil {
		return nil, err
	}
	for i, dir := range config.Drives {
		// skip cacheFSObjects creation for cache drives missing a format.json
		if formats[i] == nil {
			cfsObjects = append(cfsObjects, nil)
			continue
		}
		if err := checkAtimeSupport(dir); err != nil {
			return nil, errors.New("Atime support required for disk caching")
		}
		cache, err := newCacheFSObjects(dir, config.Expiry, config.MaxUse)
		if err != nil {
			return nil, err
		}
		// Start the purging go-routine for entries that have expired
		go cache.purge()

		// Start trash purge routine for deleted buckets.
		go cache.purgeTrash()

		cfsObjects = append(cfsObjects, cache)
	}
	return &diskCache{cfs: cfsObjects}, nil
}