• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang nat.ParsePortSpecs函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/docker/go-connections/nat.ParsePortSpecs函数的典型用法代码示例。如果您正苦于以下问题:Golang ParsePortSpecs函数的具体用法?Golang ParsePortSpecs怎么用?Golang ParsePortSpecs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ParsePortSpecs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: ports

func ports(c *config.ServiceConfig) (map[nat.Port]struct{}, nat.PortMap, error) {
	ports, binding, err := nat.ParsePortSpecs(c.Ports)
	if err != nil {
		return nil, nil, err
	}

	exPorts, _, err := nat.ParsePortSpecs(c.Expose)
	if err != nil {
		return nil, nil, err
	}

	for k, v := range exPorts {
		ports[k] = v
	}

	exposedPorts := map[nat.Port]struct{}{}
	for k, v := range ports {
		exposedPorts[nat.Port(k)] = v
	}

	portBindings := nat.PortMap{}
	for k, bv := range binding {
		dcbs := make([]nat.PortBinding, len(bv))
		for k, v := range bv {
			dcbs[k] = nat.PortBinding{HostIP: v.HostIP, HostPort: v.HostPort}
		}
		portBindings[nat.Port(k)] = dcbs
	}
	return exposedPorts, portBindings, nil
}
开发者ID:jainvipin,项目名称:libcompose,代码行数:30,代码来源:convert.go


示例2: TestPort

func TestPort(t *testing.T) {
	portMap, bindingMap, err := nat.ParsePortSpecs([]string{
		"1236:1235/tcp",
		"1237:1235/tcp",
		"2345/udp", "80",
		"127.0.0.1::8080",
		"127.0.0.1:5279:8080",
	})
	if err != nil {
		t.Errorf("Failed to parse ports: %s", err.Error())
	}
	t.Logf("portMap: %s", portMap)
	t.Logf("bindingMap: %s", bindingMap)

	for p := range bindingMap {
		expected := bindingMap[p]
		for i := range expected {
			expected[i].HostIP = ""
		}

		bindings := fromPortbinding(p, bindingMap[p])
		t.Logf("binding: %s", bindings)
		_, outMap, err := nat.ParsePortSpecs(bindings)
		if err != nil {
			t.Errorf("Failed to parse back string bindings: %s", err)
		}
		for op := range outMap {
			assert.Equal(t, outMap[op], bindingMap[op])
		}

	}
}
开发者ID:vmware,项目名称:vic,代码行数:32,代码来源:container_proxy_test.go


示例3: expose

// EXPOSE 6667/tcp 7000/tcp
//
// Expose ports for links and port mappings. This all ends up in
// b.runConfig.ExposedPorts for runconfig.
//
func expose(b *Builder, args []string, attributes map[string]bool, original string) error {
	portsTab := args

	if len(args) == 0 {
		return errAtLeastOneArgument("EXPOSE")
	}

	if err := b.flags.Parse(); err != nil {
		return err
	}

	if b.runConfig.ExposedPorts == nil {
		b.runConfig.ExposedPorts = make(nat.PortSet)
	}

	ports, _, err := nat.ParsePortSpecs(portsTab)
	if err != nil {
		return err
	}

	// instead of using ports directly, we build a list of ports and sort it so
	// the order is consistent. This prevents cache burst where map ordering
	// changes between builds
	portList := make([]string, len(ports))
	var i int
	for port := range ports {
		if _, exists := b.runConfig.ExposedPorts[port]; !exists {
			b.runConfig.ExposedPorts[port] = struct{}{}
		}
		portList[i] = string(port)
		i++
	}
	sort.Strings(portList)
	return b.commit("", b.runConfig.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " ")))
}
开发者ID:SUSE,项目名称:docker.mirror,代码行数:40,代码来源:dispatchers.go


示例4: mergePorts

// TODO: should this override by name, or does swarm handle that?
func mergePorts(flags *pflag.FlagSet, portConfig *[]swarm.PortConfig) {
	if !flags.Changed("ports") {
		return
	}

	values := flags.Lookup("ports").Value.(*opts.ListOpts).GetAll()
	ports, portBindings, _ := nat.ParsePortSpecs(values)

	for port := range ports {
		*portConfig = append(*portConfig, convertPortToPortConfig(port, portBindings)...)
	}
}
开发者ID:amitshukla,项目名称:docker,代码行数:13,代码来源:update.go


示例5: ToEndpointSpec

