ronantakizawa/codereview-bench huggingface dataset:
Repository: moby/moby
File: daemon/execdriver/native/driver.go (Go)

Code before:
			return nil, err
		}
		key = strings.ToLower(key)
		switch key {
		case "native.cgroupdriver":
			// override the default if they set options
			if val == "cgroupfs" || !systemd.UseSystemd() {
				cgm = libcontainer.Cgroupfs
			} else {
				cgm = libcontainer.SystemdCgroups
			}
		default:
			return nil, fmt.Errorf("Unknown option %s\n", key)
		}
	}

	f, err := libcontainer.New(
		root,
		cgm,
		libcontainer.InitPath(reexec.Self(), DriverName),
	)
	if err != nil {
		return nil, err
	}

	return &driver{
		root:             root,
		initPath:         initPath,
		activeContainers: make(map[string]libcontainer.Container),
		machineMemory:    meminfo.MemTotal,
		factory:          f,
	}, nil
}

type execOutput struct {
	exitCode int
	err      error
}

func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
	// take the Command and populate the libcontainer.Config from it
	container, err := d.createContainer(c)
	if err != nil {
		return execdriver.ExitStatus{ExitCode: -1}, err
	}

	var term execdriver.Terminal

	p := &libcontainer.Process{
		Args: append([]string{c.ProcessConfig.Entrypoint}, c.ProcessConfig.Arguments...),
		Env:  c.ProcessConfig.Env,

Review comment (bug):
Maybe add a `DEBUG` or `INFO` log giving the cgroup manager we picked?


Code after:
		key, val, err := parsers.ParseKeyValueOpt(option)
		if err != nil {
			return nil, err
		}
		key = strings.ToLower(key)
		switch key {
		case "native.cgroupdriver":
			// override the default if they set options
			switch val {
			case "systemd":
				if systemd.UseSystemd() {
					cgm = libcontainer.SystemdCgroups
				} else {
					// warn them that they chose the wrong driver
					logrus.Warn("You cannot use systemd as native.cgroupdriver, using cgroupfs instead")
				}
			case "cgroupfs":
				cgm = libcontainer.Cgroupfs
			default:
				return nil, fmt.Errorf("Unknown native.cgroupdriver given %q. try cgroupfs or systemd", val)
			}
		default:
			return nil, fmt.Errorf("Unknown option %s\n", key)
		}
	}

	logrus.Debugf("Using %v as native.cgroupdriver", cgm)

	f, err := libcontainer.New(
		root,
		cgm,
		libcontainer.InitPath(reexec.Self(), DriverName),
	)
	if err != nil {
		return nil, err
	}

	return &driver{
		root:             root,
		initPath:         initPath,
		activeContainers: make(map[string]libcontainer.Container),
		machineMemory:    meminfo.MemTotal,
		factory:          f,
	}, nil
}

type execOutput struct {
	exitCode int
	err      error
}
Repository: moby/moby
File: daemon/archive_tarcopyoptions_unix.go (Go)

Code before:
func getIDOrName(nameOrID string) (id int, name string) {
	if uid, err := strconv.ParseUint(nameOrID, 10, 32); err == nil && uid <= math.MaxInt32 {
		// uid provided
		return int(uid), ""
	}
	// not am id, assume name
	return 0, nameOrID
}

func lookupUser(ctr *container.Container, nameOrID string) (user.User, error) {
	passwdPath, err := resourcePath(ctr, user.GetPasswdPath)
	if err != nil {
		return user.User{}, err
	}
	userID, userName := getIDOrName(nameOrID)
	users, err := user.ParsePasswdFileFilter(passwdPath, func(entry user.User) bool {
		if userName != "" {
			return entry.Name == userName
		}
		return entry.Uid == userID
	})
	if err != nil {
		return user.User{}, err
	}
	if len(users) == 0 {
		return user.User{}, errors.New("no group found")
	}
	return users[0], nil
}

