// LaunchRemoteEnforcer prepares the environment and launches the process. If the process
// is already launched, it will notify the caller, so that it can avoid any
// new initialization.
774326
func (p *RemoteMonitor) LaunchRemoteEnforcer(
	contextID string,
	refPid int,
	refNSPath string,
	arg string,
	statsServerSecret string,
	procMountPoint string,
) (bool, error) {

	// Locking here to get the procesinfo to avoid race conditions
	// where multiple LaunchProcess happen for the same context.
	p.Lock()
	if _, err := p.activeProcesses.Get(contextID); err == nil {
		p.Unlock()
		return false, nil
	}

	procInfo := &processInfo{
		contextID: contextID,
	}
	p.activeProcesses.AddOrUpdate(contextID, procInfo)
	p.Unlock()

	// We will lock the procInfo here, so a kill will have to wait and avoid any race.
	procInfo.Lock()
	defer procInfo.Unlock()

	var err error
	defer func() {
		// If we encoutered an error we remove it from the cache. We will
		// not be monitoring it any more. Caller is responsible for re-launching.
		if err != nil {
			p.Lock()
			defer p.Unlock()
			p.activeProcesses.Remove(contextID) // nolint errcheck
		}
	}()

	// We check if the NetNsPath was given as parameter.
	// If it was we will use it. Otherwise we will determine it based on the PID.
	nsPath := refNSPath
	if refNSPath == "" {
		nsPath = filepath.Join(procMountPoint, strconv.Itoa(refPid), "ns/net")
	}

	var hoststat os.FileInfo
	if hoststat, err = os.Stat(filepath.Join(procMountPoint, "1/ns/net")); err != nil {
		return false, err
	}

	var pidstat os.FileInfo
	if pidstat, err = os.Stat(nsPath); err != nil {
		return false, fmt.Errorf("container pid %d not found: %s", refPid, err)
	}

	if pidstat.Sys().(*syscall.Stat_t).Ino == hoststat.Sys().(*syscall.Stat_t).Ino {
		err = fmt.Errorf("refused to launch a remote enforcer in host namespace")
		return false, err
	}

	if _, err = os.Stat(p.netNSPath); err != nil {
		err = os.MkdirAll(p.netNSPath, os.ModeDir)
		if err != nil {
			zap.L().Warn("could not create directory netns directory", zap.Error(err))
		}
	}

	// A symlink is created from /var/run/netns/<context> to the NetNSPath
	contextFile := filepath.Join(p.netNSPath, strings.Replace(contextID, "/", "_", -1))
	// Remove the context file if it already exists.
	if removeErr := os.RemoveAll(contextFile); err != nil {
		zap.L().Warn("Failed to remove namespace link",
			zap.Error(removeErr))
	}

	if err = os.Symlink(nsPath, contextFile); err != nil {
		zap.L().Warn("Failed to create symlink for use by ip netns", zap.Error(err))
	}

	cmd := p.getLaunchProcessCmd(p.remoteEnforcerTempBuildPath, p.remoteEnforcerBuildName, arg)

	if err = p.pollStdOutAndErr(cmd, contextID); err != nil {
		return false, err
	}

	var randomkeystring string
	randomkeystring, err = crypto.GenerateRandomString(secretLength)
	if err != nil {
		// This is a more serious failure. We can't reliably control the remote enforcer
		return false, fmt.Errorf("unable to generate secret: %s", err)
	}

	// Start command
	newEnvVars := p.getLaunchProcessEnvVars(
		procMountPoint,
		contextID,
		randomkeystring,
		statsServerSecret,
		refPid,
		refNSPath,
	)
	cmd.Env = append(os.Environ(), newEnvVars...)

	if err = cmd.Start(); err != nil {
		// Cleanup resources
		if err1 := os.Remove(contextFile); err1 != nil {
			zap.L().Warn("Failed to clean up netns path", zap.Error(err1))
		}
		return false, fmt.Errorf("unable to start enforcer binary: %s", err)
	}

	procInfo.process = cmd.Process

	if err = p.rpc.NewRPCClient(contextID, contextID2SocketPath(contextID), randomkeystring); err != nil {
		return false, fmt.Errorf("failed to established rpc channel: %s", err)
	}

	go func() {
		status := cmd.Wait()
		p.childExitStatus <- exitStatus{
			process:    cmd.Process.Pid,
			contextID:  contextID,
			exitStatus: status,
		}
	}()

	return true, nil
}
283884
func (f *FSNotifications) LaunchProcessor(ctx context.Context) {
	f.notificationMutex.Lock()
	defer f.notificationMutex.Unlock()

	f.log.CDebugf(ctx, "Launching notifications channel")
	// The notifications channel needs to have "infinite" capacity,
	// because otherwise we risk a deadlock between libkbfs and
	// libfs.  The notification processor sends invalidates to the
	// kernel.  In osxfuse 3.X, the kernel can call back into userland
	// during an invalidate (a GetAttr()) call, which in turn takes
	// locks within libkbfs.  So if libkbfs ever gets blocked while
	// trying to enqueue a notification (while it is holding locks),
	// we could have a deadlock.  Yes, if there are too many
	// outstanding notifications we'll run out of memory and crash,
	// but otherwise we risk deadlock.  Which is worse?
	f.notifications = channels.NewInfiniteChannel()

	// start the notification processor
	go f.processNotifications(ctx)
}
1049693
func (s *Service) DynoRestart(ctx context.Context, appIdentity string, dynoIdentity string) (DynoRestartResult, error) {
	var dyno DynoRestartResult
	return dyno, s.Delete(ctx, &dyno, fmt.Sprintf("/apps/%v/dynos/%v", appIdentity, dynoIdentity))
}
25690
func NewRemote(
	sess *protos.Session,
	reply string,
	rpcClient cluster.RPCClient,
	encoder codec.PacketEncoder,
	serializer serialize.Serializer,
	serviceDiscovery cluster.ServiceDiscovery,
	frontendID string,
	messageEncoder message.Encoder,
) (*Remote, error) {
	a := &Remote{
		chDie:            make(chan struct{}),
		reply:            reply, // TODO this is totally coupled with NATS
		serializer:       serializer,
		encoder:          encoder,
		rpcClient:        rpcClient,
		serviceDiscovery: serviceDiscovery,
		frontendID:       frontendID,
		messageEncoder:   messageEncoder,
	}

	// binding session
	s := session.New(a, false, sess.GetUid())
	s.SetFrontendData(frontendID, sess.GetId())
	err := s.SetDataEncoded(sess.GetData())
	if err != nil {
		return nil, err
	}
	a.Session = s

	return a, nil
}
653023
func (impl *adminImpl) LaunchJob(c context.Context, cfg *api.JobConfig) (*api.JobID, error) {
	def, ok := mappers[cfg.Kind] // see mappers.go
	if !ok {
		return nil, status.Errorf(codes.InvalidArgument, "unknown mapper kind")
	}

	cfgBlob, err := proto.Marshal(cfg)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to marshal JobConfig - %s", err)
	}

	launchCfg := def.Config
	launchCfg.Mapper = def.mapperID()
	launchCfg.Params = cfgBlob

	jid, err := impl.ctl.LaunchJob(c, &launchCfg)
	if err != nil {
		return nil, toStatus(err)
	}

	return &api.JobID{JobId: int64(jid)}, nil
}
905563
func (m *MockRemoteIntf) InitEnforcer(req rpcwrapper.Request, resp *rpcwrapper.Response) error {
	ret := m.ctrl.Call(m, "InitEnforcer", req, resp)
	ret0, _ := ret[0].(error)
	return ret0
}
251405
func (m *MockProcessManager) KillRemoteEnforcer(contextID string, force bool) error {
	ret := m.ctrl.Call(m, "KillRemoteEnforcer", contextID, force)
	ret0, _ := ret[0].(error)
	return ret0
}
448705
func (c *Client) CreateRemoteCluster(rc services.RemoteCluster) error {
	data, err := services.MarshalRemoteCluster(rc)
	if err != nil {
		return trace.Wrap(err)
	}
	args := &createRemoteClusterRawReq{
		RemoteCluster: data,
	}
	_, err = c.PostJSON(c.Endpoint("remoteclusters"), args)
	return trace.Wrap(err)
}
271574
func NewEnforcerSafe(params ...interface{}) (e *Enforcer, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", r)
			e = nil
		}
	}()

	e = NewEnforcer(params...)
	err = nil
	return
}
756825
func Launch(cmd []string, wd string, foreground bool, _ []string) (*Process, error) {
	return nil, ErrNativeBackendDisabled
}
232929
func remoteCreateCallback(cremote unsafe.Pointer, crepo unsafe.Pointer, cname, curl *C.char, payload unsafe.Pointer) C.int {
	name := C.GoString(cname)
	url := C.GoString(curl)
	repo := newRepositoryFromC((*C.git_repository)(crepo))
	// We don't own this repository, so make sure we don't try to free it
	runtime.SetFinalizer(repo, nil)

	if opts, ok := pointerHandles.Get(payload).(CloneOptions); ok {
		remote, err := opts.RemoteCreateCallback(repo, name, url)
		// clear finalizer as the calling C function will
		// free the remote itself
		runtime.SetFinalizer(remote, nil)

		if err == ErrOk && remote != nil {
			cptr := (**C.git_remote)(cremote)
			*cptr = remote.ptr
		} else if err == ErrOk && remote == nil {
			panic("no remote created by callback")
		}

		return C.int(err)
	} else {
		panic("invalid remote create callback")
	}
}
812317
func (c *RemoteEndpointsCommandBase) NewRemoteEndpointsAPI(controllerName string) (*applicationoffers.Client, error) {
	root, err := c.CommandBase.NewAPIRoot(c.ClientStore(), controllerName, "")
	if err != nil {
		return nil, err
	}
	return applicationoffers.NewClient(root), nil
}
166840
func NoConsensusLauncher(kern *Kernel) process.Launcher {
	return process.Launcher{
		Name:    NoConsensusProcessName,
		Enabled: kern.Node == nil,
		Launch: func() (process.Process, error) {
			accountState := kern.State
			nameRegState := kern.State
			kern.Service = rpc.NewService(accountState, nameRegState, kern.Blockchain, kern.State, nil, kern.Logger)
			// TimeoutFactor scales in units of seconds
			blockDuration := time.Duration(kern.timeoutFactor * float64(time.Second))
			//proc := abci.NewProcess(kern.checker, kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic)
			proc := abci.NewProcess(kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic)
			// Provide execution accounts against backend state since we will commit immediately
			accounts := execution.NewAccounts(kern.committer, kern.keyClient, AccountsRingMutexCount)
			// Elide consensus and use a CheckTx function that immediately commits any valid transaction
			kern.Transactor = execution.NewTransactor(kern.Blockchain, kern.Emitter, accounts, proc.CheckTx, kern.txCodec,
				kern.Logger)
			return proc, nil
		},
	}
}
105235
func (s *UpdateServiceInput) SetForceNewDeployment(v bool) *UpdateServiceInput {
	s.ForceNewDeployment = &v
	return s
}
250781
func NewRemoteService(
	rpcClient cluster.RPCClient,
	rpcServer cluster.RPCServer,
	sd cluster.ServiceDiscovery,
	encoder codec.PacketEncoder,
	serializer serialize.Serializer,
	router *router.Router,
	messageEncoder message.Encoder,
	server *cluster.Server,
) *RemoteService {
	return &RemoteService{
		services:               make(map[string]*component.Service),
		rpcClient:              rpcClient,
		rpcServer:              rpcServer,
		encoder:                encoder,
		serviceDiscovery:       sd,
		serializer:             serializer,
		router:                 router,
		messageEncoder:         messageEncoder,
		server:                 server,
		remoteBindingListeners: make([]cluster.RemoteBindingListener, 0),
	}
}
1173346
func (s *RemoteEnforcer) SetTargetNetworks(req rpcwrapper.Request, resp *rpcwrapper.Response) error {

	var err error
	if !s.rpcHandle.CheckValidity(&req, s.rpcSecret) {
		resp.Status = "SetTargetNetworks message auth failed" //nolint
		return fmt.Errorf(resp.Status)
	}

	cmdLock.Lock()
	defer cmdLock.Unlock()

	if s.enforcer == nil || s.supervisor == nil {
		return fmt.Errorf(resp.Status)
	}

	payload := req.Payload.(rpcwrapper.SetTargetNetworksPayload)

	// If any error happens, cleanup everything on exit so that we can recover
	// by launcing a new remote.
	defer func() {
		if err != nil {
			s.cleanup()
		}
	}()

	if err = s.enforcer.SetTargetNetworks(payload.Configuration); err != nil {
		return err
	}

	err = s.supervisor.SetTargetNetworks(payload.Configuration)

	return err
}
462076
func InitializeRemoteClient(client *client.Client) {
	managerLock.Lock()
	defer managerLock.Unlock()
	manager[remote] = &zclient{
		client:          client,
		connectionsLock: sync.RWMutex{},
		connections:     make(map[string]*zconn),
	}
}