func (e *endpointOptions) ToEndpointSpec() *swarm.EndpointSpec {
	portConfigs := []swarm.PortConfig{}
	// We can ignore errors because the format was already validated by ValidatePort
	ports, portBindings, _ := nat.ParsePortSpecs(e.ports.GetAll())

	for port := range ports {
		portConfigs = append(portConfigs, convertPortToPortConfig(port, portBindings)...)
	}

	return &swarm.EndpointSpec{
		Mode:  swarm.ResolutionMode(strings.ToLower(e.mode)),
		Ports: portConfigs,
	}
}
开发者ID:CrocdileChan,项目名称:docker,代码行数:14,代码来源:opts.go


示例6: updatePorts

// TODO: should this override by name, or does swarm handle that?
func updatePorts(flags *pflag.FlagSet, portConfig *[]swarm.PortConfig) {
	if !flags.Changed(flagPublish) {
		return
	}

	values := flags.Lookup(flagPublish).Value.(*opts.ListOpts).GetAll()
	ports, portBindings, _ := nat.ParsePortSpecs(values)

	var localPortConfig []swarm.PortConfig
	for port := range ports {
		localPortConfig = append(localPortConfig, convertPortToPortConfig(port, portBindings)...)
	}
	*portConfig = localPortConfig
}
开发者ID:agrarianlabs,项目名称:localdiscovery,代码行数:15,代码来源:update.go


示例7: convertEndpointSpec

func convertEndpointSpec(source []string) (*swarm.EndpointSpec, error) {
	portConfigs := []swarm.PortConfig{}
	ports, portBindings, err := nat.ParsePortSpecs(source)
	if err != nil {
		return nil, err
	}

	for port := range ports {
		portConfigs = append(
			portConfigs,
			opts.ConvertPortToPortConfig(port, portBindings)...)
	}

	return &swarm.EndpointSpec{Ports: portConfigs}, nil
}
开发者ID:shakamunyi,项目名称:docker,代码行数:15,代码来源:service.go


示例8: specificiesHostPort

func (s *Service) specificiesHostPort() bool {
	_, bindings, err := nat.ParsePortSpecs(s.Config().Ports)

	if err != nil {
		fmt.Println(err)
	}

	for _, portBindings := range bindings {
		for _, portBinding := range portBindings {
			if portBinding.HostPort != "" {
				return true
			}
		}
	}

	return false
}
开发者ID:datawolf,项目名称:libcompose,代码行数:17,代码来源:service.go


示例9: toValues

func (c *dockerCmd) toValues() (url.Values, error) {
	ports, portBindings, err := nat.ParsePortSpecs(c.ports)
	if err != nil {
		return nil, err
	}
	c.config.Config.ExposedPorts = map[docker.Port]struct{}{}
	for k, v := range ports {
		c.config.Config.ExposedPorts[docker.Port(k)] = v
	}
	c.config.HostConfig.PortBindings = map[docker.Port][]docker.PortBinding{}
	for k, v := range portBindings {
		var val []docker.PortBinding
		for _, b := range v {
			val = append(val, docker.PortBinding{HostIP: b.HostIP, HostPort: b.HostPort})
		}
		c.config.HostConfig.PortBindings[docker.Port(k)] = val
	}
	val, err := form.EncodeToValues(c.config)
	if err != nil {
		return nil, err
	}
	for k := range val {
		lower := strings.ToLower(k)
		if lower == k {
			continue
		}
		val[lower] = val[k]
		delete(val, k)
	}
	for k, v := range c.raw {
		k = strings.ToLower(k)
		matches := reKeyWithIndex.FindStringSubmatch(k)
		if len(matches) >= 1 {
			val.Del(matches[1])
		}
		val.Set(k, v)
	}
	return val, nil
}
开发者ID:tsuru,项目名称:tsuru,代码行数:39,代码来源:cmd.go


示例10: bindContainer