func lookupGID(ctr *container.Container, nameOrID string) (int, error) {
	groupID, groupName := getIDOrName(nameOrID)
	if groupName == "" {
		// GID is passed, no need to look up
		return groupID, nil
	}

	groupPath, err := resourcePath(ctr, user.GetGroupPath)
	if err != nil {
		return 0, err
	}
	groups, err := user.ParseGroupFileFilter(groupPath, func(entry user.Group) bool {
		if groupName != "" {
			return entry.Name == groupName
		}
		return entry.Gid == groupID
	})
	if err != nil {
		return 0, err
	}
	if len(groups) == 0 {

Review comment (suggestion):
```suggestion
		return user.User{}, errors.New("no user found")
```

Code after:
func getIDOrName(nameOrID string) (id int, name string) {
	if uid, err := strconv.ParseUint(nameOrID, 10, 32); err == nil && uid <= math.MaxInt32 {
		// uid provided
		return int(uid), ""
	}
	// not an id, assume name
	return 0, nameOrID
}

func lookupUser(nameOrID string) (uid, gid int, _ error) {
	userID, userName := getIDOrName(nameOrID)
	if userName != "" {
		u, err := user.LookupUser(userName)
		if err != nil {
			return 0, 0, fmt.Errorf("failed to look up user %q in container: %w", userName, err)
		}
		return u.Uid, u.Gid, nil
	}

	u, err := user.LookupUid(userID)
	if err != nil {
		// Match behavior of "docker run": when using a UID for the
		// user, resolving the user and its primary group is best-effort.
		// If a user with the given UID is found, we use its primary
		// group, otherwise use it as-is and use the default (0) as
		//  GID.
		//
		//	docker run --rm --user 12345 ubuntu id
		//	uid=12345 gid=0(root) groups=0(root)
		//
		//	docker run --rm ubuntu cat /etc/passwd | grep www-data
		//	www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
		//
		//	docker run --rm --user 33 ubuntu id
		//	uid=33(www-data) gid=33(www-data) groups=33(www-data)
		return userID, 0, nil
	}
	return u.Uid, u.Gid, nil
}

func lookupGID(nameOrID string) (int, error) {
	groupID, groupName := getIDOrName(nameOrID)
	if groupName == "" {
		// GID is passed, no need to look up
		return groupID, nil
	}
	group, err := user.LookupGroup(groupName)
	if err != nil {
		return 0, fmt.Errorf("failed to look up group %q in container: %w", nameOrID, err)
	}
	return group.Gid, nil
Repository: moby/moby
File: daemon/logger/fluentd/fluentd.go (Go)

Code before:
	// and these are transferred again automatically.
	return f.writer.PostWithTime(f.tag, ts, data)
}

func (f *fluentd) Close() error {
	return f.writer.Close()
}

func (f *fluentd) Name() string {
	return name
}

// ValidateLogOpt looks for fluentd specific log option fluentd-address.
func ValidateLogOpt(cfg map[string]string) error {
	for key := range cfg {
		switch key {
		case "env":
		case "env-regex":
		case "labels":
		case "labels-regex":
		case "tag":
		case addressKey:
		case bufferLimitKey:
		case retryWaitKey:
		case maxRetriesKey:
		case asyncConnectKey:
		case subSecondPrecisionKey:
			// Accepted
		default:
			return fmt.Errorf("unknown log opt '%s' for fluentd log driver", key)
		}
	}

	_, err := parseAddress(cfg[addressKey])
	return err
}

func parseAddress(address string) (*location, error) {
	if address == "" {
		return &location{
			protocol: defaultProtocol,
			host:     defaultHost,
			port:     defaultPort,
			path:     "",
		}, nil
	}

	protocol := defaultProtocol
	givenAddress := address
	if urlutil.IsTransportURL(address) {
		url, err := url.Parse(address)

Review comment (suggestion):
This error msg doesn't show the pair of keys now conflicting (just shows values of these keys). It should show conflicting keys and these values for users.

Code after:
		if err != nil {
			return config, err
		}
		bufferLimit = int(bl64)
	}

	retryWait := defaultRetryWait
	if cfg[retryWaitKey] != "" {
		rwd, err := time.ParseDuration(cfg[retryWaitKey])
		if err != nil {
			return config, err
		}
		retryWait = int(rwd.Seconds() * 1000)
	}

	maxRetries := defaultMaxRetries
	if cfg[maxRetriesKey] != "" {
		mr64, err := strconv.ParseUint(cfg[maxRetriesKey], 10, strconv.IntSize)
		if err != nil {
			return config, err
		}
		maxRetries = int(mr64)
	}

	if cfg[asyncKey] != "" && cfg[asyncConnectKey] != "" {
		return config, errors.Errorf("conflicting options: cannot specify both '%s' and '%s", asyncKey, asyncConnectKey)
	}

	async := false
	if cfg[asyncKey] != "" {
		if async, err = strconv.ParseBool(cfg[asyncKey]); err != nil {
			return config, err
		}
	}

	// TODO fluentd-async-connect is deprecated in driver v1.4.0. Remove after two stable releases
	asyncConnect := false
	if cfg[asyncConnectKey] != "" {
		if asyncConnect, err = strconv.ParseBool(cfg[asyncConnectKey]); err != nil {
			return config, err
		}
	}

	subSecondPrecision := false
	if cfg[subSecondPrecisionKey] != "" {
		if subSecondPrecision, err = strconv.ParseBool(cfg[subSecondPrecisionKey]); err != nil {
			return config, err
		}
	}

	requestAck := false
Repository: moby/moby
File: daemon/logger/fluentd/fluentd.go (Go)

Code before:

	addressKey            = "fluentd-address"
	bufferLimitKey        = "fluentd-buffer-limit"
	retryWaitKey          = "fluentd-retry-wait"
	maxRetriesKey         = "fluentd-max-retries"
	asyncConnectKey       = "fluentd-async-connect"
	subSecondPrecisionKey = "fluentd-sub-second-precision"
)

func init() {
	if err := logger.RegisterLogDriver(name, New); err != nil {
		logrus.Fatal(err)
	}
	if err := logger.RegisterLogOptValidator(name, ValidateLogOpt); err != nil {
		logrus.Fatal(err)
	}
}

// New creates a fluentd logger using the configuration passed in on
// the context. The supported context configuration variable is
// fluentd-address.
func New(info logger.Info) (logger.Logger, error) {
	loc, err := parseAddress(info.Config[addressKey])
	if err != nil {
		return nil, err
	}

	tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
	if err != nil {
		return nil, err
	}

	extra, err := info.ExtraAttributes(nil)
	if err != nil {
		return nil, err
	}

	bufferLimit := defaultBufferLimit
	if info.Config[bufferLimitKey] != "" {
		bl64, err := units.RAMInBytes(info.Config[bufferLimitKey])
		if err != nil {
			return nil, err
		}
		bufferLimit = int(bl64)
	}

	retryWait := defaultRetryWait
	if info.Config[retryWaitKey] != "" {
		rwd, err := time.ParseDuration(info.Config[retryWaitKey])
		if err != nil {
			return nil, err

Review comment (suggestion):
This would typically need to be an `errdefs.InvalidParameter` error, I think.

Code after:

	addressKey            = "fluentd-address"
	asyncKey              = "fluentd-async"
	asyncConnectKey       = "fluentd-async-connect" // deprecated option (use fluent-async instead)
	bufferLimitKey        = "fluentd-buffer-limit"
	maxRetriesKey         = "fluentd-max-retries"
	requestAckKey         = "fluentd-request-ack"
	retryWaitKey          = "fluentd-retry-wait"
	subSecondPrecisionKey = "fluentd-sub-second-precision"
)

func init() {
	if err := logger.RegisterLogDriver(name, New); err != nil {
		logrus.Fatal(err)
	}
	if err := logger.RegisterLogOptValidator(name, ValidateLogOpt); err != nil {
		logrus.Fatal(err)
	}
}

// New creates a fluentd logger using the configuration passed in on
// the context. The supported context configuration variable is
// fluentd-address.
func New(info logger.Info) (logger.Logger, error) {
	fluentConfig, err := parseConfig(info.Config)
	if err != nil {
		return nil, errdefs.InvalidParameter(err)
	}

	tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
	if err != nil {
		return nil, errdefs.InvalidParameter(err)
	}

	extra, err := info.ExtraAttributes(nil)
	if err != nil {
		return nil, errdefs.InvalidParameter(err)
	}

	logrus.WithField("container", info.ContainerID).WithField("config", fluentConfig).
		Debug("logging driver fluentd configured")

	log, err := fluent.New(fluentConfig)
	if err != nil {
		return nil, err
	}
	return &fluentd{
		tag:           tag,
		containerID:   info.ContainerID,
		containerName: info.ContainerName,
		writer:        log,
Repository: moby/moby
File: client/client_test.go (Go)

Code before:
			expectedVersion: api.DefaultVersion,
		},
		{
			doc: "invalid docker host",
			envs: map[string]string{
				"DOCKER_HOST": "host",
			},
			expectedError: "unable to parse docker host `host`",
		},
		{
			doc: "invalid docker host, with good format",
			envs: map[string]string{
				"DOCKER_HOST": "invalid://url",
			},
			expectedVersion: api.DefaultVersion,
		},
		{
			doc: "override api version",
			envs: map[string]string{
				"DOCKER_API_VERSION": "1.22",
			},
			expectedVersion: "1.22",
		},
	}

	env.PatchAll(t, nil)()
	for _, c := range testcases {
		env.PatchAll(t, c.envs)
		apiclient, err := NewClientWithOpts(FromEnv)
		if c.expectedError != "" {
			assert.Check(t, is.Error(err, c.expectedError), c.doc)
		} else {
			assert.Check(t, err, c.doc)
			version := apiclient.ClientVersion()
			assert.Check(t, is.Equal(c.expectedVersion, version), c.doc)
		}

		if c.envs["DOCKER_TLS_VERIFY"] != "" {
			// pedantic checking that this is handled correctly
			tr := apiclient.client.Transport.(*http.Transport)
			assert.Assert(t, tr.TLSClientConfig != nil, c.doc)
			assert.Check(t, is.Equal(tr.TLSClientConfig.InsecureSkipVerify, false), c.doc)
		}
	}
}

func TestGetAPIPath(t *testing.T) {
	testcases := []struct {
		version  string
		path     string
		query    url.Values

Review comment (bug):
DOH! I know what's wrong (probably!); this should of course be

```suggestion
	env.PatchAll(t, nil)
```

Otherwise, we're calling the `cleanup` _immediately_ 🤦 

Code after:
			expectedVersion: api.DefaultVersion,
		},
		{
			doc: "invalid docker host",
			envs: map[string]string{
				"DOCKER_HOST": "host",
			},
			expectedError: "unable to parse docker host `host`",
		},
		{
			doc: "invalid docker host, with good format",
			envs: map[string]string{
				"DOCKER_HOST": "invalid://url",
			},
			expectedVersion: api.DefaultVersion,
		},
		{
			doc: "override api version",
			envs: map[string]string{
				"DOCKER_API_VERSION": "1.22",
			},
			expectedVersion: "1.22",
		},
	}

	env.PatchAll(t, nil)
	for _, tc := range testcases {
		t.Run(tc.doc, func(t *testing.T) {
			env.PatchAll(t, tc.envs)
			client, err := NewClientWithOpts(FromEnv)
			if tc.expectedError != "" {
				assert.Check(t, is.Error(err, tc.expectedError))
			} else {
				assert.Check(t, err)
				assert.Check(t, is.Equal(client.ClientVersion(), tc.expectedVersion))
			}

			if tc.envs["DOCKER_TLS_VERIFY"] != "" {
				// pedantic checking that this is handled correctly
				tlsConfig := client.tlsConfig()
				assert.Assert(t, tlsConfig != nil)
				assert.Check(t, is.Equal(tlsConfig.InsecureSkipVerify, false))
			}
		})
	}
}

func TestGetAPIPath(t *testing.T) {
	tests := []struct {
		version  string
		path     string
Repository: moby/moby
File: libnetwork/drivers/bridge/setup_ip_tables.go (Go)

Code before:
		version = iptables.IPv6
	}

	if err := programChainRule(version, inDropRule, "DROP INCOMING", insert); err != nil {
		return err
	}
	if err := programChainRule(version, outDropRule, "DROP OUTGOING", insert); err != nil {
		return err
	}
	// Set Inter Container Communication.
	return setIcc(version, bridgeIface, icc, insert)
}

func clearEndpointConnections(nlh *netlink.Handle, ep *bridgeEndpoint) {
	var ipv4List []net.IP
	var ipv6List []net.IP
	if ep.addr != nil {
		ipv4List = append(ipv4List, ep.addr.IP)
	}
	if ep.addrv6 != nil {
		ipv6List = append(ipv6List, ep.addrv6.IP)
	}
	iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List)
}

func clearConnectionsToUDPPorts(nlh *netlink.Handle, ep *bridgeEndpoint) {
	var udpPorts []uint16

	for _, pb := range ep.portMapping {
		if pb.Proto == types.UDP {
			udpPorts = append(udpPorts, pb.HostPort)
		}
	}

	iptables.DeleteConntrackEntriesByPort(nlh, types.UDP, udpPorts)
}


Review comment (suggestion):
I wonder if this should be folded into `clearEndpointConnections`. Should UDP connections also be flushed when revoking external connectivity? (i.e. the other caller of `clearEndpointConnections`)

Code after:
		version = iptables.IPv6
	}

	if err := programChainRule(version, inDropRule, "DROP INCOMING", insert); err != nil {
		return err
	}
	if err := programChainRule(version, outDropRule, "DROP OUTGOING", insert); err != nil {
		return err
	}
	// Set Inter Container Communication.
	return setIcc(version, bridgeIface, icc, insert)
}

