<commit_before>package network

import (
	"bufio"
	"bytes"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"math/big"
	"math/rand"
	"net"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"

	"github.com/lxc/lxd/lxd/db"
	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/device/nictype"
	"github.com/lxc/lxd/lxd/dnsmasq"
	"github.com/lxc/lxd/lxd/dnsmasq/dhcpalloc"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/ip"
	"github.com/lxc/lxd/lxd/project"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/lxd/util"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/version"
)

func networkValidPort(value string) error {
	if value == "" {
		return nil
	}

	valueInt, err := strconv.ParseInt(value, 10, 64)
	if err != nil {
		return fmt.Errorf("Invalid value for an integer: %s", value)
	}

	if valueInt < 1 || valueInt > 65536 {
		return fmt.Errorf("Invalid port number: %s", value)
	}

	return nil
}

// RandomDevName returns a random device name with prefix.
// If the random string combined with the prefix exceeds 13 characters then empty string is returned.
// This is to ensure we support buggy dhclient applications: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=858580
func RandomDevName(prefix string) string {
	// Return a new random veth device name.
	randBytes := make([]byte, 4)
	rand.Read(randBytes)
	iface := prefix + hex.EncodeToString(randBytes)
	if len(iface) > 13 {
		return ""
	}

	return iface
}

// usedByInstanceDevices looks for instance NIC devices using the network and runs the supplied usageFunc for each.
func usedByInstanceDevices(s *state.State, networkProjectName string, networkName string, usageFunc func(inst db.Instance, nicName string, nicConfig map[string]string) error) error {
	return s.Cluster.InstanceList(nil, func(inst db.Instance, p db.Project, profiles []api.Profile) error {
		// Get the instance's effective network project name.
		instNetworkProject := project.NetworkProjectFromRecord(&p)

		// Skip instances who's effective network project doesn't match this Network's project.
		if instNetworkProject != networkProjectName {
			return nil
		}

		// Look for NIC devices using this network.
		devices := db.ExpandInstanceDevices(deviceConfig.NewDevices(inst.Devices), profiles)
		for devName, devConfig := range devices {
			if isInUseByDevice(networkName, devConfig) {
				err := usageFunc(inst, devName, devConfig)
				if err != nil {
					return err
				}
			}
		}

		return nil
	})
}

// UsedBy returns list of API resources using network. Accepts firstOnly argument to indicate that only the first
// resource using network should be returned. This can help to quickly check if the network is in use.
func UsedBy(s *state.State, networkProjectName string, networkName string, firstOnly bool) ([]string, error) {
	var err error
	var usedBy []string

	// Only networks defined in the default project can be used by other networks. Cheapest to do.
	if networkProjectName == project.Default {
		// Get all managed networks across all projects.
		var projectNetworks map[string]map[int64]api.Network

		err = s.Cluster.Transaction(func(tx *db.ClusterTx) error {
			projectNetworks, err = tx.GetCreatedNetworks()
			return err
		})
		if err != nil {<commit_msg>lxd/network/network/utils: Updates UsedBy to check if the network has any created peers<commit_after>package network

import (
	"bufio"
	"bytes"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"math/big"
	"math/rand"
	"net"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"

	"github.com/lxc/lxd/lxd/db"
	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/device/nictype"
	"github.com/lxc/lxd/lxd/dnsmasq"
	"github.com/lxc/lxd/lxd/dnsmasq/dhcpalloc"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/ip"
	"github.com/lxc/lxd/lxd/project"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/lxd/util"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/version"
)

func networkValidPort(value string) error {
	if value == "" {
		return nil
	}

	valueInt, err := strconv.ParseInt(value, 10, 64)
	if err != nil {
		return fmt.Errorf("Invalid value for an integer: %s", value)
	}

	if valueInt < 1 || valueInt > 65536 {
		return fmt.Errorf("Invalid port number: %s", value)
	}

	return nil
}

// RandomDevName returns a random device name with prefix.
// If the random string combined with the prefix exceeds 13 characters then empty string is returned.
// This is to ensure we support buggy dhclient applications: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=858580
func RandomDevName(prefix string) string {
	// Return a new random veth device name.
	randBytes := make([]byte, 4)
	rand.Read(randBytes)
	iface := prefix + hex.EncodeToString(randBytes)
	if len(iface) > 13 {
		return ""
	}

	return iface
}

// usedByInstanceDevices looks for instance NIC devices using the network and runs the supplied usageFunc for each.
func usedByInstanceDevices(s *state.State, networkProjectName string, networkName string, usageFunc func(inst db.Instance, nicName string, nicConfig map[string]string) error) error {
	return s.Cluster.InstanceList(nil, func(inst db.Instance, p db.Project, profiles []api.Profile) error {
		// Get the instance's effective network project name.
		instNetworkProject := project.NetworkProjectFromRecord(&p)

		// Skip instances who's effective network project doesn't match this Network's project.
		if instNetworkProject != networkProjectName {
			return nil
		}

		// Look for NIC devices using this network.
		devices := db.ExpandInstanceDevices(deviceConfig.NewDevices(inst.Devices), profiles)
		for devName, devConfig := range devices {
			if isInUseByDevice(networkName, devConfig) {
				err := usageFunc(inst, devName, devConfig)
				if err != nil {
					return err
				}
			}
		}

		return nil
	})
}

// UsedBy returns list of API resources using network. Accepts firstOnly argument to indicate that only the first
// resource using network should be returned. This can help to quickly check if the network is in use.
func UsedBy(s *state.State, networkProjectName string, networkID int64, networkName string, firstOnly bool) ([]string, error) {
	var err error
	var usedBy []string

	// If managed network being passed in, check if it has any peerings in a created state.
	if networkID > 0 {
		peers, err := s.Cluster.GetNetworkPeers(networkID)
		if err != nil {
			return nil, fmt.Errorf("Failed getting network peers: %w", err)
		}

		for _, peer := range peers {
			if peer.Status == api.NetworkStatusCreated {
				// Add the target project/network of the peering as using this network.
				usedBy = append(usedBy, api.NewURL().Path(version.APIVersion, "networks", peer.TargetNetwork).Project(peer.TargetProject).String())

				if firstOnly {
					return usedBy, nil
				}
			}
		}
	}

	// Only networks defined in the default project can be used by other networks. Cheapest to do.
	if networkProjectName == project.Default {
		// Get all managed networks across all projects.
		var projectNetworks map[string]map[int64]api.Network

		err = s.Cluster.Transaction(func(tx *db.ClusterTx) error {
			projectNetworks, err = tx.GetCreatedNetworks()
			return err
		})
		if err != nil {
{'fraction_non_alphanumeric': 0.11343243605196196, 'fraction_numerical': 0.006562207044328378, 'mean_word_length': 3.978666666666667, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7363619', 'n_tokens_mistral': 2670, 'n_tokens_neox': 2474, 'n_words': 706}