func (c *Context) bindContainer(h *exec.Handle) ([]*Endpoint, error) {
	con, err := c.container(h)
	if con != nil {
		return con.Endpoints(), nil // already bound
	}

	if _, ok := err.(ResourceNotFoundError); !ok {
		return nil, err
	}

	con = &Container{
		id:   uid.Parse(h.ExecConfig.ID),
		name: h.ExecConfig.Name,
	}

	defaultMarked := false
	aliases := make(map[string]*Container)
	var endpoints []*Endpoint
	for _, ne := range h.ExecConfig.Networks {
		var s *Scope
		s, ok := c.scopes[ne.Network.Name]
		if !ok {
			return nil, &ResourceNotFoundError{}
		}

		defer func() {
			if err == nil {
				return
			}

			s.RemoveContainer(con)
		}()

		var eip *net.IP
		if ne.Static {
			eip = &ne.IP.IP
		} else if !ip.IsUnspecifiedIP(ne.Assigned.IP) {
			// for VCH restart, we need to reserve
			// the IP of the running container
			//
			// this may be a DHCP assigned IP, however, the
			// addContainer call below will ignore reserving
			// an IP if the scope is "dynamic"
			eip = &ne.Assigned.IP
		}

		e := newEndpoint(con, s, eip, nil)
		e.static = ne.Static
		if err = s.AddContainer(con, e); err != nil {
			return nil, err
		}

		ports, _, err := nat.ParsePortSpecs(ne.Ports)
		if err != nil {
			return nil, err
		}
		for p := range ports {
			var port Port
			if port, err = ParsePort(string(p)); err != nil {
				return nil, err
			}

			if err = e.addPort(port); err != nil {
				return nil, err
			}
		}

		if !ip.IsUnspecifiedIP(e.IP()) {
			ne.IP = &net.IPNet{
				IP:   e.IP(),
				Mask: e.Scope().Subnet().Mask,
			}
		}
		ne.Network.Gateway = net.IPNet{IP: e.Gateway(), Mask: e.Subnet().Mask}
		ne.Network.Nameservers = make([]net.IP, len(s.dns))
		copy(ne.Network.Nameservers, s.dns)

		// mark the external network as default
		if !defaultMarked && e.Scope().Type() == constants.ExternalScopeType {
			defaultMarked = true
			ne.Network.Default = true
		}

		// dns lookup aliases
		aliases[fmt.Sprintf("%s:%s", s.Name(), con.name)] = con
		aliases[fmt.Sprintf("%s:%s", s.Name(), con.id.Truncate())] = con

		// container specific aliases
		for _, a := range ne.Network.Aliases {
			log.Debugf("adding alias %s", a)
			l := strings.Split(a, ":")
			if len(l) != 2 {
				err = fmt.Errorf("Parsing network alias %s failed", a)
				return nil, err
			}

			who, what := l[0], l[1]
			if who == "" {
				who = con.name
			}
//.........这里部分代码省略.........
开发者ID:vmware,项目名称:vic,代码行数:101,代码来源:context.go


示例11: Parse


//.........这里部分代码省略.........
			copts.volumes.Delete(bind)
		}
	}

	// Can't evaluate options passed into --tmpfs until we actually mount
	tmpfs := make(map[string]string)
	for _, t := range copts.tmpfs.GetAll() {
		if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
			if _, _, err := mount.ParseTmpfsOptions(arr[1]); err != nil {
				return nil, nil, nil, err
			}
			tmpfs[arr[0]] = arr[1]
		} else {
			tmpfs[arr[0]] = ""
		}
	}

	var (
		runCmd     strslice.StrSlice
		entrypoint strslice.StrSlice
	)

	if len(copts.Args) > 0 {
		runCmd = strslice.StrSlice(copts.Args)
	}

	if copts.entrypoint != "" {
		entrypoint = strslice.StrSlice{copts.entrypoint}
	} else if flags.Changed("entrypoint") {
		// if `--entrypoint=` is parsed then Entrypoint is reset
		entrypoint = []string{""}
	}

	ports, portBindings, err := nat.ParsePortSpecs(copts.publish.GetAll())
	if err != nil {
		return nil, nil, nil, err
	}

	// Merge in exposed ports to the map of published ports
	for _, e := range copts.expose.GetAll() {
		if strings.Contains(e, ":") {
			return nil, nil, nil, fmt.Errorf("invalid port format for --expose: %s", e)
		}
		//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
		proto, port := nat.SplitProtoPort(e)
		//parse the start and end port and create a sequence of ports to expose
		//if expose a port, the start and end port are the same
		start, end, err := nat.ParsePortRange(port)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("invalid range format for --expose: %s, error: %s", e, err)
		}
		for i := start; i <= end; i++ {
			p, err := nat.NewPort(proto, strconv.FormatUint(i, 10))
			if err != nil {
				return nil, nil, nil, err
			}
			if _, exists := ports[p]; !exists {
				ports[p] = struct{}{}
			}
		}
	}

	// parse device mappings
	deviceMappings := []container.DeviceMapping{}
	for _, device := range copts.devices.GetAll() {
		deviceMapping, err := ParseDevice(device)
开发者ID:SUSE,项目名称:docker.mirror,代码行数:67,代码来源:parse.go


示例12: IsFormat

func (checker portsFormatChecker) IsFormat(input string) bool {
	_, _, err := nat.ParsePortSpecs([]string{input})
	return err == nil
}
开发者ID:kunalkushwaha,项目名称:libcompose,代码行数:4,代码来源:schema_helpers.go


示例13: Set

// Set a new port value
func (p *PortOpt) Set(value string) error {
	longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value)
	if err != nil {
		return err
	}
	if longSyntax {
		csvReader := csv.NewReader(strings.NewReader(value))
		fields, err := csvReader.Read()
		if err != nil {
			return err
		}

		pConfig := swarm.PortConfig{}
		for _, field := range fields {
			parts := strings.SplitN(field, "=", 2)
			if len(parts) != 2 {
				return fmt.Errorf("invalid field %s", field)
			}

			key := strings.ToLower(parts[0])
			value := strings.ToLower(parts[1])

			switch key {
			case portOptProtocol:
				if value != string(swarm.PortConfigProtocolTCP) && value != string(swarm.PortConfigProtocolUDP) {
					return fmt.Errorf("invalid protocol value %s", value)
				}

				pConfig.Protocol = swarm.PortConfigProtocol(value)
			case portOptMode:
				if value != string(swarm.PortConfigPublishModeIngress) && value != string(swarm.PortConfigPublishModeHost) {
					return fmt.Errorf("invalid publish mode value %s", value)
				}

				pConfig.PublishMode = swarm.PortConfigPublishMode(value)
			case portOptTargetPort:
				tPort, err := strconv.ParseUint(value, 10, 16)
				if err != nil {
					return err
				}

				pConfig.TargetPort = uint32(tPort)
			case portOptPublishedPort:
				pPort, err := strconv.ParseUint(value, 10, 16)
				if err != nil {
					return err
				}

				pConfig.PublishedPort = uint32(pPort)
			default:
				return fmt.Errorf("invalid field key %s", key)
			}
		}

		if pConfig.TargetPort == 0 {
			return fmt.Errorf("missing mandatory field %q", portOptTargetPort)
		}

		if pConfig.PublishMode == "" {
			pConfig.PublishMode = swarm.PortConfigPublishModeIngress
		}

		if pConfig.Protocol == "" {
			pConfig.Protocol = swarm.PortConfigProtocolTCP
		}

		p.ports = append(p.ports, pConfig)
	} else {
		// short syntax
		portConfigs := []swarm.PortConfig{}
		// We can ignore errors because the format was already validated by ValidatePort
		ports, portBindings, _ := nat.ParsePortSpecs([]string{value})

		for port := range ports {
			portConfigs = append(portConfigs, ConvertPortToPortConfig(port, portBindings)...)
		}
		p.ports = append(p.ports, portConfigs...)
	}
	return nil
}
开发者ID:harche,项目名称:docker,代码行数:81,代码来源:port.go