// clearConntrackEntries flushes conntrack entries matching endpoint IP address
// or matching one of the exposed UDP port.
// In the first case, this could happen if packets were received by the host
// between userland proxy startup and iptables setup.
// In the latter case, this could happen if packets were received whereas there
// were nowhere to route them, as netfilter creates entries in such case.
// This is required because iptables NAT rules are evaluated by netfilter only
// when creating a new conntrack entry. When Docker latter adds NAT rules,
// netfilter ignore them for any packet matching a pre-existing conntrack entry.
// As such, we need to flush all those conntrack entries to make sure NAT rules
// are correctly applied to all packets.
// See: #8795, #44688 & #44742.
func clearConntrackEntries(nlh *netlink.Handle, ep *bridgeEndpoint) {
	var ipv4List []net.IP
	var ipv6List []net.IP
	var udpPorts []uint16

	if ep.addr != nil {
		ipv4List = append(ipv4List, ep.addr.IP)
	}
	if ep.addrv6 != nil {
		ipv6List = append(ipv6List, ep.addrv6.IP)
	}
	for _, pb := range ep.portMapping {
		if pb.Proto == types.UDP {
			udpPorts = append(udpPorts, pb.HostPort)
		}
	}

	iptables.DeleteConntrackEntries(nlh, ipv4List, ipv6List)
	iptables.DeleteConntrackEntriesByPort(nlh, types.UDP, udpPorts)
}
Repository: moby/moby
File: client/request.go (Go)

