// MakeRSync creates an RSync object using string paths,
// inferring most of the configuration
517093
func MakeRSync(
	InputFile,
	Source,
	OutFile string,
	Summary FileSummary,
) (r *RSync, err error) {
	useTempFile := false
	if useTempFile, err = IsSameFile(InputFile, OutFile); err != nil {
		return nil, err
	}

	inputFile, err := os.Open(InputFile)

	if err != nil {
		return
	}

	var out io.WriteCloser
	var outFilename = OutFile
	var copier closer

	if useTempFile {
		out, outFilename, err = getTempFile()

		if err != nil {
			return
		}

		copier = &fileCopyCloser{
			from: outFilename,
			to:   OutFile,
		}
	} else {
		out, err = getOutFile(OutFile)

		if err != nil {
			return
		}

		copier = nullCloser{}
	}

	// blocksource
	var source *blocksources.BlockSourceBase

	resolver := blocksources.MakeFileSizedBlockResolver(
		uint64(Summary.GetBlockSize()),
		Summary.GetFileSize(),
	)

	source = blocksources.NewHttpBlockSource(
		Source,
		DefaultConcurrency,
		resolver,
		&filechecksum.HashVerifier{
			Hash:                md5.New(),
			BlockSize:           Summary.GetBlockSize(),
			BlockChecksumGetter: Summary,
		},
	)

	r = &RSync{
		Input:   inputFile,
		Output:  out,
		Source:  source,
		Summary: Summary,
		OnClose: []closer{
			&fileCloser{inputFile, InputFile},
			&fileCloser{out, outFilename},
			copier,
		},
	}

	return
}
629663
func makeRPCOptions(kind RPCAuthorityKind, opts []RPCOption) (*rpcOptions, error) {
	options := &rpcOptions{kind: kind}
	for _, o := range opts {
		o.apply(options)
	}

	// Set default scopes.
	asSelfOrActorOrProject := options.kind == AsSelf || options.kind == AsActor || options.kind == AsProject
	if asSelfOrActorOrProject && len(options.scopes) == 0 {
		options.scopes = defaultOAuthScopes
	}

	// Validate options.
	if !asSelfOrActorOrProject && len(options.scopes) != 0 {
		return nil, fmt.Errorf("auth: WithScopes can only be used with AsSelf or AsActor authorization kind")
	}
	if options.serviceAccount != "" && options.kind != AsActor {
		return nil, fmt.Errorf("auth: WithServiceAccount can only be used with AsActor authorization kind")
	}
	if options.serviceAccount == "" && options.kind == AsActor {
		return nil, fmt.Errorf("auth: AsActor authorization kind requires WithServiceAccount option")
	}
	if options.delegationToken != "" && options.kind != AsUser {
		return nil, fmt.Errorf("auth: WithDelegationToken can only be used with AsUser authorization kind")
	}
	if len(options.delegationTags) != 0 && options.kind != AsUser {
		return nil, fmt.Errorf("auth: WithDelegationTags can only be used with AsUser authorization kind")
	}
	if len(options.delegationTags) != 0 && options.delegationToken != "" {
		return nil, fmt.Errorf("auth: WithDelegationTags and WithDelegationToken cannot be used together")
	}
	if options.project == "" && options.kind == AsProject {
		return nil, fmt.Errorf("auth: AsProject authorization kind requires WithProject option")
	}

	// Validate 'kind' and pick correct implementation of getRPCHeaders.
	switch options.kind {
	case NoAuth:
		options.getRPCHeaders = noAuthHeaders
	case AsSelf:
		options.getRPCHeaders = asSelfHeaders
	case AsUser:
		options.getRPCHeaders = asUserHeaders
	case AsCredentialsForwarder:
		options.checkCtx = func(c context.Context) error {
			_, err := forwardedCreds(c)
			return err
		}
		options.getRPCHeaders = func(c context.Context, _ string, _ *rpcOptions) (*oauth2.Token, map[string]string, error) {
			tok, err := forwardedCreds(c)
			return tok, nil, err
		}
	case AsActor:
		options.getRPCHeaders = asActorHeaders
	case AsProject:
		options.getRPCHeaders = asProjectHeaders
	default:
		return nil, fmt.Errorf("auth: unknown RPCAuthorityKind %d", options.kind)
	}

	// Default value for "client" field in monitoring metrics.
	if options.monitoringClient == "" {
		options.monitoringClient = "luci-go-server"
	}

	return options, nil
}
587927
func (opts *WriteOptions) SetSync(value bool) {
	C.rocksdb_writeoptions_set_sync(opts.c, boolToChar(value))
}
1158181
func (c *Client) LinodeConfigCreate(linodeID int, kernelID int, label string,
	diskList string, conf LinodeConfigCreateOpts) (configID int, err error) {

	args, err := c.argMarshal(conf)
	if err != nil {
		return 0, err
	}
	args["LinodeID"] = linodeID
	args["KernelID"] = kernelID
	args["Label"] = label
	args["DiskList"] = diskList

	data, err := c.apiCall("linode.config.create", args)
	if err != nil {
		return 0, err
	}

	err = unmarshalSingle(data, "ConfigID", &configID)
	if err != nil {
		return 0, err
	}

	return configID, nil
}
526852
func (helper *CacheHelper) DoResync(resyncEv datasync.ResyncEvent) error {
	var wasError error
	//idx.Put()
	ifaces, found := resyncEv.GetValues()[helper.Prefix]
	if found {
		// Step 1: fill the existing things
		resyncNames := map[string]interface{}{}
		for {
			item, stop := ifaces.GetNext()
			if stop {
				break
			}
			ifaceName, err := helper.ParseName(item.GetKey())
			if err != nil {
				wasError = err
			} else {
				current := proto.Clone(helper.DataPrototype)
				item.GetValue(current)
				helper.IDX.Put(ifaceName, current)
				resyncNames[ifaceName] = nil
			}
		}

		// Step 2:
		existingNames := []string{} //TODO
		for _, existingName := range existingNames {
			if _, found := resyncNames[existingName]; !found {
				helper.IDX.Delete(existingName)
			}
		}
	}
	return wasError
}
1272464
func (s *DataMsgServiceServer) DataResyncs(ctx context.Context, req *msg.DataResyncRequests) (
	*msg.DataResyncReplies, error) {
	resyncs := req.GetDataResyncs()
	if resyncs != nil {
		//TODO propagate event like in Kafka transport

		/*localtxn := syncbase.NewLocalBytesTxn(s.adapter.localtransp.PropagateBytesResync)
		if len(resyncs) == 0 {
			log.Debug("received empty resync => DELETE ALL")
		}
		for _, chReq := range resyncs {
			//TODO chReq.ContentType
			localtxn.Put(chReq.Key, chReq.Content)
		}
		err := localtxn.Commit()*/
		var err error
		if err != nil {
			return &msg.DataResyncReplies{MsgId: replySeq(), Error: &msg.Error{Message: err.Error()} /*TODO all other fields*/}, err
		}

		return &msg.DataResyncReplies{MsgId: replySeq() /*TODO all other fields*/}, nil
	}

	err := errors.New("unexpected place - nil resyncs")
	return &msg.DataResyncReplies{MsgId: replySeq(), Error: &msg.Error{Message: err.Error()} /*TODO all other fields*/}, err
}
752619
func MakeFileFunc(baseDir string, encBase64 bool) function.Function {
	return function.New(&function.Spec{
		Params: []function.Parameter{
			{
				Name: "path",
				Type: cty.String,
			},
		},
		Type: function.StaticReturnType(cty.String),
		Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
			path := args[0].AsString()
			src, err := readFileBytes(baseDir, path)
			if err != nil {
				return cty.UnknownVal(cty.String), err
			}

			switch {
			case encBase64:
				enc := base64.StdEncoding.EncodeToString(src)
				return cty.StringVal(enc), nil
			default:
				if !utf8.Valid(src) {
					return cty.UnknownVal(cty.String), fmt.Errorf("contents of %s are not valid UTF-8; use the filebase64 function to obtain the Base64 encoded contents or the other file functions (e.g. filemd5, filesha256) to obtain file hashing results instead", path)
				}
				return cty.StringVal(string(src)), nil
			}
		},
	})
}
64934
func MakeDirs(conn ZookeeperConnection, path string, makeLastNode bool, aclProvider ACLProvider) error {
	if err := ValidatePath(path); err != nil {
		return err
	}

	pos := 1 // skip first slash, root is guaranteed to exist

	for pos < len(path) {
		if idx := strings.Index(path[pos+1:], PATH_SEPARATOR); idx == -1 {
			if makeLastNode {
				pos = len(path)
			} else {
				return nil
			}
		} else {
			pos += idx + 1
		}

		subPath := path[:pos]

		if exists, _, err := conn.Exists(subPath); err != nil {
			return err
		} else if !exists {
			var acls []zk.ACL

			if aclProvider != nil {
				if acls = aclProvider.GetAclForPath(subPath); len(acls) == 0 {
					acls = aclProvider.GetDefaultAcl()
				}
			}

			if acls == nil {
				acls = OPEN_ACL_UNSAFE
			}

			if _, err := conn.Create(subPath, []byte{}, int32(PERSISTENT), acls); err != nil && err != zk.ErrNodeExists {
				return err
			}
		}
	}

	return nil
}
1330063
func MakeRequestAsync(request rest.Request) (chan *rest.Response, chan error) {
	r := make(chan *rest.Response)
	e := make(chan error)

	go func() {
		response, err := MakeRequestRetry(request)
		if err != nil {
			e <- err
		}
		if response != nil {
			r <- response
		}
	}()

	return r, e
}
229168
func (keys *watchBrokerKeys) resync() error {
	iterators := map[string]datasync.KeyValIterator{}
	for _, keyPrefix := range keys.prefixes {
		it, err := keys.adapter.db.ListValues(keyPrefix)
		if err != nil {
			return errors.WithMessagef(err, "list values for %s failed", keyPrefix)
		}
		iterators[keyPrefix] = NewIterator(it)
	}

	resyncEvent := syncbase.NewResyncEventDB(context.Background(), iterators)

	select {
	case keys.resyncChan <- resyncEvent:
		// ok
	case <-time.After(ResyncAcceptTimeout):
		logrus.DefaultLogger().Warn("Timeout of resync send!")
		return errors.New("resync not accepted in time")
	}

	select {
	case err := <-resyncEvent.DoneChan:
		if err != nil {
			return errors.WithMessagef(err, "resync returned error")
		}
	case <-time.After(ResyncDoneTimeout):
		logrus.DefaultLogger().Warn("Timeout of resync callback!")
	}

	return nil
}
1081021
func (c *client) RepoListSync() ([]*Repo, error) {
	var out []*Repo
	uri := fmt.Sprintf(pathRepos, c.addr)
	err := c.post(uri, nil, &out)
	return out, err
}
261924
func (f *DeltaFIFO) Resync() error {
	f.lock.Lock()
	defer f.lock.Unlock()

	if f.knownObjects == nil {
		return nil
	}

	keys := f.knownObjects.ListKeys()
	for _, k := range keys {
		if err := f.syncKeyLocked(k); err != nil {
			return err
		}
	}
	return nil
}
1258660
func (d *domainClient) MakeSnapshot(ctx context.Context, args *MakeSnapshotArgs) (reply *MakeSnapshotReply, err error) {
	reply = new(MakeSnapshotReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "LayerTree.makeSnapshot", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "LayerTree.makeSnapshot", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "LayerTree", Op: "MakeSnapshot", Err: err}
	}
	return
}
867710
func (m *PodMonitor) Resync(ctx context.Context) error {
	if m.kubeClient == nil {
		return errors.New("pod: client has not been initialized yet")
	}

	return ResyncWithAllPods(ctx, m.kubeClient, m.eventsCh)
}
887147
func hasLocalRsync() bool {
	_, err := exec.LookPath("rsync")
	if err != nil {
		return false
	}
	return true
}
1238068
func SyncConfig(addr string, localDir string) (bool, error) {
	return local.SyncConfig(addr, localDir)
}
401196
func (l *linuxProcessor) Resync(ctx context.Context, e *common.EventInfo) error {

	if e != nil {
		// If its a host service then use pu from eventInfo
		// The code block below assumes that pu is already created
		if e.HostService {
			return l.resyncHostService(ctx, e)
		}
	}

	cgroups := l.netcls.ListAllCgroups("")
	for _, cgroup := range cgroups {

		if _, ok := ignoreNames[cgroup]; ok {
			continue
		}

		isSSHPU := strings.Contains(cgroup, "ssh")
		if l.ssh != isSSHPU {
			continue
		}

		// List all the cgroup processes. If its empty, we can remove it.
		procs, err := l.netcls.ListCgroupProcesses(cgroup)
		if err != nil {
			continue
		}

		// All processes in cgroup have died. Let's clean up.
		if len(procs) == 0 {
			if err := l.netcls.DeleteCgroup(cgroup); err != nil {
				zap.L().Warn("Failed to deleted cgroup",
					zap.String("cgroup", cgroup),
					zap.Error(err),
				)
			}
			continue
		}

		runtime := policy.NewPURuntimeWithDefaults()
		puType := common.LinuxProcessPU
		if l.ssh && isSSHPU {
			puType = common.SSHSessionPU
		}
		runtime.SetPUType(puType)
		runtime.SetOptions(policy.OptionsType{
			CgroupMark: strconv.FormatUint(cgnetcls.MarkVal(), 10),
			CgroupName: cgroup,
		})

		// Processes are still alive. We should enforce policy.
		if err := l.config.Policy.HandlePUEvent(ctx, cgroup, common.EventStart, runtime); err != nil {
			zap.L().Error("Failed to restart cgroup control", zap.String("cgroup ID", cgroup), zap.Error(err))
		}

		if err := l.processLinuxServiceStart(cgroup, nil, runtime); err != nil {
			return err
		}
	}
	return nil
}