// Attach to an existing process with the given PID. Once attached, if
// the DWARF information cannot be found in the binary, Delve will look
// for external debug files in the directories passed in.
506184
func Attach(pid int, debugInfoDirs []string) (*Process, error) {
	dbp := New(pid)
	dbp.common = proc.NewCommonProcess(true)

	var err error
	dbp.execPtraceFunc(func() { err = PtraceAttach(dbp.pid) })
	if err != nil {
		return nil, err
	}
	_, _, err = dbp.wait(dbp.pid, 0)
	if err != nil {
		return nil, err
	}

	err = dbp.initialize(findExecutable("", dbp.pid), debugInfoDirs)
	if err != nil {
		dbp.Detach(false)
		return nil, err
	}
	return dbp, nil
}
904681
func (c *RPCServer) AttachedToExistingProcess(arg AttachedToExistingProcessIn, out *AttachedToExistingProcessOut) error {
	if c.config.AttachPid != 0 {
		out.Answer = true
	}
	return nil
}
1215906
func (a *azureDiskAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {
	volumeSource, _, err := getVolumeSource(spec)
	if err != nil {
		klog.Warningf("failed to get azure disk spec (%v)", err)
		return "", err
	}

	diskController, err := getDiskController(a.plugin.host)
	if err != nil {
		return "", err
	}

	lun, err := diskController.GetDiskLun(volumeSource.DiskName, volumeSource.DataDiskURI, nodeName)
	if err == cloudprovider.InstanceNotFound {
		// Log error and continue with attach
		klog.Warningf(
			"Error checking if volume is already attached to current node (%q). Will continue and try attach anyway. err=%v",
			nodeName, err)
	}

	if err == nil {
		// Volume is already attached to node.
		klog.V(2).Infof("Attach operation is successful. volume %q is already attached to node %q at lun %d.", volumeSource.DiskName, nodeName, lun)
	} else {
		klog.V(2).Infof("GetDiskLun returned: %v. Initiating attaching volume %q to node %q.", err, volumeSource.DataDiskURI, nodeName)

		isManagedDisk := (*volumeSource.Kind == v1.AzureManagedDisk)
		err = diskController.AttachDisk(isManagedDisk, volumeSource.DiskName, volumeSource.DataDiskURI, nodeName, compute.CachingTypes(*volumeSource.CachingMode))
		if err == nil {
			klog.V(2).Infof("Attach operation successful: volume %q attached to node %q.", volumeSource.DataDiskURI, nodeName)
		} else {
			klog.V(2).Infof("Attach volume %q to instance %q failed with %v", volumeSource.DataDiskURI, nodeName, err)
			return "", fmt.Errorf("Attach volume %q to instance %q failed with %v", volumeSource.DiskName, nodeName, err)
		}
	}

	return strconv.Itoa(int(lun)), err
}
103484
func (d Docker) ContainerAttach(cId string, stdin io.ReadCloser, stdout, stderr io.Writer, stream bool) error {
	<-d.hyper.Ready

	err := d.Daemon.Attach(stdin, ioutils.NopWriteCloser(stdout), cId)
	if err != nil {
		return err
	}

	code, err := d.Daemon.ExitCode(cId, "")
	if err != nil {
		return err
	}

	if code == 0 {
		return nil
	}

	return &jsonmessage.JSONError{
		Message: fmt.Sprintf("The container '%s' returned a non-zero code: %d", cId, code),
		Code:    code,
	}
}
1031270
func (c *ContainerIO) Attach(opts AttachOptions) {
	var wg sync.WaitGroup
	key := utils.GenerateID()
	stdinKey := streamKey(c.id, "attach-"+key, Stdin)
	stdoutKey := streamKey(c.id, "attach-"+key, Stdout)
	stderrKey := streamKey(c.id, "attach-"+key, Stderr)

	var stdinStreamRC io.ReadCloser
	if c.stdin != nil && opts.Stdin != nil {
		// Create a wrapper of stdin which could be closed. Note that the
		// wrapper doesn't close the actual stdin, it only stops io.Copy.
		// The actual stdin will be closed by stream server.
		stdinStreamRC = cioutil.NewWrapReadCloser(opts.Stdin)
		wg.Add(1)
		go func() {
			if _, err := io.Copy(c.stdin, stdinStreamRC); err != nil {
				logrus.WithError(err).Errorf("Failed to pipe stdin for container attach %q", c.id)
			}
			logrus.Infof("Attach stream %q closed", stdinKey)
			if opts.StdinOnce && !opts.Tty {
				// Due to kubectl requirements and current docker behavior, when (opts.StdinOnce &&
				// opts.Tty) we have to close container stdin and keep stdout and stderr open until
				// container stops.
				c.stdin.Close()
				// Also closes the containerd side.
				if err := opts.CloseStdin(); err != nil {
					logrus.WithError(err).Errorf("Failed to close stdin for container %q", c.id)
				}
			} else {
				if opts.Stdout != nil {
					c.stdoutGroup.Remove(stdoutKey)
				}
				if opts.Stderr != nil {
					c.stderrGroup.Remove(stderrKey)
				}
			}
			wg.Done()
		}()
	}

	attachStream := func(key string, close <-chan struct{}) {
		<-close
		logrus.Infof("Attach stream %q closed", key)
		// Make sure stdin gets closed.
		if stdinStreamRC != nil {
			stdinStreamRC.Close()
		}
		wg.Done()
	}

	if opts.Stdout != nil {
		wg.Add(1)
		wc, close := cioutil.NewWriteCloseInformer(opts.Stdout)
		c.stdoutGroup.Add(stdoutKey, wc)
		go attachStream(stdoutKey, close)
	}
	if !opts.Tty && opts.Stderr != nil {
		wg.Add(1)
		wc, close := cioutil.NewWriteCloseInformer(opts.Stderr)
		c.stderrGroup.Add(stderrKey, wc)
		go attachStream(stderrKey, close)
	}
	wg.Wait()
}
1116468
func (a *HostAgent) AttachAndRun(dockerID string, command []string) ([]byte, error) {
	return utils.AttachAndRun(dockerID, command)
}
736753
func PID(pid int) ([]Info, error) {
	f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid))
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return parseInfoFile(f)
}
942962
func (s *RPCServer) ProcessPid(arg ProcessPidIn, out *ProcessPidOut) error {
	out.Pid = s.debugger.ProcessPid()
	return nil
}
1137613
func (c *Host) Attach(req *host.AttachReq, wait bool) (AttachClient, error) {
	rwc, err := c.c.Hijack("POST", "/attach", http.Header{"Upgrade": {"flynn-attach/0"}}, req)
	if err != nil {
		return nil, err
	}

	attachState := make([]byte, 1)
	if _, err := rwc.Read(attachState); err != nil {
		rwc.Close()
		return nil, err
	}

	handleState := func() error {
		switch attachState[0] {
		case host.AttachSuccess:
			return nil
		case host.AttachError:
			errBytes, err := ioutil.ReadAll(rwc)
			rwc.Close()
			if err != nil {
				return err
			}
			if len(errBytes) >= 4 {
				errBytes = errBytes[4:]
			}
			errMsg := string(errBytes)
			switch errMsg {
			case host.ErrJobNotRunning.Error():
				return host.ErrJobNotRunning
			case host.ErrAttached.Error():
				return host.ErrAttached
			}
			return errors.New(errMsg)
		default:
			rwc.Close()
			return fmt.Errorf("cluster: unknown attach state: %d", attachState)
		}
	}

	if attachState[0] == host.AttachWaiting {
		if !wait {
			rwc.Close()
			return nil, ErrWouldWait
		}
		wait := func() error {
			if _, err := rwc.Read(attachState); err != nil {
				rwc.Close()
				return err
			}
			return handleState()
		}
		c := &attachClient{
			conn: rwc,
			wait: wait,
			w:    bufio.NewWriter(rwc),
		}
		c.mtx.Lock()
		return c, nil
	}

	return NewAttachClient(rwc), handleState()
}
427583
func (daemon *Daemon) killPossiblyDeadProcess(container *containerpkg.Container, sig int) error {
	err := daemon.killWithSignal(container, sig)
	if errdefs.IsNotFound(err) {
		e := errNoSuchProcess{container.GetPID(), sig}
		logrus.Debug(e)
		return e
	}
	return err
}
1262213
func (pid *PID) Load() error {
	data, err := ioutil.ReadFile(pid.Path())
	if err != nil {
		return fmt.Errorf("no PID file exists at %s; process not running?", pid.Path())
	}

	return json.Unmarshal(data, &pid)
}
1144182
func (e *endpoint) Attach(dispatcher stack.NetworkDispatcher) {
	e.dispatcher = dispatcher
	e.lower.Attach(e)
}
544402
func (a *ALIVolumes) AttachVolume(volume *Volume) error {
	// TODO: what if this volume has already been attached to another instance?
	// Aliyun Disk can only be attached to one instance
	if volume.LocalDevice == "" && volume.AttachedTo == "" {
		attachDiskArgs := &ecs.AttachDiskArgs{
			InstanceId: a.instanceId,
			DiskId:     volume.ID,
			// TODO: DeleteWithInstance?
		}
		err := a.client.AttachDisk(attachDiskArgs)
		if err != nil {
			return fmt.Errorf("error attach disk %q: %v", volume.ID, err)
		}

		// TODO: Do we have to wait for attach to complete?
		// retrieve device info
		args := &ecs.DescribeDisksArgs{
			RegionId: common.Region(a.region),
			ZoneId:   a.zone,
			DiskIds:  []string{volume.ID},
		}
		disks, _, err := a.client.DescribeDisks(args)
		if err != nil || len(disks) == 0 {
			return fmt.Errorf("error querying Aliyun disk %q: %v", volume.ID, err)
		}

		volume.LocalDevice = disks[0].Device
		volume.AttachedTo = a.instanceId
	} else if volume.AttachedTo != a.instanceId {
		return fmt.Errorf("cannot reattach an attached disk without detaching it first")
	}
	return nil
}
744918
func (client *Client) Attach(cid string, options *AttachOptions) (io.ReadCloser, error) {
	values := url.Values{}
	add := func(name string, val bool) {
		values.Add(name, strconv.FormatBool(val))
	}
	add("logs", options.Logs)
	add("stream", options.Stream)
	add("stdin", options.Stdin)
	add("stdout", options.Stdout)
	add("stderr", options.Stderr)

	p := fmt.Sprintf("/containers/%s/attach?%s", cid, values.Encode())
	req, err := http.NewRequest("POST", client.URL.String()+p, nil)
	if err != nil {
		return nil, fmt.Errorf("could not construct request to docker")
	}
	resp, err := client.HTTPClient.Do(req)
	if err != nil {
		if !strings.Contains(err.Error(), "connection refused") && client.TLSConfig == nil {
			return nil, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err)
		}
		return nil, err
	}
	if resp.StatusCode == http.StatusOK {
		return resp.Body, nil
	}

	resp.Body.Close()
	switch resp.StatusCode {
	case http.StatusSwitchingProtocols:
		return nil, fmt.Errorf("docker: attach: did not send websocket request but got 101 back")
	case http.StatusBadRequest:
		// Probably shouldn't get here
		return nil, fmt.Errorf("docker: attach: invalid request parameters")
	case http.StatusInternalServerError:
		return nil, fmt.Errorf("docker: attach: internal server error")
	default:
		return nil, fmt.Errorf("docker: attach: unexpected status code %s", resp.Status)
	}
}
656055
func (vs *VSphere) AttachDisk(vmDiskPath string, storagePolicyName string, nodeName k8stypes.NodeName) (diskUUID string, err error) {
	attachDiskInternal := func(vmDiskPath string, storagePolicyName string, nodeName k8stypes.NodeName) (diskUUID string, err error) {
		if nodeName == "" {
			nodeName = convertToK8sType(vs.hostName)
		}
		// Create context
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		vsi, err := vs.getVSphereInstance(nodeName)
		if err != nil {
			return "", err
		}
		// Ensure client is logged in and session is valid
		err = vs.nodeManager.vcConnect(ctx, vsi)
		if err != nil {
			return "", err
		}

		vm, err := vs.getVMFromNodeName(ctx, nodeName)
		if err != nil {
			klog.Errorf("Failed to get VM object for node: %q. err: +%v", convertToString(nodeName), err)
			return "", err
		}

		diskUUID, err = vm.AttachDisk(ctx, vmDiskPath, &vclib.VolumeOptions{SCSIControllerType: vclib.PVSCSIControllerType, StoragePolicyName: storagePolicyName})
		if err != nil {
			klog.Errorf("Failed to attach disk: %s for node: %s. err: +%v", vmDiskPath, convertToString(nodeName), err)
			return "", err
		}
		return diskUUID, nil
	}
	requestTime := time.Now()
	diskUUID, err = attachDiskInternal(vmDiskPath, storagePolicyName, nodeName)
	if err != nil {
		if vclib.IsManagedObjectNotFoundError(err) {
			err = vs.nodeManager.RediscoverNode(nodeName)
			if err == nil {
				klog.V(4).Infof("AttachDisk: Found node %q", convertToString(nodeName))
				diskUUID, err = attachDiskInternal(vmDiskPath, storagePolicyName, nodeName)
				klog.V(4).Infof("AttachDisk: Retry: diskUUID %s, err +%v", diskUUID, err)
			}
		}
	}
	klog.V(4).Infof("AttachDisk executed for node %s and volume %s with diskUUID %s. Err: %s", convertToString(nodeName), vmDiskPath, diskUUID, err)
	vclib.RecordvSphereMetric(vclib.OperationAttachVolume, requestTime, err)
	return diskUUID, err
}
684958
func (m *Scheduler) attach(ctx context.Context, task *ecs.Task, stdin io.Reader, stdout, stderr io.Writer) error {
	if a, _ := arn.Parse(aws.StringValue(task.TaskArn)); a != nil {
		fmt.Fprintf(stderr, "Attaching to %s...\r\n", a.Resource)
	}

	descContainerInstanceResp, err := m.ecs.DescribeContainerInstances(&ecs.DescribeContainerInstancesInput{
		Cluster:            task.ClusterArn,
		ContainerInstances: []*string{task.ContainerInstanceArn},
	})
	if err != nil {
		return fmt.Errorf("error describing container instance (%s): %v", aws.StringValue(task.ContainerInstanceArn), err)
	}

	containerInstance := descContainerInstanceResp.ContainerInstances[0]
	descInstanceResp, err := m.ec2.DescribeInstances(&ec2.DescribeInstancesInput{
		InstanceIds: []*string{containerInstance.Ec2InstanceId},
	})
	if err != nil {
		return fmt.Errorf("error describing ec2 instance (%s): %v", aws.StringValue(containerInstance.Ec2InstanceId), err)
	}

	ec2Instance := descInstanceResp.Reservations[0].Instances[0]

	// Wait for the task to start running. It will stay in the
	// PENDING state while the container is being pulled.
	if err := m.ecs.WaitUntilTasksNotPending(&ecs.DescribeTasksInput{
		Cluster: task.ClusterArn,
		Tasks:   []*string{task.TaskArn},
	}); err != nil {
		return fmt.Errorf("error waiting for %s to transition from PENDING state: %s", aws.StringValue(task.TaskArn), err)
	}

	// Open a new connection to the Docker daemon on the EC2
	// instance where the task is running.
	d, err := m.NewDockerClient(ec2Instance)
	if err != nil {
		return fmt.Errorf("error connecting to docker daemon on %s: %v", aws.StringValue(ec2Instance.InstanceId), err)
	}

	// Find the container id for the ECS task.
	containers, err := d.ListContainers(docker.ListContainersOptions{
		All: true,
		Filters: map[string][]string{
			"label": []string{
				fmt.Sprintf("com.amazonaws.ecs.task-arn=%s", aws.StringValue(task.TaskArn)),
				//fmt.Sprintf("com.amazonaws.ecs.container-name", p)
			},
		},
	})
	if err != nil {
		return fmt.Errorf("error listing containers for task: %v", err)
	}

	if len(containers) != 1 {
		return fmt.Errorf("unable to find container for %s running on %s", aws.StringValue(task.TaskArn), aws.StringValue(ec2Instance.InstanceId))
	}

	containerID := containers[0].ID

	if err := d.AttachToContainer(docker.AttachToContainerOptions{
		Container:    containerID,
		InputStream:  stdin,
		OutputStream: stdout,
		ErrorStream:  stderr,
		Logs:         true,
		Stream:       true,
		Stdin:        true,
		Stdout:       true,
		Stderr:       true,
		RawTerminal:  true,
	}); err != nil {
		return fmt.Errorf("error attaching to container (%s): %v", containerID, err)
	}

	return nil
}
1346231
func (n *Node) Attach() (*rpc.Client, error) {
	n.lock.RLock()
	defer n.lock.RUnlock()

	if n.server == nil {
		return nil, ErrNodeStopped
	}
	return rpc.DialInProc(n.inprocHandler), nil
}