Code before:
			return errors.Wrap(err, "Error reading JSON")
		}
		errorMessage = strings.TrimSpace(errorResponse.Message)
	} else {
		errorMessage = strings.TrimSpace(string(body))
	}

	return errors.Wrap(errors.New(errorMessage), "Error response from daemon")
}

func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request {
	// Add CLI Config's HTTP Headers BEFORE we set the Docker headers
	// then the user can't change OUR headers
	for k, v := range cli.customHTTPHeaders {
		if versions.LessThan(cli.version, "1.25") && http.CanonicalHeaderKey(k) == "User-Agent" {
			continue
		}
		req.Header.Set(k, v)
	}

	for k, v := range headers {
		req.Header[http.CanonicalHeaderKey(k)] = v
	}

	if cli.userAgent != "" {
		req.Header.Set("User-Agent", cli.userAgent)
	}
	return req
}

func encodeData(data interface{}) (*bytes.Buffer, error) {
	params := bytes.NewBuffer(nil)
	if data != nil {
		if err := json.NewEncoder(params).Encode(data); err != nil {
			return nil, err
		}
	}
	return params, nil
}

func ensureReaderClosed(response serverResponse) {
	if response.body != nil {
		// Drain up to 512 bytes and close the body to let the Transport reuse the connection
		io.CopyN(io.Discard, response.body, 512)
		response.body.Close()
	}
}