示例14: TestMerge

func TestMerge(t *testing.T) {
	volumesImage := make(map[string]struct{})
	volumesImage["/test1"] = struct{}{}
	volumesImage["/test2"] = struct{}{}
	portsImage := make(nat.PortSet)
	portsImage[newPortNoError("tcp", "1111")] = struct{}{}
	portsImage[newPortNoError("tcp", "2222")] = struct{}{}
	configImage := &containertypes.Config{
		ExposedPorts: portsImage,
		Env:          []string{"VAR1=1", "VAR2=2"},
		Volumes:      volumesImage,
	}

	portsUser := make(nat.PortSet)
	portsUser[newPortNoError("tcp", "2222")] = struct{}{}
	portsUser[newPortNoError("tcp", "3333")] = struct{}{}
	volumesUser := make(map[string]struct{})
	volumesUser["/test3"] = struct{}{}
	configUser := &containertypes.Config{
		ExposedPorts: portsUser,
		Env:          []string{"VAR2=3", "VAR3=3"},
		Volumes:      volumesUser,
	}

	if err := merge(configUser, configImage); err != nil {
		t.Error(err)
	}

	if len(configUser.ExposedPorts) != 3 {
		t.Fatalf("Expected 3 ExposedPorts, 1111, 2222 and 3333, found %d", len(configUser.ExposedPorts))
	}
	for portSpecs := range configUser.ExposedPorts {
		if portSpecs.Port() != "1111" && portSpecs.Port() != "2222" && portSpecs.Port() != "3333" {
			t.Fatalf("Expected 1111 or 2222 or 3333, found %s", portSpecs)
		}
	}
	if len(configUser.Env) != 3 {
		t.Fatalf("Expected 3 env var, VAR1=1, VAR2=3 and VAR3=3, found %d", len(configUser.Env))
	}
	for _, env := range configUser.Env {
		if env != "VAR1=1" && env != "VAR2=3" && env != "VAR3=3" {
			t.Fatalf("Expected VAR1=1 or VAR2=3 or VAR3=3, found %s", env)
		}
	}

	if len(configUser.Volumes) != 3 {
		t.Fatalf("Expected 3 volumes, /test1, /test2 and /test3, found %d", len(configUser.Volumes))
	}
	for v := range configUser.Volumes {
		if v != "/test1" && v != "/test2" && v != "/test3" {
			t.Fatalf("Expected /test1 or /test2 or /test3, found %s", v)
		}
	}

	ports, _, err := nat.ParsePortSpecs([]string{"0000"})
	if err != nil {
		t.Error(err)
	}
	configImage2 := &containertypes.Config{
		ExposedPorts: ports,
	}

	if err := merge(configUser, configImage2); err != nil {
		t.Error(err)
	}

	if len(configUser.ExposedPorts) != 4 {
		t.Fatalf("Expected 4 ExposedPorts, 0000, 1111, 2222 and 3333, found %d", len(configUser.ExposedPorts))
	}
	for portSpecs := range configUser.ExposedPorts {
		if portSpecs.Port() != "0" && portSpecs.Port() != "1111" && portSpecs.Port() != "2222" && portSpecs.Port() != "3333" {
			t.Fatalf("Expected %q or %q or %q or %q, found %s", 0, 1111, 2222, 3333, portSpecs)
		}
	}
}
开发者ID:Mic92,项目名称:docker,代码行数:75,代码来源:daemon_test.go


