PortForward to a container.

@param namespace The namespace of the Pod
@param name The name of the Pod
@param ports The ports to forward
@return The result of the Port Forward request.
542553
public PortForwardResult forward(String namespace, String name, List<Integer> ports)
      throws ApiException, IOException {
    String path = makePath(namespace, name);
    WebSocketStreamHandler handler = new WebSocketStreamHandler();
    PortForwardResult result = new PortForwardResult(handler, ports);
    List<Pair> queryParams = new ArrayList<>();
    for (Integer port : ports) {
      queryParams.add(new Pair("ports", port.toString()));
    }
    WebSockets.stream(path, "GET", queryParams, apiClient, handler);

    // Wait for streams to start.
    result.init();

    return result;
  }
804625
public void createContainer(String container) {

        ContainerController controller = this.platformContainers.get(container);
        if (controller == null) {

            // TODO make this configurable
            Profile p = new ProfileImpl();
            p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID);
            p.setParameter(Profile.MAIN_HOST, MAIN_HOST);
            p.setParameter(Profile.MAIN_PORT, MAIN_PORT);
            p.setParameter(Profile.LOCAL_HOST, MAIN_HOST);
            int port = Integer.parseInt(MAIN_PORT);
            port = port + 1 + this.platformContainers.size();
            p.setParameter(Profile.LOCAL_PORT, Integer.toString(port));
            p.setParameter(Profile.CONTAINER_NAME, container);
            logger.fine("Creating container " + container + "...");
            ContainerController agentContainer = this.runtime
                    .createAgentContainer(p);
            this.platformContainers.put(container, agentContainer);
            logger.fine("Container " + container + " created successfully.");
        } else {
            logger.fine("Container " + container + " is already created.");
        }

    }
783917
private Map<String, List<PortBinding>> portBindings() {
    final Map<String, List<PortBinding>> bindings = Maps.newHashMap();
    for (final Map.Entry<String, PortMapping> e : job.getPorts().entrySet()) {
      final PortMapping mapping = e.getValue();
      final Integer jobDefinedExtPort = mapping.getExternalPort();

      // If the job didn't specify an external port, use dynamically allocated ports
      final String externalPort = jobDefinedExtPort == null
                                  ? ports.get(e.getKey()).toString() : jobDefinedExtPort.toString();

      final PortBinding binding = PortBinding.of(mapping.getIp(), externalPort);
      final String entry = containerPort(mapping.getInternalPort(), mapping.getProtocol());
      bindings.put(entry, Collections.singletonList(binding));
    }
    return bindings;
  }
974943
public function forward(ConnectionInterface $connection, $forwardAddress, $forwardPort, $protocolVersion = 2)
    {
        if ($connection instanceof PortConnection) {
            $sourceAddress = $connection->getSourceAddress();
            $sourcePort = $connection->getSourcePort();
            $targetAddress = $connection->getTargetAddress();
            $targetPort = $connection->getTargetPort();
        } elseif ($connection instanceof Connection) {
            list($sourceAddress, $sourcePort) = explode(':', stream_socket_get_name($connection->stream, true));
            list($targetAddress, $targetPort) = explode(':', stream_socket_get_name($connection->stream, false));
        } else {
            throw new \InvalidArgumentException("This connection type is not supported.");
        }

        $connection->pause();

        $header = Header::createForward4($sourceAddress, $sourcePort, $targetAddress, $targetPort, $protocolVersion);
        /** @var Promise $promise */
        $promise = $this->connector->create($forwardAddress, $forwardPort);
        return $promise
            ->then(function(Stream $forwardedConnection) use (
                $connection, $header,
                $sourceAddress, $sourcePort,
                $targetAddress, $targetPort
            ) {
                $forwardedConnection->pause();
                $forwardedConnection->getBuffer()->once('full-drain', function() use ($connection, $forwardedConnection) {
                    $this->emit('forward', [$connection, $forwardedConnection]);
                    $connection->pipe($forwardedConnection);
                    $forwardedConnection->pipe($connection);
                    $connection->resume();
                    $forwardedConnection->resume();
                });
                $forwardedConnection->write($header);

        });
    }
784746
public static Container findContainerByIdOrByName( String name, DockerClient dockerClient ) {

		Container result = null;
		List<Container> containers = dockerClient.listContainersCmd().withShowAll( true ).exec();
		for( Container container : containers ) {
			List<String> names = Arrays.asList( container.getNames());

			// Docker containers are prefixed with '/'.
			// At least, those we created, since their parent is the Docker daemon.
			if( container.getId().equals( name )
					|| names.contains( "/" + name )) {
				result = container;
				break;
			}
		}

		return result;
	}
994132
private ContainerInfo getContainerInfo(String name) {

        if (!m_containerInfos.containsKey(name)) {
            m_containerInfos.put(name, new ContainerInfo(name));
        }
        return m_containerInfos.get(name);
    }
1201115
public DatanodeRegistration getDNRegistrationForNS(int namespaceId) 
  throws IOException {
    NamespaceService nsos = namespaceManager.get(namespaceId);
    if(nsos==null || nsos.getNsRegistration()==null) {
      throw new IOException("cannot find NSOfferService for namespaceId="+namespaceId);
    }
    return nsos.getNsRegistration();
  }
387676
function Namespace(server, name){
  this.name = name;
  this.server = server;
  this.sockets = {};
  this.connected = {};
  this.fns = [];
  this.ids = 0;
  this.rooms = [];
  this.flags = {};
  this.initAdapter();
}
44619
public static AltsServerBuilder forPort(int port) {
    NettyServerBuilder nettyDelegate = NettyServerBuilder.forAddress(new InetSocketAddress(port));
    return new AltsServerBuilder(nettyDelegate);
  }
123547
func (r *RemoteRuntimeService) PortForward(req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {
	ctx, cancel := getContextWithTimeout(r.timeout)
	defer cancel()

	resp, err := r.runtimeClient.PortForward(ctx, req)
	if err != nil {
		klog.Errorf("PortForward %s from runtime service failed: %v", req.PodSandboxId, err)
		return nil, err
	}

	if resp.Url == "" {
		errorMessage := "URL is not set"
		klog.Errorf("Exec failed: %s", errorMessage)
		return nil, errors.New(errorMessage)
	}

	return resp, nil
}
973262
def def_forward(mappings, *names)
      if mappings.instance_of? Hash
        mappings.each do |method_name, target|
          define_singleton_method method_name do |*args, &block|
            self.config = config.public_send(target, *args, &block)
          end
        end
      else
        def_forward([mappings, *names].map{|name| {name => name}}.inject(:merge))
      end
    end
281247
public boolean hasExtension(String namespace) {
        synchronized (packetExtensions) {
            for (ExtensionElement packetExtension : packetExtensions.values()) {
                if (packetExtension.getNamespace().equals(namespace)) {
                    return true;
                }
            }
        }
        return false;
    }
539066
func (t *Tunnel) ForwardPort() error {
	// Build a url to the portforward endpoint
	// example: http://localhost:8080/api/v1/namespaces/helm/pods/tiller-deploy-9itlq/portforward
	u := t.client.Post().
		Resource("pods").
		Namespace(t.Namespace).
		Name(t.PodName).
		SubResource("portforward").URL()

	transport, upgrader, err := spdy.RoundTripperFor(t.config)
	if err != nil {
		return err
	}
	dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", u)

	local, err := getAvailablePort()
	if err != nil {
		return fmt.Errorf("could not find an available port: %s", err)
	}
	t.Local = local

	ports := []string{fmt.Sprintf("%d:%d", t.Local, t.Remote)}

	pf, err := portforward.New(dialer, ports, t.stopChan, t.readyChan, t.Out, t.Out)
	if err != nil {
		return err
	}

	errChan := make(chan error)
	go func() {
		errChan <- pf.ForwardPorts()
	}()

	select {
	case err = <-errChan:
		return fmt.Errorf("forwarding ports: %v", err)
	case <-pf.Ready:
		return nil
	}
}
594115
public static ImmutableSortedSet<String> hosts(int...ports) {
        if (ports.length == 0) {
            return ImmutableSortedSet.of(
                    HostAndPort.fromParts("", Constants.DEFAULT_INTERNAL_PORT).toString());
        }
        ImmutableSortedSet.Builder<String> sbld = ImmutableSortedSet.naturalOrder();
        for (int p: ports) {
            sbld.add(HostAndPort.fromParts("", p).toString());
        }
        return sbld.build();
    }
945381
func (o PortForwardOptions) RunPortForward() error {
	pod, err := o.PodClient.Pods(o.Namespace).Get(o.PodName, metav1.GetOptions{})
	if err != nil {
		return err
	}

	if pod.Status.Phase != corev1.PodRunning {
		return fmt.Errorf("unable to forward port because pod is not running. Current status=%v", pod.Status.Phase)
	}

	signals := make(chan os.Signal, 1)
	signal.Notify(signals, os.Interrupt)
	defer signal.Stop(signals)

	go func() {
		<-signals
		if o.StopChannel != nil {
			close(o.StopChannel)
		}
	}()

	req := o.RESTClient.Post().
		Resource("pods").
		Namespace(o.Namespace).
		Name(pod.Name).
		SubResource("portforward")

	return o.PortForwarder.ForwardPorts("POST", req.URL(), o)
}
370835
func (f *portForwarder) ForwardPorts(ports []string, stopChan <-chan struct{}) error {
	req := f.Client.CoreV1().RESTClient().Post().
		Resource("pods").
		Namespace(f.Namespace).
		Name(f.PodName).
		SubResource("portforward")

	transport, upgrader, err := spdy.RoundTripperFor(f.Config)
	dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", req.URL())

	// TODO: Make os.Stdout/Stderr configurable
	readyChan := make(chan struct{})
	fw, err := portforward.New(dialer, ports, stopChan, readyChan, f.Out, f.ErrOut)
	if err != nil {
		return err
	}
	errChan := make(chan error)
	go func() { errChan <- fw.ForwardPorts() }()
	select {
	case <-readyChan:
		return nil
	case err = <-errChan:
		return err
	}
}
19510
func PortForwardLocation(
	getter ResourceGetter,
	connInfo client.ConnectionInfoGetter,
	ctx context.Context,
	name string,
	opts *api.PodPortForwardOptions,
) (*url.URL, http.RoundTripper, error) {
	pod, err := getPod(getter, ctx, name)
	if err != nil {
		return nil, nil, err
	}

	nodeName := types.NodeName(pod.Spec.NodeName)
	if len(nodeName) == 0 {
		// If pod has not been assigned a host, return an empty location
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("pod %s does not have a host assigned", name))
	}
	nodeInfo, err := connInfo.GetConnectionInfo(ctx, nodeName)
	if err != nil {
		return nil, nil, err
	}
	params := url.Values{}
	if err := streamParams(params, opts); err != nil {
		return nil, nil, err
	}
	loc := &url.URL{
		Scheme:   nodeInfo.Scheme,
		Host:     net.JoinHostPort(nodeInfo.Hostname, nodeInfo.Port),
		Path:     fmt.Sprintf("/portForward/%s/%s", pod.Namespace, pod.Name),
		RawQuery: params.Encode(),
	}
	return loc, nodeInfo.Transport, nil
}