Review comment (suggestion):
I think  `cli.userAgent` should be `*string` and `*cli.userAgent == ""` should just unset the `User-Agent` header.


Code after:
	if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) && ct == "application/json" {
		var errorResponse types.ErrorResponse
		if err := json.Unmarshal(body, &errorResponse); err != nil {
			return errors.Wrap(err, "Error reading JSON")
		}
		errorMessage = strings.TrimSpace(errorResponse.Message)
	} else {
		errorMessage = strings.TrimSpace(string(body))
	}

	return errors.Wrap(errors.New(errorMessage), "Error response from daemon")
}

func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request {
	// Add CLI Config's HTTP Headers BEFORE we set the Docker headers
	// then the user can't change OUR headers
	for k, v := range cli.customHTTPHeaders {
		if versions.LessThan(cli.version, "1.25") && http.CanonicalHeaderKey(k) == "User-Agent" {
			continue
		}
		req.Header.Set(k, v)
	}

	for k, v := range headers {
		req.Header[http.CanonicalHeaderKey(k)] = v
	}

	if cli.userAgent != nil {
		if *cli.userAgent == "" {
			req.Header.Del("User-Agent")
		} else {
			req.Header.Set("User-Agent", *cli.userAgent)
		}
	}
	return req
}

func encodeData(data interface{}) (*bytes.Buffer, error) {
	params := bytes.NewBuffer(nil)
	if data != nil {
		if err := json.NewEncoder(params).Encode(data); err != nil {
			return nil, err
		}
	}
	return params, nil
}

func ensureReaderClosed(response serverResponse) {
	if response.body != nil {
		// Drain up to 512 bytes and close the body to let the Transport reuse the connection
		io.CopyN(io.Discard, response.body, 512)
Repository: moby/moby
File: libnetwork/network.go (Go)

Code before:
		ipamV4Config[i] = ic
	}

	n.mu.Lock()
	defer n.mu.Unlock()
	n.ipamV4Config = ipamV4Config
}

// Special drivers are ones which do not need to perform any Network plumbing
func (n *Network) hasSpecialDriver() bool {
	return n.Type() == "host" || n.Type() == "null"
}

func (n *Network) hasLoadBalancerEndpoint() bool {
	return len(n.loadBalancerIP) != 0
}

func (n *Network) ResolveName(ctx context.Context, req string, ipType int) ([]net.IP, bool) {
	var ipv6Miss bool

	c := n.getController()
	networkID := n.ID()

	ctx, span := otel.Tracer("").Start(ctx, "Network.ResolveName", trace.WithAttributes(
		attribute.String("network-name", n.Name()),
		attribute.String("network-id", networkID),
	))
	defer span.End()

	c.mu.Lock()
	// TODO(aker): release the lock earlier
	defer c.mu.Unlock()
	sr, ok := c.svcRecords[networkID]

	if !ok {
		return nil, false
	}

	req = strings.TrimSuffix(req, ".")
	req = strings.ToLower(req)
	ipSet, ok := sr.svcMap.Get(req)

	if ipType == types.IPv6 {
		// If the name resolved to v4 address then its a valid name in
		// the docker network domain. If the network is not v6 enabled
		// set ipv6Miss to filter the DNS query from going to external
		// resolvers.
		if ok && !n.enableIPv6 {
			ipv6Miss = true
		}
		ipSet, ok = sr.svcIPv6Map.Get(req)

Review comment (suggestion):
We probably need to define a proper naming schema for these attributes. For the record, the OTEL sdk adds these attributes to all spans:

* `internal.span.format`
* `otel.library.name`
* `span.kind`

So I think those attributes should be named something like:

* `network-name` -> `libnet.network.name`
* `network-id` -> `libnet.network.id`

Code after:
		ipamV4Config[i] = ic
	}

	n.mu.Lock()
	defer n.mu.Unlock()
	n.ipamV4Config = ipamV4Config
}

// Special drivers are ones which do not need to perform any Network plumbing
func (n *Network) hasSpecialDriver() bool {
	return n.Type() == "host" || n.Type() == "null"
}

func (n *Network) hasLoadBalancerEndpoint() bool {
	return len(n.loadBalancerIP) != 0
}

func (n *Network) ResolveName(ctx context.Context, req string, ipType int) ([]net.IP, bool) {
	var ipv6Miss bool

	c := n.getController()
	networkID := n.ID()

	_, span := otel.Tracer("").Start(ctx, "Network.ResolveName", trace.WithAttributes(
		attribute.String("libnet.network.name", n.Name()),
		attribute.String("libnet.network.id", networkID),
	))
	defer span.End()

	c.mu.Lock()
	// TODO(aker): release the lock earlier
	defer c.mu.Unlock()
	sr, ok := c.svcRecords[networkID]

	if !ok {
		return nil, false
	}

	req = strings.TrimSuffix(req, ".")
	req = strings.ToLower(req)
	ipSet, ok := sr.svcMap.Get(req)

	if ipType == types.IPv6 {
		// If the name resolved to v4 address then its a valid name in
		// the docker network domain. If the network is not v6 enabled
		// set ipv6Miss to filter the DNS query from going to external
		// resolvers.
		if ok && !n.enableIPv6 {
			ipv6Miss = true
		}
		ipSet, ok = sr.svcIPv6Map.Get(req)