示例15: Parse


//.........这里部分代码省略.........
	tmpfs := make(map[string]string)
	for _, t := range flTmpfs.GetAll() {
		if arr := strings.SplitN(t, ":", 2); len(arr) > 1 {
			if _, _, err := mount.ParseTmpfsOptions(arr[1]); err != nil {
				return nil, nil, nil, cmd, err
			}
			tmpfs[arr[0]] = arr[1]
		} else {
			tmpfs[arr[0]] = ""
		}
	}

	var (
		parsedArgs = cmd.Args()
		runCmd     strslice.StrSlice
		entrypoint strslice.StrSlice
		image      = cmd.Arg(0)
	)
	if len(parsedArgs) > 1 {
		runCmd = strslice.StrSlice(parsedArgs[1:])
	}
	if *flEntrypoint != "" {
		entrypoint = strslice.StrSlice{*flEntrypoint}
	}
	// Validate if the given hostname is RFC 1123 (https://tools.ietf.org/html/rfc1123) compliant.
	hostname := *flHostname
	if hostname != "" {
		matched, _ := regexp.MatchString("^(([[:alnum:]]|[[:alnum:]][[:alnum:]\\-]*[[:alnum:]])\\.)*([[:alnum:]]|[[:alnum:]][[:alnum:]\\-]*[[:alnum:]])$", hostname)
		if !matched {
			return nil, nil, nil, cmd, fmt.Errorf("invalid hostname format for --hostname: %s", hostname)
		}
	}

	ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll())
	if err != nil {
		return nil, nil, nil, cmd, err
	}

	// Merge in exposed ports to the map of published ports
	for _, e := range flExpose.GetAll() {
		if strings.Contains(e, ":") {
			return nil, nil, nil, cmd, fmt.Errorf("invalid port format for --expose: %s", e)
		}
		//support two formats for expose, original format <portnum>/[<proto>] or <startport-endport>/[<proto>]
		proto, port := nat.SplitProtoPort(e)
		//parse the start and end port and create a sequence of ports to expose
		//if expose a port, the start and end port are the same
		start, end, err := nat.ParsePortRange(port)
		if err != nil {
			return nil, nil, nil, cmd, fmt.Errorf("invalid range format for --expose: %s, error: %s", e, err)
		}
		for i := start; i <= end; i++ {
			p, err := nat.NewPort(proto, strconv.FormatUint(i, 10))
			if err != nil {
				return nil, nil, nil, cmd, err
			}
			if _, exists := ports[p]; !exists {
				ports[p] = struct{}{}
			}
		}
	}

	// parse device mappings
	deviceMappings := []container.DeviceMapping{}
	for _, device := range flDevices.GetAll() {
		deviceMapping, err := ParseDevice(device)
开发者ID:mefellows,项目名称:parity,代码行数:67,代码来源:parse.go



注:本文中的github.com/docker/go-connections/nat.ParsePortSpecs函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang nat.Port函数代码示例发布时间:2022-05-23
下一篇:
Golang nat.ParsePortSpec函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap