diff --git a/client/connection.go b/client/connection.go index c2f6d738723a..5555bc41e0dc 100644 --- a/client/connection.go +++ b/client/connection.go @@ -332,7 +332,7 @@ func httpsLXD(ctx context.Context, requestURL string, args *ConnectionArgs) (Ins eventListeners: make(map[string][]*EventListener), } - if shared.StringInSlice(args.AuthType, []string{"candid", "oidc"}) { + if shared.ValueInSlice(args.AuthType, []string{"candid", "oidc"}) { server.RequireAuthenticated(true) } diff --git a/client/lxd.go b/client/lxd.go index 0d597dccb430..f31643aa8463 100644 --- a/client/lxd.go +++ b/client/lxd.go @@ -93,7 +93,7 @@ func (r *ProtocolLXD) GetConnectionInfo() (*ConnectionInfo, error) { } url := fmt.Sprintf("https://%s", addr) - if !shared.StringInSlice(url, urls) { + if !shared.ValueInSlice(url, urls) { urls = append(urls, url) } } diff --git a/client/lxd_containers.go b/client/lxd_containers.go index 1bbf80efeefc..686530401005 100644 --- a/client/lxd_containers.go +++ b/client/lxd_containers.go @@ -308,7 +308,7 @@ func (r *ProtocolLXD) CopyContainer(source InstanceServer, container api.Contain } } - if shared.StringInSlice(args.Mode, []string{"push", "relay"}) { + if shared.ValueInSlice(args.Mode, []string{"push", "relay"}) { if !r.HasExtension("container_push") { return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension") } @@ -1002,7 +1002,7 @@ func (r *ProtocolLXD) CopyContainerSnapshot(source InstanceServer, containerName // Process the copy arguments if args != nil { // Quick checks. - if shared.StringInSlice(args.Mode, []string{"push", "relay"}) { + if shared.ValueInSlice(args.Mode, []string{"push", "relay"}) { if !r.HasExtension("container_push") { return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension") } diff --git a/client/lxd_events.go b/client/lxd_events.go index 4a37bf43f280..e796b00552e9 100644 --- a/client/lxd_events.go +++ b/client/lxd_events.go @@ -143,7 +143,7 @@ func (r *ProtocolLXD) getEvents(allProjects bool) (*EventListener, error) { for _, listener := range r.eventListeners[listener.projectName] { listener.targetsLock.Lock() for _, target := range listener.targets { - if target.types != nil && !shared.StringInSlice(event.Type, target.types) { + if target.types != nil && !shared.ValueInSlice(event.Type, target.types) { continue } diff --git a/client/lxd_images.go b/client/lxd_images.go index f66b13a65744..aa6768011896 100644 --- a/client/lxd_images.go +++ b/client/lxd_images.go @@ -259,7 +259,7 @@ func lxdDownloadImage(fingerprint string, uri string, userAgent string, do func( return nil, err } - if !shared.StringInSlice(part.FormName(), []string{"rootfs", "rootfs.img"}) { + if !shared.ValueInSlice(part.FormName(), []string{"rootfs", "rootfs.img"}) { return nil, fmt.Errorf("Invalid multipart image") } diff --git a/client/lxd_instances.go b/client/lxd_instances.go index 73affff1251c..53e1110ad346 100644 --- a/client/lxd_instances.go +++ b/client/lxd_instances.go @@ -744,7 +744,7 @@ func (r *ProtocolLXD) CopyInstance(source InstanceServer, instance api.Instance, } } - if shared.StringInSlice(args.Mode, []string{"push", "relay"}) { + if shared.ValueInSlice(args.Mode, []string{"push", "relay"}) { if !r.HasExtension("container_push") { return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension") } @@ -1720,7 +1720,7 @@ func (r *ProtocolLXD) CopyInstanceSnapshot(source InstanceServer, instanceName s // Process the copy arguments if args != nil { // Quick checks. - if shared.StringInSlice(args.Mode, []string{"push", "relay"}) { + if shared.ValueInSlice(args.Mode, []string{"push", "relay"}) { if !r.HasExtension("container_push") { return nil, fmt.Errorf("The target server is missing the required \"container_push\" API extension") } diff --git a/client/lxd_server.go b/client/lxd_server.go index ba8bd08af0cb..83f2bcda405a 100644 --- a/client/lxd_server.go +++ b/client/lxd_server.go @@ -63,7 +63,7 @@ func (r *ProtocolLXD) HasExtension(extension string) bool { return true } - return shared.StringInSlice(extension, r.server.APIExtensions) + return shared.ValueInSlice(extension, r.server.APIExtensions) } // CheckExtension checks if the server has the specified extension. diff --git a/lxc-to-lxd/main_migrate.go b/lxc-to-lxd/main_migrate.go index 957ef81803ab..7aa00e2ec59b 100644 --- a/lxc-to-lxd/main_migrate.go +++ b/lxc-to-lxd/main_migrate.go @@ -72,7 +72,7 @@ func (c *cmdMigrate) RunE(cmd *cobra.Command, args []string) error { // Retrieve LXC containers for _, container := range liblxc.Containers(c.flagLXCPath) { - if !c.flagAll && !shared.StringInSlice(container.Name(), c.flagContainers) { + if !c.flagAll && !shared.ValueInSlice(container.Name(), c.flagContainers) { continue } @@ -335,7 +335,7 @@ func convertContainer(d lxd.ContainerServer, container *liblxc.Container, storag if value != nil { for _, cap := range strings.Split(value[0], " ") { // Ignore capabilities that are dropped in LXD containers by default. - if shared.StringInSlice(cap, []string{"mac_admin", "mac_override", "sys_module", + if shared.ValueInSlice(cap, []string{"mac_admin", "mac_override", "sys_module", "sys_time"}) { continue } @@ -570,7 +570,7 @@ func convertStorageConfig(conf []string, devices map[string]map[string]string) e } // Ignore mounts that are present in LXD containers by default. - if shared.StringInSlice(parts[0], []string{"proc", "sysfs"}) { + if shared.ValueInSlice(parts[0], []string{"proc", "sysfs"}) { continue } @@ -578,12 +578,12 @@ func convertStorageConfig(conf []string, devices map[string]map[string]string) e device["type"] = "disk" // Deal with read-only mounts - if shared.StringInSlice("ro", strings.Split(parts[3], ",")) { + if shared.ValueInSlice("ro", strings.Split(parts[3], ",")) { device["readonly"] = "true" } // Deal with optional mounts - if shared.StringInSlice("optional", strings.Split(parts[3], ",")) { + if shared.ValueInSlice("optional", strings.Split(parts[3], ",")) { device["optional"] = "true" } else { if strings.HasPrefix(parts[0], "/") { diff --git a/lxc/action.go b/lxc/action.go index 5c06b7727bdc..086e652f1bdd 100644 --- a/lxc/action.go +++ b/lxc/action.go @@ -126,12 +126,12 @@ func (c *cmdAction) Command(action string) *cobra.Command { cmd.Flags().BoolVar(&c.flagStateless, "stateless", false, i18n.G("Ignore the instance state")) } - if shared.StringInSlice(action, []string{"start", "restart", "stop"}) { + if shared.ValueInSlice(action, []string{"start", "restart", "stop"}) { cmd.Flags().StringVar(&c.flagConsole, "console", "", i18n.G("Immediately attach to the console")+"``") cmd.Flags().Lookup("console").NoOptDefVal = "console" } - if shared.StringInSlice(action, []string{"restart", "stop"}) { + if shared.ValueInSlice(action, []string{"restart", "stop"}) { cmd.Flags().BoolVarP(&c.flagForce, "force", "f", false, i18n.G("Force the instance to stop")) cmd.Flags().IntVar(&c.flagTimeout, "timeout", -1, i18n.G("Time to wait for the instance to shutdown cleanly")+"``") } diff --git a/lxc/cluster.go b/lxc/cluster.go index c354f792467d..61af9aa60942 100644 --- a/lxc/cluster.go +++ b/lxc/cluster.go @@ -548,7 +548,7 @@ Are you really sure you want to force removing %s? (yes/no): `), name) input, _ := reader.ReadString('\n') input = strings.TrimSuffix(input, "\n") - if !shared.StringInSlice(strings.ToLower(input), []string{i18n.G("yes")}) { + if !shared.ValueInSlice(strings.ToLower(input), []string{i18n.G("yes")}) { return fmt.Errorf(i18n.G("User aborted delete operation")) } diff --git a/lxc/cluster_group.go b/lxc/cluster_group.go index c631f77b785e..d4f723f51404 100644 --- a/lxc/cluster_group.go +++ b/lxc/cluster_group.go @@ -487,7 +487,7 @@ func (c *cmdClusterGroupRemove) Run(cmd *cobra.Command, args []string) error { return err } - if !shared.StringInSlice(args[1], member.Groups) { + if !shared.ValueInSlice(args[1], member.Groups) { return fmt.Errorf(i18n.G("Cluster group %s isn't currently applied to %s"), args[1], resource.name) } @@ -661,7 +661,7 @@ func (c *cmdClusterGroupAdd) Run(cmd *cobra.Command, args []string) error { return err } - if shared.StringInSlice(args[1], member.Groups) { + if shared.ValueInSlice(args[1], member.Groups) { return fmt.Errorf(i18n.G("Cluster member %s is already in group %s"), resource.name, args[1]) } diff --git a/lxc/cluster_role.go b/lxc/cluster_role.go index 78c2750f5c4b..5c0762b88b41 100644 --- a/lxc/cluster_role.go +++ b/lxc/cluster_role.go @@ -82,7 +82,7 @@ func (c *cmdClusterRoleAdd) Run(cmd *cobra.Command, args []string) error { memberWritable := member.Writable() newRoles := shared.SplitNTrimSpace(args[1], ",", -1, false) for _, newRole := range newRoles { - if shared.StringInSlice(newRole, memberWritable.Roles) { + if shared.ValueInSlice(newRole, memberWritable.Roles) { return fmt.Errorf(i18n.G("Member %q already has role %q"), resource.name, newRole) } } @@ -138,12 +138,12 @@ func (c *cmdClusterRoleRemove) Run(cmd *cobra.Command, args []string) error { memberWritable := member.Writable() rolesToRemove := shared.SplitNTrimSpace(args[1], ",", -1, false) for _, roleToRemove := range rolesToRemove { - if !shared.StringInSlice(roleToRemove, memberWritable.Roles) { + if !shared.ValueInSlice(roleToRemove, memberWritable.Roles) { return fmt.Errorf(i18n.G("Member %q does not have role %q"), resource.name, roleToRemove) } } - memberWritable.Roles = shared.RemoveElementsFromStringSlice(memberWritable.Roles, rolesToRemove...) + memberWritable.Roles = shared.RemoveElementsFromSlice(memberWritable.Roles, rolesToRemove...) return resource.server.UpdateClusterMember(resource.name, memberWritable, etag) } diff --git a/lxc/config/remote.go b/lxc/config/remote.go index dc34a5d29d2f..b63f34c4920b 100644 --- a/lxc/config/remote.go +++ b/lxc/config/remote.go @@ -95,7 +95,7 @@ func (c *Config) GetInstanceServer(name string) (lxd.InstanceServer, error) { } // HTTPs - if !shared.StringInSlice(remote.AuthType, []string{"candid", "oidc"}) && (args.TLSClientCert == "" || args.TLSClientKey == "") { + if !shared.ValueInSlice(remote.AuthType, []string{"candid", "oidc"}) && (args.TLSClientCert == "" || args.TLSClientKey == "") { return nil, fmt.Errorf("Missing TLS client certificate and key") } @@ -295,7 +295,7 @@ func (c *Config) getConnectionArgs(name string) (*lxd.ConnectionArgs, error) { } // Stop here if no client certificate involved - if remote.Protocol == "simplestreams" || shared.StringInSlice(remote.AuthType, []string{"candid", "oidc"}) { + if remote.Protocol == "simplestreams" || shared.ValueInSlice(remote.AuthType, []string{"candid", "oidc"}) { return &args, nil } diff --git a/lxc/config_trust.go b/lxc/config_trust.go index 993d54677ae9..66dbe99a5dba 100644 --- a/lxc/config_trust.go +++ b/lxc/config_trust.go @@ -115,7 +115,7 @@ func (c *cmdConfigTrustAdd) Run(cmd *cobra.Command, args []string) error { } // Validate flags. - if !shared.StringInSlice(c.flagType, []string{"client", "metrics"}) { + if !shared.ValueInSlice(c.flagType, []string{"client", "metrics"}) { return fmt.Errorf(i18n.G("Unknown certificate type %q"), c.flagType) } diff --git a/lxc/console.go b/lxc/console.go index 3cc068064455..7f5d4081e73f 100644 --- a/lxc/console.go +++ b/lxc/console.go @@ -104,7 +104,7 @@ func (c *cmdConsole) Run(cmd *cobra.Command, args []string) error { } // Validate flags. - if !shared.StringInSlice(c.flagType, []string{"console", "vga"}) { + if !shared.ValueInSlice(c.flagType, []string{"console", "vga"}) { return fmt.Errorf(i18n.G("Unknown output type %q"), c.flagType) } diff --git a/lxc/delete.go b/lxc/delete.go index 42f66e0d0b5b..b073c6c8abda 100644 --- a/lxc/delete.go +++ b/lxc/delete.go @@ -44,7 +44,7 @@ func (c *cmdDelete) promptDelete(name string) error { input, _ := reader.ReadString('\n') input = strings.TrimSuffix(input, "\n") - if !shared.StringInSlice(strings.ToLower(input), []string{i18n.G("yes")}) { + if !shared.ValueInSlice(strings.ToLower(input), []string{i18n.G("yes")}) { return fmt.Errorf(i18n.G("User aborted delete operation")) } diff --git a/lxc/list.go b/lxc/list.go index 14f2611ba158..1b9091ca69f1 100644 --- a/lxc/list.go +++ b/lxc/list.go @@ -765,7 +765,7 @@ func (c *cmdList) IP4ColumnData(cInfo api.InstanceFull) string { } for _, addr := range net.Addresses { - if shared.StringInSlice(addr.Scope, []string{"link", "local"}) { + if shared.ValueInSlice(addr.Scope, []string{"link", "local"}) { continue } @@ -791,7 +791,7 @@ func (c *cmdList) IP6ColumnData(cInfo api.InstanceFull) string { } for _, addr := range net.Addresses { - if shared.StringInSlice(addr.Scope, []string{"link", "local"}) { + if shared.ValueInSlice(addr.Scope, []string{"link", "local"}) { continue } diff --git a/lxc/main.go b/lxc/main.go index 430046e878d3..a329def538c0 100644 --- a/lxc/main.go +++ b/lxc/main.go @@ -391,7 +391,7 @@ func (c *cmdGlobal) PreRun(cmd *cobra.Command, args []string) error { flush = true } - if !shared.StringInSlice(cmd.Name(), []string{"init", "launch"}) { + if !shared.ValueInSlice(cmd.Name(), []string{"init", "launch"}) { fmt.Fprintf(os.Stderr, i18n.G(`To start your first container, try: lxc launch ubuntu:22.04 Or for a virtual machine: lxc launch ubuntu:22.04 --vm`)+"\n") flush = true diff --git a/lxc/monitor.go b/lxc/monitor.go index 07d727a4c1a0..369e6dbc0053 100644 --- a/lxc/monitor.go +++ b/lxc/monitor.go @@ -66,7 +66,7 @@ func (c *cmdMonitor) Run(cmd *cobra.Command, args []string) error { return err } - if !shared.StringInSlice(c.flagFormat, []string{"json", "pretty", "yaml"}) { + if !shared.ValueInSlice(c.flagFormat, []string{"json", "pretty", "yaml"}) { return fmt.Errorf(i18n.G("Invalid format: %s"), c.flagFormat) } diff --git a/lxc/network.go b/lxc/network.go index 54387c92552d..2d4ee59cb8d8 100644 --- a/lxc/network.go +++ b/lxc/network.go @@ -950,7 +950,7 @@ func (c *cmdNetworkList) Run(cmd *cobra.Command, args []string) error { data := [][]string{} for _, network := range networks { - if shared.StringInSlice(network.Type, []string{"loopback", "unknown"}) { + if shared.ValueInSlice(network.Type, []string{"loopback", "unknown"}) { continue } diff --git a/lxc/profile.go b/lxc/profile.go index 6d5bb219d183..8d5dac43bf55 100644 --- a/lxc/profile.go +++ b/lxc/profile.go @@ -704,7 +704,7 @@ func (c *cmdProfileRemove) Run(cmd *cobra.Command, args []string) error { return err } - if !shared.StringInSlice(args[1], inst.Profiles) { + if !shared.ValueInSlice(args[1], inst.Profiles) { return fmt.Errorf(i18n.G("Profile %s isn't currently applied to %s"), args[1], resource.name) } diff --git a/lxc/project.go b/lxc/project.go index 2893db437cc7..e9e5846ffc42 100644 --- a/lxc/project.go +++ b/lxc/project.go @@ -839,7 +839,7 @@ func (c *cmdProjectInfo) Run(cmd *cobra.Command, args []string) error { for k, v := range projectState.Resources { limit := i18n.G("UNLIMITED") if v.Limit >= 0 { - if shared.StringInSlice(k, byteLimits) { + if shared.ValueInSlice(k, byteLimits) { limit = units.GetByteSizeStringIEC(v.Limit, 2) } else { limit = fmt.Sprintf("%d", v.Limit) @@ -847,7 +847,7 @@ func (c *cmdProjectInfo) Run(cmd *cobra.Command, args []string) error { } usage := "" - if shared.StringInSlice(k, byteLimits) { + if shared.ValueInSlice(k, byteLimits) { usage = units.GetByteSizeStringIEC(v.Usage, 2) } else { usage = fmt.Sprintf("%d", v.Usage) diff --git a/lxc/query.go b/lxc/query.go index 07553d4d02f0..3443527e48fd 100644 --- a/lxc/query.go +++ b/lxc/query.go @@ -72,7 +72,7 @@ func (c *cmdQuery) Run(cmd *cobra.Command, args []string) error { return fmt.Errorf(i18n.G("--project cannot be used with the query command")) } - if !shared.StringInSlice(c.flagAction, []string{"GET", "PUT", "POST", "PATCH", "DELETE"}) { + if !shared.ValueInSlice(c.flagAction, []string{"GET", "PUT", "POST", "PATCH", "DELETE"}) { return fmt.Errorf(i18n.G("Action %q isn't supported by this tool"), c.flagAction) } diff --git a/lxc/remote.go b/lxc/remote.go index 0f466f5bcbf5..40c0fd578aa4 100644 --- a/lxc/remote.go +++ b/lxc/remote.go @@ -125,7 +125,7 @@ func (c *cmdRemoteAdd) findProject(d lxd.InstanceServer, project string) (string } // Deal with multiple projects. - if shared.StringInSlice("default", names) { + if shared.ValueInSlice("default", names) { // If we have access to the default project, use it. return "", nil } @@ -509,15 +509,15 @@ func (c *cmdRemoteAdd) Run(cmd *cobra.Command, args []string) error { // If not specified, the preferred order of authentication is 1) OIDC 2) Candid 3) TLS. if c.flagAuthType == "" { - if !srv.Public && shared.StringInSlice("oidc", srv.AuthMethods) { + if !srv.Public && shared.ValueInSlice("oidc", srv.AuthMethods) { c.flagAuthType = "oidc" - } else if !srv.Public && shared.StringInSlice("candid", srv.AuthMethods) { + } else if !srv.Public && shared.ValueInSlice("candid", srv.AuthMethods) { c.flagAuthType = "candid" } else { c.flagAuthType = "tls" } - if shared.StringInSlice(c.flagAuthType, []string{"oidc", "candid"}) { + if shared.ValueInSlice(c.flagAuthType, []string{"oidc", "candid"}) { // Update the remote configuration remote := conf.Remotes[server] remote.AuthType = c.flagAuthType @@ -543,7 +543,7 @@ func (c *cmdRemoteAdd) Run(cmd *cobra.Command, args []string) error { } } - if !srv.Public && !shared.StringInSlice(c.flagAuthType, srv.AuthMethods) { + if !srv.Public && !shared.ValueInSlice(c.flagAuthType, srv.AuthMethods) { return fmt.Errorf(i18n.G("Authentication type '%s' not supported by server"), c.flagAuthType) } diff --git a/lxc/storage_volume.go b/lxc/storage_volume.go index e053eca24712..f24f1c749282 100644 --- a/lxc/storage_volume.go +++ b/lxc/storage_volume.go @@ -135,7 +135,7 @@ func (c *cmdStorageVolume) parseVolume(defaultType string, name string) (string, fields := strings.SplitN(name, "/", 2) if len(fields) == 1 { return fields[0], defaultType - } else if len(fields) == 2 && !shared.StringInSlice(fields[0], []string{"custom", "image", "container", "virtual-machine"}) { + } else if len(fields) == 2 && !shared.ValueInSlice(fields[0], []string{"custom", "image", "container", "virtual-machine"}) { return name, defaultType } @@ -2437,7 +2437,7 @@ func (c *cmdStorageVolumeImport) Run(cmd *cobra.Command, args []string) error { } } else { // Validate type flag - if !shared.StringInSlice(c.flagType, []string{"backup", "iso"}) { + if !shared.ValueInSlice(c.flagType, []string{"backup", "iso"}) { return fmt.Errorf("Import type needs to be \"backup\" or \"iso\"") } } diff --git a/lxd-agent/main_agent.go b/lxd-agent/main_agent.go index 9f37b633ff9b..15f109c8cf35 100644 --- a/lxd-agent/main_agent.go +++ b/lxd-agent/main_agent.go @@ -63,7 +63,7 @@ func (c *cmdAgent) Run(cmd *cobra.Command, args []string) error { } // Sync the hostname. - if shared.PathExists("/proc/sys/kernel/hostname") && shared.StringInSlice("/etc/hostname", files) { + if shared.PathExists("/proc/sys/kernel/hostname") && shared.ValueInSlice("/etc/hostname", files) { // Open the two files. src, err := os.Open("/etc/hostname") if err != nil { @@ -90,7 +90,7 @@ func (c *cmdAgent) Run(cmd *cobra.Command, args []string) error { } // Run cloud-init. - if shared.PathExists("/etc/cloud") && shared.StringInSlice("/var/lib/cloud/seed/nocloud-net/meta-data", files) { + if shared.PathExists("/etc/cloud") && shared.ValueInSlice("/var/lib/cloud/seed/nocloud-net/meta-data", files) { logger.Info("Seeding cloud-init") cloudInitPath := "/run/cloud-init" diff --git a/lxd-agent/metrics.go b/lxd-agent/metrics.go index 9ea288dca308..494c979d61b0 100644 --- a/lxd-agent/metrics.go +++ b/lxd-agent/metrics.go @@ -274,7 +274,7 @@ func getFilesystemMetrics(d *Daemon) (map[string]metrics.FilesystemMetrics, erro } // Skip uninteresting mounts - if shared.StringInSlice(fields[2], defFSTypesExcluded) || defMountPointsExcluded.MatchString(fields[1]) { + if shared.ValueInSlice(fields[2], defFSTypesExcluded) || defMountPointsExcluded.MatchString(fields[1]) { continue } diff --git a/lxd-migrate/main_migrate.go b/lxd-migrate/main_migrate.go index 5fe6a6a17143..8a94eb6c8350 100644 --- a/lxd-migrate/main_migrate.go +++ b/lxd-migrate/main_migrate.go @@ -172,13 +172,13 @@ func (c *cmdMigrate) askServer() (lxd.InstanceServer, string, error) { i := 1 - if shared.StringInSlice("candid", apiServer.AuthMethods) { + if shared.ValueInSlice("candid", apiServer.AuthMethods) { fmt.Printf("%d) Candid/RBAC based authentication\n", i) availableAuthMethods = append(availableAuthMethods, authMethodCandid) i++ } - if shared.StringInSlice("tls", apiServer.AuthMethods) { + if shared.ValueInSlice("tls", apiServer.AuthMethods) { fmt.Printf("%d) Use a certificate token\n", i) availableAuthMethods = append(availableAuthMethods, authMethodTLSCertificateToken) i++ @@ -189,7 +189,7 @@ func (c *cmdMigrate) askServer() (lxd.InstanceServer, string, error) { availableAuthMethods = append(availableAuthMethods, authMethodTLSTemporaryCertificate) } - if len(apiServer.AuthMethods) > 1 || shared.StringInSlice("tls", apiServer.AuthMethods) { + if len(apiServer.AuthMethods) > 1 || shared.ValueInSlice("tls", apiServer.AuthMethods) { authMethodInt, err := c.global.asker.AskInt("Please pick an authentication mechanism above: ", 1, int64(i), "", nil) if err != nil { return nil, "", err @@ -306,7 +306,7 @@ func (c *cmdMigrate) RunInteractive(server lxd.InstanceServer) (cmdMigrateData, return cmdMigrateData{}, err } - if shared.StringInSlice(instanceName, instanceNames) { + if shared.ValueInSlice(instanceName, instanceNames) { fmt.Printf("Instance %q already exists\n", instanceName) continue } @@ -343,7 +343,7 @@ func (c *cmdMigrate) RunInteractive(server lxd.InstanceServer) (cmdMigrateData, if config.InstanceArgs.Type == api.InstanceTypeVM { architectureName, _ := osarch.ArchitectureGetLocal() - if shared.StringInSlice(architectureName, []string{"x86_64", "aarch64"}) { + if shared.ValueInSlice(architectureName, []string{"x86_64", "aarch64"}) { hasSecureBoot, err := c.global.asker.AskBool("Does the VM support UEFI Secure Boot? [default=no]: ", "no") if err != nil { return cmdMigrateData{}, err @@ -604,7 +604,7 @@ func (c *cmdMigrate) askProfiles(server lxd.InstanceServer, config *cmdMigrateDa profiles := strings.Split(s, " ") for _, profile := range profiles { - if !shared.StringInSlice(profile, profileNames) { + if !shared.ValueInSlice(profile, profileNames) { return fmt.Errorf("Unknown profile %q", profile) } } diff --git a/lxd-user/lxd.go b/lxd-user/lxd.go index f720a1d0d6ee..ef0bf1701a9b 100644 --- a/lxd-user/lxd.go +++ b/lxd-user/lxd.go @@ -21,7 +21,7 @@ func lxdIsConfigured(client lxd.InstanceServer) (bool, error) { return false, fmt.Errorf("Failed to list networks: %w", err) } - if !shared.StringInSlice("lxdbr0", networks) { + if !shared.ValueInSlice("lxdbr0", networks) { // Couldn't find lxdbr0. return false, nil } @@ -32,7 +32,7 @@ func lxdIsConfigured(client lxd.InstanceServer) (bool, error) { return false, fmt.Errorf("Failed to list storage pools: %w", err) } - if !shared.StringInSlice("default", pools) { + if !shared.ValueInSlice("default", pools) { // No storage pool found. return false, nil } @@ -67,7 +67,7 @@ func lxdInitialConfiguration(client lxd.InstanceServer) error { pool.Name = "default" // Check if ZFS supported. - if shared.StringInSlice("zfs", availableBackends) { + if shared.ValueInSlice("zfs", availableBackends) { pool.Driver = "zfs" // Check if zsys. @@ -185,7 +185,7 @@ func lxdSetupUser(uid uint32) error { return fmt.Errorf("Unable to retrieve project list: %w", err) } - if !shared.StringInSlice(projectName, projects) { + if !shared.ValueInSlice(projectName, projects) { // Create the project. err := client.CreateProject(api.ProjectsPost{ Name: projectName, diff --git a/lxd/acme/acme.go b/lxd/acme/acme.go index 720892c44fd6..d9e9d4b18528 100644 --- a/lxd/acme/acme.go +++ b/lxd/acme/acme.go @@ -35,7 +35,7 @@ const ClusterCertFilename = "cluster.crt.new" // certificateNeedsUpdate returns true if the domain doesn't match the certificate's DNS names // or it's valid for less than 30 days. func certificateNeedsUpdate(domain string, cert *x509.Certificate) bool { - return !shared.StringInSlice(domain, cert.DNSNames) || time.Now().After(cert.NotAfter.Add(-30*24*time.Hour)) + return !shared.ValueInSlice(domain, cert.DNSNames) || time.Now().After(cert.NotAfter.Add(-30*24*time.Hour)) } // UpdateCertificate updates the certificate. diff --git a/lxd/api_cluster.go b/lxd/api_cluster.go index ff8a9624de67..8f7b95f73c3c 100644 --- a/lxd/api_cluster.go +++ b/lxd/api_cluster.go @@ -951,7 +951,7 @@ func clusterInitMember(d lxd.InstanceServer, client lxd.InstanceServer, memberCo continue } - if !shared.StringInSlice(config.Key, db.NodeSpecificStorageConfig) { + if !shared.ValueInSlice(config.Key, db.NodeSpecificStorageConfig) { logger.Warnf("Ignoring config key %q for storage pool %q", config.Key, config.Name) continue } @@ -1017,7 +1017,7 @@ func clusterInitMember(d lxd.InstanceServer, client lxd.InstanceServer, memberCo continue } - if !shared.StringInSlice(config.Key, db.NodeSpecificNetworkConfig) { + if !shared.ValueInSlice(config.Key, db.NodeSpecificNetworkConfig) { logger.Warnf("Ignoring config key %q for network %q in project %q", config.Key, config.Name, p.Name) continue } @@ -1644,11 +1644,11 @@ func updateClusterNode(s *state.State, gateway *cluster.Gateway, r *http.Request } // Validate the request - if shared.StringInSlice(string(db.ClusterRoleDatabase), memberInfo.Roles) && !shared.StringInSlice(string(db.ClusterRoleDatabase), req.Roles) { + if shared.ValueInSlice(string(db.ClusterRoleDatabase), memberInfo.Roles) && !shared.ValueInSlice(string(db.ClusterRoleDatabase), req.Roles) { return response.BadRequest(fmt.Errorf("The %q role cannot be dropped at this time", db.ClusterRoleDatabase)) } - if !shared.StringInSlice(string(db.ClusterRoleDatabase), memberInfo.Roles) && shared.StringInSlice(string(db.ClusterRoleDatabase), req.Roles) { + if !shared.ValueInSlice(string(db.ClusterRoleDatabase), memberInfo.Roles) && shared.ValueInSlice(string(db.ClusterRoleDatabase), req.Roles) { return response.BadRequest(fmt.Errorf("The %q role cannot be added at this time", db.ClusterRoleDatabase)) } @@ -4014,7 +4014,7 @@ func clusterGroupPut(d *Daemon, r *http.Request) response.Response { skipMembers := []string{} for _, oldMember := range members { - if !shared.StringInSlice(oldMember, req.Members) { + if !shared.ValueInSlice(oldMember, req.Members) { // Get all cluster groups this member belongs to. groups, err := tx.GetClusterGroupsWithNode(ctx, oldMember) if err != nil { @@ -4037,7 +4037,7 @@ func clusterGroupPut(d *Daemon, r *http.Request) response.Response { for _, member := range req.Members { // Skip these members as they already belong to this group. - if shared.StringInSlice(member, skipMembers) { + if shared.ValueInSlice(member, skipMembers) { continue } @@ -4192,7 +4192,7 @@ func clusterGroupPatch(d *Daemon, r *http.Request) response.Response { skipMembers := []string{} for _, oldMember := range members { - if !shared.StringInSlice(oldMember, req.Members) { + if !shared.ValueInSlice(oldMember, req.Members) { // Get all cluster groups this member belongs to. groups, err := tx.GetClusterGroupsWithNode(ctx, oldMember) if err != nil { @@ -4216,7 +4216,7 @@ func clusterGroupPatch(d *Daemon, r *http.Request) response.Response { for _, member := range req.Members { // Skip these members as they already belong to this group. - if shared.StringInSlice(member, skipMembers) { + if shared.ValueInSlice(member, skipMembers) { continue } @@ -4318,7 +4318,7 @@ func clusterGroupValidateName(name string) error { return fmt.Errorf("Reserved cluster group name") } - if shared.StringInSlice(name, []string{".", ".."}) { + if shared.ValueInSlice(name, []string{".", ".."}) { return fmt.Errorf("Invalid cluster group name %q", name) } diff --git a/lxd/api_internal.go b/lxd/api_internal.go index edbf3ff2be7b..fd37bd28b44d 100644 --- a/lxd/api_internal.go +++ b/lxd/api_internal.go @@ -418,7 +418,7 @@ func internalSQLGet(d *Daemon, r *http.Request) response.Response { database := r.FormValue("database") - if !shared.StringInSlice(database, []string{"local", "global"}) { + if !shared.ValueInSlice(database, []string{"local", "global"}) { return response.BadRequest(fmt.Errorf("Invalid database")) } @@ -461,7 +461,7 @@ func internalSQLPost(d *Daemon, r *http.Request) response.Response { return response.BadRequest(err) } - if !shared.StringInSlice(req.Database, []string{"local", "global"}) { + if !shared.ValueInSlice(req.Database, []string{"local", "global"}) { return response.BadRequest(fmt.Errorf("Invalid database")) } diff --git a/lxd/api_internal_recover.go b/lxd/api_internal_recover.go index 9840c428d077..87ff4117a7e9 100644 --- a/lxd/api_internal_recover.go +++ b/lxd/api_internal_recover.go @@ -144,7 +144,7 @@ func internalRecoverScan(s *state.State, userPools []api.StoragePoolsPost, valid addDependencyError := func(err error) { errStr := err.Error() - if !shared.StringInSlice(errStr, res.DependencyErrors) { + if !shared.ValueInSlice(errStr, res.DependencyErrors) { res.DependencyErrors = append(res.DependencyErrors, errStr) } } diff --git a/lxd/api_metrics.go b/lxd/api_metrics.go index d7ea47a96254..2dfaef7c4998 100644 --- a/lxd/api_metrics.go +++ b/lxd/api_metrics.go @@ -274,7 +274,7 @@ func metricsGet(d *Daemon, r *http.Request) response.Response { } for _, project := range projectsToFetch { - if shared.StringInSlice(*project.Project, updatedProjects) { + if shared.ValueInSlice(*project.Project, updatedProjects) { continue } diff --git a/lxd/api_project.go b/lxd/api_project.go index a100d9fabda9..620f25b1d3d9 100644 --- a/lxd/api_project.go +++ b/lxd/api_project.go @@ -721,7 +721,7 @@ func projectChange(s *state.State, project *api.Project, req api.ProjectPut) res return fmt.Errorf("Persist profile changes: %w", err) } - if shared.StringInSlice("features.profiles", configChanged) { + if shared.ValueInSlice("features.profiles", configChanged) { if shared.IsTrue(req.Config["features.profiles"]) { err = projectCreateDefaultProfile(tx, project.Name) if err != nil { @@ -736,7 +736,7 @@ func projectChange(s *state.State, project *api.Project, req api.ProjectPut) res } } - if shared.StringInSlice("features.images", configChanged) && shared.IsFalse(req.Config["features.images"]) && shared.IsTrue(req.Config["features.profiles"]) { + if shared.ValueInSlice("features.images", configChanged) && shared.IsFalse(req.Config["features.images"]) && shared.IsTrue(req.Config["features.profiles"]) { err = cluster.InitProjectWithoutImages(ctx, tx.Tx(), project.Name) if err != nil { return err @@ -1484,7 +1484,7 @@ func projectValidateName(name string) error { return fmt.Errorf("Reserved project name") } - if shared.StringInSlice(name, []string{".", ".."}) { + if shared.ValueInSlice(name, []string{".", ".."}) { return fmt.Errorf("Invalid project name %q", name) } diff --git a/lxd/apparmor/instance_forkproxy.go b/lxd/apparmor/instance_forkproxy.go index 7b8142962982..2483303a74aa 100644 --- a/lxd/apparmor/instance_forkproxy.go +++ b/lxd/apparmor/instance_forkproxy.go @@ -143,7 +143,7 @@ func forkproxyProfile(sysOS *sys.OS, inst instance, dev device) (string, error) return "", err } - if !shared.StringInSlice(v, sockets) { + if !shared.ValueInSlice(v, sockets) { sockets = append(sockets, v) } } diff --git a/lxd/auth/candid/identity.go b/lxd/auth/candid/identity.go index 0baec565eb24..b081397869a0 100644 --- a/lxd/auth/candid/identity.go +++ b/lxd/auth/candid/identity.go @@ -37,7 +37,7 @@ func (m *IdentityClientWrapper) DeclaredIdentity(ctx context.Context, declared m } // Check that it was a valid domain - if !shared.StringInSlice(fields[1], m.ValidDomains) { + if !shared.ValueInSlice(fields[1], m.ValidDomains) { logger.Warnf("Failed candid client authentication: untrusted domain \"%s\"", fields[1]) return nil, fmt.Errorf("Untrusted candid domain") } diff --git a/lxd/auth/driver_rbac.go b/lxd/auth/driver_rbac.go index 016c70d7fe3e..e8685638c115 100644 --- a/lxd/auth/driver_rbac.go +++ b/lxd/auth/driver_rbac.go @@ -362,7 +362,7 @@ func (r *rbac) UserAccess(username string) (*UserAccess, error) { // Prepare the response. access := UserAccess{ - Admin: shared.StringInSlice("admin", permissions[""]), + Admin: shared.ValueInSlice("admin", permissions[""]), Projects: map[string][]string{}, } @@ -435,7 +435,7 @@ func (r *rbac) syncAdmin(username string) bool { return false } - return shared.StringInSlice("admin", permissions[""]) + return shared.ValueInSlice("admin", permissions[""]) } func (r *rbac) syncPermissions(username string) error { diff --git a/lxd/auth/driver_tls.go b/lxd/auth/driver_tls.go index d503f30f5698..1c41b71ba7c7 100644 --- a/lxd/auth/driver_tls.go +++ b/lxd/auth/driver_tls.go @@ -61,5 +61,5 @@ func (a *tls) UserHasPermission(r *http.Request, projectName string, permission return true } - return shared.StringInSlice(permission, ua.Projects[projectName]) + return shared.ValueInSlice(permission, ua.Projects[projectName]) } diff --git a/lxd/auth/oidc/oidc.go b/lxd/auth/oidc/oidc.go index 544541e520fa..e6b8e84d2d8f 100644 --- a/lxd/auth/oidc/oidc.go +++ b/lxd/auth/oidc/oidc.go @@ -235,7 +235,7 @@ func (o *Verifier) VerifyAccessToken(ctx context.Context, token string) (*oidc.A // Check that the token includes the configured audience. audience := claims.GetAudience() - if o.audience != "" && !shared.StringInSlice(o.audience, audience) { + if o.audience != "" && !shared.ValueInSlice(o.audience, audience) { return nil, fmt.Errorf("Provided OIDC token doesn't allow the configured audience") } diff --git a/lxd/cgroup/abstraction.go b/lxd/cgroup/abstraction.go index 62fa82c8a9ec..ce582dd4be76 100644 --- a/lxd/cgroup/abstraction.go +++ b/lxd/cgroup/abstraction.go @@ -674,11 +674,11 @@ func (cg *CGroup) SetBlkioWeight(limit int64) error { // SetBlkioLimit sets the specified read or write limit for a device. func (cg *CGroup) SetBlkioLimit(dev string, oType string, uType string, limit int64) error { - if !shared.StringInSlice(oType, []string{"read", "write"}) { + if !shared.ValueInSlice(oType, []string{"read", "write"}) { return fmt.Errorf("Invalid I/O operation type: %s", oType) } - if !shared.StringInSlice(uType, []string{"iops", "bps"}) { + if !shared.ValueInSlice(uType, []string{"iops", "bps"}) { return fmt.Errorf("Invalid I/O limit type: %s", uType) } diff --git a/lxd/cluster/events.go b/lxd/cluster/events.go index 2d3b78039d26..73942dfffb21 100644 --- a/lxd/cluster/events.go +++ b/lxd/cluster/events.go @@ -323,7 +323,7 @@ func EventsUpdateListeners(endpoints *endpoints.Endpoints, cluster *db.Cluster, // Indicate to any notifiers waiting for this member's address that it is connected. for connected, notifyAddresses := range listenersNotify { - if shared.StringInSlice(m.Address, notifyAddresses) { + if shared.ValueInSlice(m.Address, notifyAddresses) { close(connected) delete(listenersNotify, connected) } diff --git a/lxd/cluster/membership.go b/lxd/cluster/membership.go index 0373aae61e49..8c96f25ba3d2 100644 --- a/lxd/cluster/membership.go +++ b/lxd/cluster/membership.go @@ -479,7 +479,7 @@ func Join(state *state.State, gateway *Gateway, networkCert *shared.CertInfo, se return fmt.Errorf("Failed to add joining node's pool config: %w", err) } - if shared.StringInSlice(driver, []string{"ceph", "cephfs"}) { + if shared.ValueInSlice(driver, []string{"ceph", "cephfs"}) { // For ceph pools we have to create volume // entries for the joining node. err := tx.UpdateCephStoragePoolAfterNodeJoin(ctx, id, node.ID) @@ -1016,7 +1016,7 @@ func newRolesChanges(state *state.State, gateway *Gateway, nodes []db.RaftNode, cluster := map[client.NodeInfo]*client.NodeMetadata{} for _, node := range nodes { - if !shared.StringInSlice(node.Address, unavailableMembers) && HasConnectivity(gateway.networkCert, gateway.state().ServerCert(), node.Address) { + if !shared.ValueInSlice(node.Address, unavailableMembers) && HasConnectivity(gateway.networkCert, gateway.state().ServerCert(), node.Address) { cluster[node.NodeInfo] = &client.NodeMetadata{ FailureDomain: domains[node.Address], } diff --git a/lxd/cluster/notify_test.go b/lxd/cluster/notify_test.go index fcfaffa40e08..8195cb52e70f 100644 --- a/lxd/cluster/notify_test.go +++ b/lxd/cluster/notify_test.go @@ -64,7 +64,7 @@ func TestNewNotifier(t *testing.T) { } require.NoError(t, err) for i := range addresses { - assert.True(t, shared.StringInSlice(f.Address(i+1), addresses)) + assert.True(t, shared.ValueInSlice(f.Address(i+1), addresses)) } } diff --git a/lxd/config/schema.go b/lxd/config/schema.go index d12c4ae2999e..9ec4b2d17e64 100644 --- a/lxd/config/schema.go +++ b/lxd/config/schema.go @@ -102,7 +102,7 @@ func (v *Key) validate(value string) error { switch v.Type { case String: case Bool: - if !shared.StringInSlice(strings.ToLower(value), booleans) { + if !shared.ValueInSlice(strings.ToLower(value), booleans) { return fmt.Errorf("invalid boolean") } diff --git a/lxd/daemon.go b/lxd/daemon.go index 8067d3b0e1ad..8010117f7f3a 100644 --- a/lxd/daemon.go +++ b/lxd/daemon.go @@ -483,7 +483,7 @@ func (d *Daemon) createCmd(restAPI *mux.Router, version string, c APIEndpoint) { } // Reject internal queries to remote, non-cluster, clients - if version == "internal" && !shared.StringInSlice(protocol, []string{"unix", "cluster"}) { + if version == "internal" && !shared.ValueInSlice(protocol, []string{"unix", "cluster"}) { // Except for the initial cluster accept request (done over trusted TLS) if !trusted || c.Path != "cluster/accept" || protocol != "tls" { logger.Warn("Rejecting remote internal API request", logger.Ctx{"ip": r.RemoteAddr}) @@ -1054,7 +1054,7 @@ func (d *Daemon) init() error { /* Setup dqlite */ clusterLogLevel := "ERROR" - if shared.StringInSlice("dqlite", trace) { + if shared.ValueInSlice("dqlite", trace) { clusterLogLevel = "TRACE" } @@ -1160,7 +1160,7 @@ func (d *Daemon) init() error { driver.WithLogFunc(cluster.DqliteLog), } - if shared.StringInSlice("database", trace) { + if shared.ValueInSlice("database", trace) { options = append(options, driver.WithTracing(dqliteClient.LogDebug)) } diff --git a/lxd/daemon_images.go b/lxd/daemon_images.go index e22286f0e333..b0ca8b3d326e 100644 --- a/lxd/daemon_images.go +++ b/lxd/daemon_images.go @@ -77,7 +77,7 @@ func ImageDownload(r *http.Request, s *state.State, op *operations.Operation, ar fp := alias // Attempt to resolve the alias - if shared.StringInSlice(protocol, []string{"lxd", "simplestreams"}) { + if shared.ValueInSlice(protocol, []string{"lxd", "simplestreams"}) { clientArgs := &lxd.ConnectionArgs{ TLSServerCert: args.Certificate, UserAgent: version.UserAgent, @@ -244,7 +244,7 @@ func ImageDownload(r *http.Request, s *state.State, op *operations.Operation, ar return nil, err } - if shared.Int64InSlice(poolID, poolIDs) { + if shared.ValueInSlice(poolID, poolIDs) { logger.Debug("Image already exists on storage pool", ctxMap) return info, nil } diff --git a/lxd/db/generate/db/mapping.go b/lxd/db/generate/db/mapping.go index 741063d91320..2d932e31eb38 100644 --- a/lxd/db/generate/db/mapping.go +++ b/lxd/db/generate/db/mapping.go @@ -153,7 +153,7 @@ func (m *Mapping) ColumnFields(exclude ...string) []*Field { fields := []*Field{} for _, field := range m.Fields { - if shared.StringInSlice(field.Name, exclude) { + if shared.ValueInSlice(field.Name, exclude) { continue } diff --git a/lxd/db/generate/db/parse.go b/lxd/db/generate/db/parse.go index 119fada14786..c54545f4bab1 100644 --- a/lxd/db/generate/db/parse.go +++ b/lxd/db/generate/db/parse.go @@ -76,7 +76,7 @@ func FiltersFromStmt(pkg *ast.Package, kind string, entity string, filters []*Fi for _, filterGroup := range stmtFilters { ignoredFilterGroup := []string{} for _, filter := range filters { - if !shared.StringInSlice(filter.Name, filterGroup) { + if !shared.ValueInSlice(filter.Name, filterGroup) { ignoredFilterGroup = append(ignoredFilterGroup, filter.Name) } } @@ -108,7 +108,7 @@ func RefFiltersFromStmt(pkg *ast.Package, entity string, ref string, filters []* for _, filterGroup := range stmtFilters { ignoredFilterGroup := []string{} for _, filter := range filters { - if !shared.StringInSlice(filter.Name, filterGroup) { + if !shared.ValueInSlice(filter.Name, filterGroup) { ignoredFilterGroup = append(ignoredFilterGroup, filter.Name) } } @@ -269,8 +269,8 @@ func tableType(pkg *ast.Package, name string, fields []*Field) TableType { } } - if shared.StringInSlice("ReferenceID", fieldNames) { - if shared.StringInSlice("Key", fieldNames) && shared.StringInSlice("Value", fieldNames) { + if shared.ValueInSlice("ReferenceID", fieldNames) { + if shared.ValueInSlice("Key", fieldNames) && shared.ValueInSlice("Value", fieldNames) { return MapTable } @@ -410,9 +410,9 @@ func parseField(f *ast.Field, kind string) (*Field, error) { stmtKind = "delete" } - if shared.StringInSlice(kind, omitFields) || shared.StringInSlice(stmtKind, omitFields) { + if shared.ValueInSlice(kind, omitFields) || shared.ValueInSlice(stmtKind, omitFields) { return nil, nil - } else if kind == "exists" && shared.StringInSlice("id", omitFields) { + } else if kind == "exists" && shared.ValueInSlice("id", omitFields) { // Exists checks ID, so if we are omitting the field from ID, also omit it from Exists. return nil, nil } diff --git a/lxd/db/migration.go b/lxd/db/migration.go index bef8e95693f5..2e1324956c42 100644 --- a/lxd/db/migration.go +++ b/lxd/db/migration.go @@ -172,7 +172,7 @@ func importPreClusteringData(tx *sql.Tx, dump *Dump) error { continue } - if column == "key" && shared.StringInSlice(value, keys) { + if column == "key" && shared.ValueInSlice(value, keys) { skip = true } } @@ -195,7 +195,7 @@ func importPreClusteringData(tx *sql.Tx, dump *Dump) error { } } key := row[index].(string) - if !shared.StringInSlice(key, NodeSpecificNetworkConfig) { + if !shared.ValueInSlice(key, NodeSpecificNetworkConfig) { nullNodeID = true break } @@ -214,7 +214,7 @@ func importPreClusteringData(tx *sql.Tx, dump *Dump) error { } } key := row[index].(string) - if !shared.StringInSlice(key, NodeSpecificStorageConfig) { + if !shared.ValueInSlice(key, NodeSpecificStorageConfig) { nullNodeID = true break } @@ -229,7 +229,7 @@ func importPreClusteringData(tx *sql.Tx, dump *Dump) error { appendNodeID() } - if shared.StringInSlice(table, preClusteringTablesRequiringProjectID) { + if shared.ValueInSlice(table, preClusteringTablesRequiringProjectID) { // These tables have a project_id reference in the new schema. columns = append(columns, "project_id") row = append(row, 1) // Reference the default project. @@ -252,7 +252,7 @@ func importPreClusteringData(tx *sql.Tx, dump *Dump) error { } // Also insert the image ID to node ID association. - if shared.StringInSlice(table, []string{"images", "networks", "storage_pools"}) { + if shared.ValueInSlice(table, []string{"images", "networks", "storage_pools"}) { entity := table[:len(table)-1] err := importNodeAssociation(entity, columns, row, tx) if err != nil { diff --git a/lxd/db/networks.go b/lxd/db/networks.go index 7d62828ef360..2e860b2423ec 100644 --- a/lxd/db/networks.go +++ b/lxd/db/networks.go @@ -264,7 +264,7 @@ WHERE networks.id = ? AND networks.state = ? // Figure which nodes are missing missing := []string{} for _, node := range nodes { - if !shared.StringInSlice(node.Name, defined) { + if !shared.ValueInSlice(node.Name, defined) { missing = append(missing, node.Name) } } @@ -847,7 +847,7 @@ func networkConfigAdd(tx *sql.Tx, networkID, nodeID int64, config map[string]str } var nodeIDValue any - if !shared.StringInSlice(k, NodeSpecificNetworkConfig) { + if !shared.ValueInSlice(k, NodeSpecificNetworkConfig) { nodeIDValue = nil } else { nodeIDValue = nodeID diff --git a/lxd/db/node.go b/lxd/db/node.go index 41f0224d8b85..2463256ee7fa 100644 --- a/lxd/db/node.go +++ b/lxd/db/node.go @@ -681,7 +681,7 @@ func (c *ClusterTx) UpdateNodeClusterGroups(ctx context.Context, id int64, group // Check if node already belongs to the given groups. for _, newGroup := range groups { - if shared.StringInSlice(newGroup, oldGroups) { + if shared.ValueInSlice(newGroup, oldGroups) { // Node already belongs to this group. skipGroups = append(skipGroups, newGroup) continue @@ -695,7 +695,7 @@ func (c *ClusterTx) UpdateNodeClusterGroups(ctx context.Context, id int64, group } for _, oldGroup := range oldGroups { - if shared.StringInSlice(oldGroup, skipGroups) { + if shared.ValueInSlice(oldGroup, skipGroups) { continue } @@ -1065,12 +1065,12 @@ func (c *ClusterTx) GetCandidateMembers(ctx context.Context, allMembers []NodeIn } // Skip group-only members if targeted cluster group doesn't match. - if member.Config["scheduler.instance"] == "group" && !shared.StringInSlice(targetClusterGroup, member.Groups) { + if member.Config["scheduler.instance"] == "group" && !shared.ValueInSlice(targetClusterGroup, member.Groups) { continue } // Skip if a group is requested and member isn't part of it. - if targetClusterGroup != "" && !shared.StringInSlice(targetClusterGroup, member.Groups) { + if targetClusterGroup != "" && !shared.ValueInSlice(targetClusterGroup, member.Groups) { continue } @@ -1078,7 +1078,7 @@ func (c *ClusterTx) GetCandidateMembers(ctx context.Context, allMembers []NodeIn if allowedClusterGroups != nil { found := false for _, allowedClusterGroup := range allowedClusterGroups { - if shared.StringInSlice(allowedClusterGroup, member.Groups) { + if shared.ValueInSlice(allowedClusterGroup, member.Groups) { found = true break } @@ -1099,7 +1099,7 @@ func (c *ClusterTx) GetCandidateMembers(ctx context.Context, allMembers []NodeIn supportedArchitectures := append([]int{member.Architecture}, personalities...) for _, supportedArchitecture := range supportedArchitectures { - if shared.IntInSlice(supportedArchitecture, targetArchitectures) { + if shared.ValueInSlice(supportedArchitecture, targetArchitectures) { candidateMembers = append(candidateMembers, member) break } diff --git a/lxd/db/node/update_test.go b/lxd/db/node/update_test.go index 9ed5a18c1d11..ba70fa93b676 100644 --- a/lxd/db/node/update_test.go +++ b/lxd/db/node/update_test.go @@ -60,7 +60,7 @@ func TestUpdateFromV36_DropTables(t *testing.T) { } for _, name := range deleted { - assert.False(t, shared.StringInSlice(name, current)) + assert.False(t, shared.ValueInSlice(name, current)) } } diff --git a/lxd/db/schema/schema.go b/lxd/db/schema/schema.go index 84faa68b9a24..c677bda91421 100644 --- a/lxd/db/schema/schema.go +++ b/lxd/db/schema/schema.go @@ -302,7 +302,7 @@ func queryCurrentVersion(ctx context.Context, tx *sql.Tx) (int, error) { } // Fix bad upgrade code between 30 and 32 - hasVersion := func(v int) bool { return shared.IntInSlice(v, versions) } + hasVersion := func(v int) bool { return shared.ValueInSlice(v, versions) } if hasVersion(30) && hasVersion(32) && !hasVersion(31) { err = insertSchemaVersion(tx, 31) if err != nil { diff --git a/lxd/db/storage_pools.go b/lxd/db/storage_pools.go index 0f6a71a15c5b..15abb3cf8b18 100644 --- a/lxd/db/storage_pools.go +++ b/lxd/db/storage_pools.go @@ -533,7 +533,7 @@ WHERE storage_pools.id = ? AND storage_pools.state = ? // Figure which nodes are missing missing := []string{} for _, node := range nodes { - if !shared.StringInSlice(node.Name, defined) { + if !shared.ValueInSlice(node.Name, defined) { missing = append(missing, node.Name) } } @@ -827,7 +827,7 @@ func storagePoolConfigAdd(tx *sql.Tx, poolID, nodeID int64, poolConfig map[strin } var nodeIDValue any - if !shared.StringInSlice(k, NodeSpecificStorageConfig) { + if !shared.ValueInSlice(k, NodeSpecificStorageConfig) { nodeIDValue = nil } else { nodeIDValue = nodeID @@ -923,7 +923,7 @@ func (c *Cluster) IsRemoteStorage(poolID int64) (bool, error) { return err } - isRemoteStorage = shared.StringInSlice(driver, StorageRemoteDriverNames()) + isRemoteStorage = shared.ValueInSlice(driver, StorageRemoteDriverNames()) return nil }) diff --git a/lxd/db/storage_volumes.go b/lxd/db/storage_volumes.go index e30424075efc..73e84b0793ef 100644 --- a/lxd/db/storage_volumes.go +++ b/lxd/db/storage_volumes.go @@ -478,7 +478,7 @@ func (c *Cluster) CreateStoragePoolVolume(projectName string, volumeName string, var result sql.Result - if shared.StringInSlice(driver, remoteDrivers) { + if shared.ValueInSlice(driver, remoteDrivers) { result, err = tx.tx.Exec(` INSERT INTO storage_volumes (storage_pool_id, type, name, description, project_id, content_type, creation_date) VALUES (?, ?, ?, ?, (SELECT id FROM projects WHERE name = ?), ?, ?) @@ -699,7 +699,7 @@ func (c *ClusterTx) GetStorageVolumeNodes(ctx context.Context, poolID int64, pro } remoteDrivers := StorageRemoteDriverNames() - if shared.StringInSlice(driver, remoteDrivers) { + if shared.ValueInSlice(driver, remoteDrivers) { return nil, ErrNoClusterMember } } diff --git a/lxd/db/warnings.go b/lxd/db/warnings.go index 1baaf5773a2c..ec4656e0b6c7 100644 --- a/lxd/db/warnings.go +++ b/lxd/db/warnings.go @@ -193,7 +193,7 @@ func (c *ClusterTx) createWarning(ctx context.Context, object cluster.Warning) ( return -1, fmt.Errorf("Failed to get project names: %w", err) } - if !shared.StringInSlice(object.Project, projects) { + if !shared.ValueInSlice(object.Project, projects) { return -1, fmt.Errorf("Unknown project %q", object.Project) } diff --git a/lxd/device/device_utils_disk.go b/lxd/device/device_utils_disk.go index 3434fe3b205e..910df23b9b70 100644 --- a/lxd/device/device_utils_disk.go +++ b/lxd/device/device_utils_disk.go @@ -99,7 +99,7 @@ func DiskMount(srcPath string, dstPath string, recursive bool, propagation strin flags, mountOptionsStr := filesystem.ResolveMountOptions(mountOptions) var readonly bool - if shared.StringInSlice("ro", mountOptions) { + if shared.ValueInSlice("ro", mountOptions) { readonly = true } diff --git a/lxd/device/device_utils_network.go b/lxd/device/device_utils_network.go index bff497c01b18..97eae024f61f 100644 --- a/lxd/device/device_utils_network.go +++ b/lxd/device/device_utils_network.go @@ -603,7 +603,7 @@ func networkClearHostVethLimits(d *deviceCommon) error { // networkValidGateway validates the gateway value. func networkValidGateway(value string) error { - if shared.StringInSlice(value, []string{"none", "auto"}) { + if shared.ValueInSlice(value, []string{"none", "auto"}) { return nil } diff --git a/lxd/device/device_utils_unix.go b/lxd/device/device_utils_unix.go index 663325d1e03a..7427152d1109 100644 --- a/lxd/device/device_utils_unix.go +++ b/lxd/device/device_utils_unix.go @@ -106,7 +106,7 @@ func UnixDeviceCreate(s *state.State, idmapSet *idmap.IdmapSet, devicesPath stri // Extra checks for nesting. if s.OS.RunningInUserNS { for key, value := range m { - if shared.StringInSlice(key, []string{"major", "minor", "mode", "uid", "gid"}) && value != "" { + if shared.ValueInSlice(key, []string{"major", "minor", "mode", "uid", "gid"}) && value != "" { return nil, fmt.Errorf("The \"%s\" property may not be set when adding a device to a nested container", key) } } diff --git a/lxd/device/disk.go b/lxd/device/disk.go index 5e9b0ff4a3e4..35ae0e694b16 100644 --- a/lxd/device/disk.go +++ b/lxd/device/disk.go @@ -168,7 +168,7 @@ func (d *disk) validateConfig(instConf instance.ConfigReader) error { // These come from https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt propagationTypes := []string{"", "private", "shared", "slave", "unbindable", "rshared", "rslave", "runbindable", "rprivate"} validatePropagation := func(input string) error { - if !shared.StringInSlice(d.config["bind"], propagationTypes) { + if !shared.ValueInSlice(d.config["bind"], propagationTypes) { return fmt.Errorf("Invalid propagation value. Must be one of: %s", strings.Join(propagationTypes, ", ")) } @@ -1876,14 +1876,14 @@ func (d *disk) getDiskLimits() (map[string]diskBlockLimit, error) { for _, block := range blocks { blockStr := "" - if shared.StringInSlice(block, validBlocks) { + if shared.ValueInSlice(block, validBlocks) { // Straightforward entry (full block device) blockStr = block } else { // Attempt to deal with a partition (guess its parent) fields := strings.SplitN(block, ":", 2) fields[1] = "0" - if shared.StringInSlice(fmt.Sprintf("%s:%s", fields[0], fields[1]), validBlocks) { + if shared.ValueInSlice(fmt.Sprintf("%s:%s", fields[0], fields[1]), validBlocks) { blockStr = fmt.Sprintf("%s:%s", fields[0], fields[1]) } } diff --git a/lxd/device/nic.go b/lxd/device/nic.go index b1d3f3233add..363fbdee0498 100644 --- a/lxd/device/nic.go +++ b/lxd/device/nic.go @@ -118,7 +118,7 @@ func nicCheckNamesUnique(instConf instance.ConfigReader) error { continue } - if shared.StringInSlice(devConfig["name"], seenNICNames) { + if shared.ValueInSlice(devConfig["name"], seenNICNames) { return fmt.Errorf("Duplicate NIC name detected %q", devConfig["name"]) } diff --git a/lxd/device/nic_bridged.go b/lxd/device/nic_bridged.go index dccc38d2f8c4..0cdd02e8a081 100644 --- a/lxd/device/nic_bridged.go +++ b/lxd/device/nic_bridged.go @@ -120,7 +120,7 @@ func (d *nicBridged) validateConfig(instConf instance.ConfigReader) error { } parentAddress := netConfig["ipv4.address"] - if shared.StringInSlice(parentAddress, []string{"", "none"}) { + if shared.ValueInSlice(parentAddress, []string{"", "none"}) { return nil } @@ -155,7 +155,7 @@ func (d *nicBridged) validateConfig(instConf instance.ConfigReader) error { } parentAddress := netConfig["ipv6.address"] - if shared.StringInSlice(parentAddress, []string{"", "none"}) { + if shared.ValueInSlice(parentAddress, []string{"", "none"}) { return nil } @@ -176,7 +176,7 @@ func (d *nicBridged) validateConfig(instConf instance.ConfigReader) error { // When we know the parent network is managed, we can validate the NIC's VLAN settings based on // on the bridge driver type. - if shared.StringInSlice(netConfig["bridge.driver"], []string{"", "native"}) { + if shared.ValueInSlice(netConfig["bridge.driver"], []string{"", "native"}) { // Check VLAN 0 isn't set when using a native Linux managed bridge, as not supported. if d.config["vlan"] == "0" { return fmt.Errorf("VLAN ID 0 is not allowed for native Linux bridges") @@ -1669,14 +1669,14 @@ func (d *nicBridged) State() (*api.InstanceStateNetwork, error) { // Add any valid-state neighbour IP entries first. for _, neighIP := range neighIPs { - if shared.StringInSlice(string(neighIP.State), validStates) { + if shared.ValueInSlice(string(neighIP.State), validStates) { ipStore(neighIP.Addr) } } // Add any non-failed-state entries. for _, neighIP := range neighIPs { - if neighIP.State != ip.NeighbourIPStateFailed && !shared.StringInSlice(string(neighIP.State), validStates) { + if neighIP.State != ip.NeighbourIPStateFailed && !shared.ValueInSlice(string(neighIP.State), validStates) { ipStore(neighIP.Addr) } } diff --git a/lxd/device/nic_ipvlan.go b/lxd/device/nic_ipvlan.go index eebb39cd24bf..3d440d96518f 100644 --- a/lxd/device/nic_ipvlan.go +++ b/lxd/device/nic_ipvlan.go @@ -115,7 +115,7 @@ func (d *nicIPVLAN) validateConfig(instConf instance.ConfigReader) error { } validModes := []string{ipvlanModeL3S, ipvlanModeL2} - if !shared.StringInSlice(value, validModes) { + if !shared.ValueInSlice(value, validModes) { return fmt.Errorf("Must be one of: %v", strings.Join(validModes, ", ")) } diff --git a/lxd/device/nic_ovn.go b/lxd/device/nic_ovn.go index 5218de05c335..811f04fdd2cf 100644 --- a/lxd/device/nic_ovn.go +++ b/lxd/device/nic_ovn.go @@ -728,7 +728,7 @@ func (d *nicOVN) Update(oldDevices deviceConfig.Devices, isRunning bool) error { newACLs := shared.SplitNTrimSpace(d.config["security.acls"], ",", -1, true) removedACLs := []string{} for _, oldACL := range oldACLs { - if !shared.StringInSlice(oldACL, newACLs) { + if !shared.ValueInSlice(oldACL, newACLs) { removedACLs = append(removedACLs, oldACL) } } diff --git a/lxd/device/proxy.go b/lxd/device/proxy.go index 22901887d89f..297e7de3168b 100644 --- a/lxd/device/proxy.go +++ b/lxd/device/proxy.go @@ -72,7 +72,7 @@ func (d *proxy) validateConfig(instConf instance.ConfigReader) error { // Supported bind types are: "host" or "instance" (or "guest" or "container", legacy options equivalent to "instance"). // If an empty value is supplied the default behavior is to assume "host" bind mode. validateBind := func(input string) error { - if !shared.StringInSlice(d.config["bind"], []string{"host", "instance", "guest", "container"}) { + if !shared.ValueInSlice(d.config["bind"], []string{"host", "instance", "guest", "container"}) { return fmt.Errorf("Invalid binding side given. Must be \"host\" or \"instance\"") } diff --git a/lxd/devices.go b/lxd/devices.go index a31228948019..1e9875f4a823 100644 --- a/lxd/devices.go +++ b/lxd/devices.go @@ -332,7 +332,7 @@ func fillFixedInstances(fixedInstances map[int64][]instance.Instance, inst insta // If the `targetCpuPool` has been manually specified (explicit CPU IDs/ranges specified with `limits.cpu`) if len(targetCpuPool) == targetCpuNum && !loadBalancing { for _, nr := range targetCpuPool { - if !shared.Int64InSlice(nr, effectiveCpus) { + if !shared.ValueInSlice(nr, effectiveCpus) { continue } @@ -450,7 +450,7 @@ func deviceTaskBalance(s *state.State) { isolatedCpusInt := resources.GetCPUIsolated() effectiveCpusSlice := []string{} for _, id := range effectiveCpusInt { - if shared.Int64InSlice(id, isolatedCpusInt) { + if shared.ValueInSlice(id, isolatedCpusInt) { continue } diff --git a/lxd/events.go b/lxd/events.go index 31ad88e95862..459199db7301 100644 --- a/lxd/events.go +++ b/lxd/events.go @@ -63,7 +63,7 @@ func eventsSocket(s *state.State, r *http.Request, w http.ResponseWriter) error if len(types) == 1 && types[0] == "" { types = []string{} for _, entry := range eventTypes { - if !s.Authorizer.UserIsAdmin(r) && shared.StringInSlice(entry, privilegedEventTypes) { + if !s.Authorizer.UserIsAdmin(r) && shared.ValueInSlice(entry, privilegedEventTypes) { continue } @@ -73,12 +73,12 @@ func eventsSocket(s *state.State, r *http.Request, w http.ResponseWriter) error // Validate event types. for _, entry := range types { - if !shared.StringInSlice(entry, eventTypes) { + if !shared.ValueInSlice(entry, eventTypes) { return api.StatusErrorf(http.StatusBadRequest, "%q isn't a supported event type", entry) } } - if shared.StringInSlice(api.EventTypeLogging, types) && !s.Authorizer.UserIsAdmin(r) { + if shared.ValueInSlice(api.EventTypeLogging, types) && !s.Authorizer.UserIsAdmin(r) { return api.StatusErrorf(http.StatusForbidden, "Forbidden") } diff --git a/lxd/events/devlxdEvents.go b/lxd/events/devlxdEvents.go index 746f5da8c3bc..9147d409d5de 100644 --- a/lxd/events/devlxdEvents.go +++ b/lxd/events/devlxdEvents.go @@ -79,7 +79,7 @@ func (s *DevLXDServer) broadcast(instanceID int, event api.Event) error { s.lock.Lock() listeners := s.listeners for _, listener := range listeners { - if !shared.StringInSlice(event.Type, listener.messageTypes) { + if !shared.ValueInSlice(event.Type, listener.messageTypes) { continue } diff --git a/lxd/events/events.go b/lxd/events/events.go index 3e0b38079a23..93603a465fe0 100644 --- a/lxd/events/events.go +++ b/lxd/events/events.go @@ -183,12 +183,12 @@ func (s *Server) broadcast(event api.Event, eventSource EventSource) error { continue } - if !shared.StringInSlice(event.Type, listener.messageTypes) { + if !shared.ValueInSlice(event.Type, listener.messageTypes) { continue } // If the event doesn't come from this member and has been excluded by listener, don't deliver it. - if eventSource != EventSourceLocal && shared.StringInSlice(event.Location, listener.excludeLocations) { + if eventSource != EventSourceLocal && shared.ValueInSlice(event.Location, listener.excludeLocations) { continue } diff --git a/lxd/firewall/drivers/drivers_nftables.go b/lxd/firewall/drivers/drivers_nftables.go index 0eec48a76703..705b7cea3eda 100644 --- a/lxd/firewall/drivers/drivers_nftables.go +++ b/lxd/firewall/drivers/drivers_nftables.go @@ -614,7 +614,7 @@ func (d Nftables) removeChains(families []string, chainSuffix string, chains ... foundChains := make(map[string]nftGenericItem) for _, family := range families { for _, item := range ruleset { - if item.ItemType == "chain" && item.Family == family && item.Table == nftablesNamespace && shared.StringInSlice(item.Name, fullChains) { + if item.ItemType == "chain" && item.Family == family && item.Table == nftablesNamespace && shared.ValueInSlice(item.Name, fullChains) { foundChains[item.Name] = item } } @@ -807,7 +807,7 @@ func (d Nftables) aclRuleCriteriaToRules(networkName string, ipVersion uint, rul } // Add protocol filters. - if shared.StringInSlice(rule.Protocol, []string{"tcp", "udp"}) { + if shared.ValueInSlice(rule.Protocol, []string{"tcp", "udp"}) { args = append(args, "meta", "l4proto", rule.Protocol) if rule.SourcePort != "" { @@ -817,7 +817,7 @@ func (d Nftables) aclRuleCriteriaToRules(networkName string, ipVersion uint, rul if rule.DestinationPort != "" { args = append(args, d.aclRulePortToACLMatch("dport", shared.SplitNTrimSpace(rule.DestinationPort, ",", -1, false)...)...) } - } else if shared.StringInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { + } else if shared.ValueInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { var icmpIPVersion uint var protoName string diff --git a/lxd/firewall/drivers/drivers_xtables.go b/lxd/firewall/drivers/drivers_xtables.go index f2f524d2b49a..3d7202d3c1d4 100644 --- a/lxd/firewall/drivers/drivers_xtables.go +++ b/lxd/firewall/drivers/drivers_xtables.go @@ -618,7 +618,7 @@ func (d Xtables) aclRuleCriteriaToArgs(networkName string, ipVersion uint, rule } // Add protocol filters. - if shared.StringInSlice(rule.Protocol, []string{"tcp", "udp"}) { + if shared.ValueInSlice(rule.Protocol, []string{"tcp", "udp"}) { args = append(args, "-p", rule.Protocol) if rule.SourcePort != "" { @@ -628,7 +628,7 @@ func (d Xtables) aclRuleCriteriaToArgs(networkName string, ipVersion uint, rule if rule.DestinationPort != "" { args = append(args, d.aclRulePortToACLMatch("dports", shared.SplitNTrimSpace(rule.DestinationPort, ",", -1, false)...)...) } - } else if shared.StringInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { + } else if shared.ValueInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { var icmpIPVersion uint var protoName string var extName string @@ -1287,7 +1287,7 @@ func (d Xtables) iptablesClear(ipVersion uint, comments []string, fromTables ... } for _, fromTable := range fromTables { - if tables != nil && !shared.StringInSlice(fromTable, tables) { + if tables != nil && !shared.ValueInSlice(fromTable, tables) { // If we successfully opened the tables file, and the requested table is not present, // then skip trying to get a list of rules from that table. continue diff --git a/lxd/images.go b/lxd/images.go index 17c1f24a52c1..c228e92d3165 100644 --- a/lxd/images.go +++ b/lxd/images.go @@ -172,7 +172,7 @@ func compressFile(compress string, infile io.Reader, outfile io.Writer) error { args = append(args, fields[1:]...) } - if shared.StringInSlice(fields[0], reproducible) { + if shared.ValueInSlice(fields[0], reproducible) { args = append(args, "-n") } @@ -1019,13 +1019,13 @@ func imagesPost(d *Daemon, r *http.Request) response.Response { return createTokenResponse(s, r, projectName, req.Source.Fingerprint, metadata) } - if !imageUpload && !shared.StringInSlice(req.Source.Type, []string{"container", "instance", "virtual-machine", "snapshot", "image", "url"}) { + if !imageUpload && !shared.ValueInSlice(req.Source.Type, []string{"container", "instance", "virtual-machine", "snapshot", "image", "url"}) { cleanup(builddir, post) return response.InternalError(fmt.Errorf("Invalid images JSON")) } /* Forward requests for containers on other nodes */ - if !imageUpload && shared.StringInSlice(req.Source.Type, []string{"container", "instance", "virtual-machine", "snapshot"}) { + if !imageUpload && shared.ValueInSlice(req.Source.Type, []string{"container", "instance", "virtual-machine", "snapshot"}) { name := req.Source.Name if name != "" { _, err = post.Seek(0, io.SeekStart) @@ -1757,7 +1757,7 @@ func distributeImage(ctx context.Context, s *state.State, nodes []string, oldFin // Add the volume to the list if the pool is backed by remote // storage as only then the volumes are shared. - if shared.StringInSlice(pool.Driver, db.StorageRemoteDriverNames()) { + if shared.ValueInSlice(pool.Driver, db.StorageRemoteDriverNames()) { imageVolumes = append(imageVolumes, vol) } } @@ -1845,7 +1845,7 @@ func distributeImage(ctx context.Context, s *state.State, nodes []string, oldFin if err != nil { logger.Error("Failed to get storage pool info", logger.Ctx{"err": err, "pool": fields[0]}) } else { - if shared.StringInSlice(pool.Driver, db.StorageRemoteDriverNames()) { + if shared.ValueInSlice(pool.Driver, db.StorageRemoteDriverNames()) { imageVolumes = append(imageVolumes, vol) } } @@ -2244,7 +2244,7 @@ func pruneLeftoverImages(s *state.State) { // Check and delete leftovers for _, entry := range entries { fp := strings.Split(entry.Name(), ".")[0] - if !shared.StringInSlice(fp, images) { + if !shared.ValueInSlice(fp, images) { err = os.RemoveAll(shared.VarPath("images", entry.Name())) if err != nil { return fmt.Errorf("Unable to remove leftover image: %v: %w", entry.Name(), err) diff --git a/lxd/init.go b/lxd/init.go index 33f29074b521..cfa0c1f215a1 100644 --- a/lxd/init.go +++ b/lxd/init.go @@ -114,7 +114,7 @@ func initDataNodeApply(d lxd.InstanceServer, config api.InitLocalPreseed) (func( for _, storagePool := range config.StoragePools { // New storagePool. - if !shared.StringInSlice(storagePool.Name, storagePoolNames) { + if !shared.ValueInSlice(storagePool.Name, storagePoolNames) { err := createStoragePool(storagePool) if err != nil { return nil, err @@ -255,7 +255,7 @@ func initDataNodeApply(d lxd.InstanceServer, config api.InitLocalPreseed) (func( for _, project := range config.Projects { // New project. - if !shared.StringInSlice(project.Name, projectNames) { + if !shared.ValueInSlice(project.Name, projectNames) { err := createProject(project) if err != nil { return nil, err @@ -359,7 +359,7 @@ func initDataNodeApply(d lxd.InstanceServer, config api.InitLocalPreseed) (func( for _, profile := range config.Profiles { // New profile. - if !shared.StringInSlice(profile.Name, profileNames) { + if !shared.ValueInSlice(profile.Name, profileNames) { err := createProfile(profile) if err != nil { return nil, err diff --git a/lxd/instance/drivers/driver_common.go b/lxd/instance/drivers/driver_common.go index 8d0dd749a458..8d1f96aafb66 100644 --- a/lxd/instance/drivers/driver_common.go +++ b/lxd/instance/drivers/driver_common.go @@ -810,7 +810,7 @@ func (d *common) getStartupSnapNameAndExpiry(inst instance.Instance) (string, *t } triggers := strings.Split(schedule, ", ") - if !shared.StringInSlice("@startup", triggers) { + if !shared.ValueInSlice("@startup", triggers) { return "", nil, nil } @@ -1204,7 +1204,7 @@ func (d *common) needsNewInstanceID(changedConfig []string, oldExpandedDevices d "user.user-data", "user.network-config", } { - if shared.StringInSlice(key, changedConfig) { + if shared.ValueInSlice(key, changedConfig) { return true } } @@ -1239,13 +1239,13 @@ func (d *common) needsNewInstanceID(changedConfig []string, oldExpandedDevices d newNames := getNICNames(d.expandedDevices) for _, entry := range oldNames { - if !shared.StringInSlice(entry, newNames) { + if !shared.ValueInSlice(entry, newNames) { return true } } for _, entry := range newNames { - if !shared.StringInSlice(entry, oldNames) { + if !shared.ValueInSlice(entry, oldNames) { return true } } @@ -1281,7 +1281,7 @@ func (d *common) deviceLoad(inst instance.Instance, deviceName string, rawConfig var err error // Create copy of config and load some fields from volatile if device is nic or infiniband. - if shared.StringInSlice(rawConfig["type"], []string{"nic", "infiniband"}) { + if shared.ValueInSlice(rawConfig["type"], []string{"nic", "infiniband"}) { configCopy, err = inst.FillNetworkDevice(deviceName, rawConfig) if err != nil { return nil, err diff --git a/lxd/instance/drivers/driver_lxc.go b/lxd/instance/drivers/driver_lxc.go index 1a7fa62e73c8..7cd8056d78aa 100644 --- a/lxd/instance/drivers/driver_lxc.go +++ b/lxd/instance/drivers/driver_lxc.go @@ -1646,7 +1646,7 @@ func (d *lxc) deviceDetachNIC(configCopy map[string]string, netIF []deviceConfig } // If interface doesn't exist inside container, cannot proceed. - if !shared.StringInSlice(configCopy["name"], ifaces) { + if !shared.ValueInSlice(configCopy["name"], ifaces) { return nil } @@ -2175,7 +2175,7 @@ func (d *lxc) startCommon() (string, []func() error, error) { // Pass any mounts into LXC. if len(runConf.Mounts) > 0 { for _, mount := range runConf.Mounts { - if shared.StringInSlice("propagation", mount.Opts) && !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 3, 0, 0) { + if shared.ValueInSlice("propagation", mount.Opts) && !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 3, 0, 0) { return "", nil, fmt.Errorf("Failed to setup device mount %q: %w", dev.Name(), fmt.Errorf("liblxc 3.0 is required for mount propagation configuration")) } @@ -2889,7 +2889,7 @@ func (d *lxc) onStopNS(args map[string]string) error { netns := args["netns"] // Validate target. - if !shared.StringInSlice(target, []string{"stop", "reboot"}) { + if !shared.ValueInSlice(target, []string{"stop", "reboot"}) { d.logger.Error("Container sent invalid target to OnStopNS", logger.Ctx{"target": target}) return fmt.Errorf("Invalid stop target %q", target) } @@ -2912,7 +2912,7 @@ func (d *lxc) onStop(args map[string]string) error { target := args["target"] // Validate target - if !shared.StringInSlice(target, []string{"stop", "reboot"}) { + if !shared.ValueInSlice(target, []string{"stop", "reboot"}) { d.logger.Error("Container sent invalid target to OnStop", logger.Ctx{"target": target}) return fmt.Errorf("Invalid stop target: %s", target) } @@ -4065,11 +4065,11 @@ func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { checkedProfiles := []string{} for _, profile := range args.Profiles { - if !shared.StringInSlice(profile.Name, profiles) { + if !shared.ValueInSlice(profile.Name, profiles) { return fmt.Errorf("Requested profile '%s' doesn't exist", profile.Name) } - if shared.StringInSlice(profile.Name, checkedProfiles) { + if shared.ValueInSlice(profile.Name, checkedProfiles) { return fmt.Errorf("Duplicate profile found in request") } @@ -4172,7 +4172,7 @@ func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { changedConfig := []string{} for key := range oldExpandedConfig { if oldExpandedConfig[key] != d.expandedConfig[key] { - if !shared.StringInSlice(key, changedConfig) { + if !shared.ValueInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } @@ -4180,7 +4180,7 @@ func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { for key := range d.expandedConfig { if oldExpandedConfig[key] != d.expandedConfig[key] { - if !shared.StringInSlice(key, changedConfig) { + if !shared.ValueInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } @@ -4242,7 +4242,7 @@ func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { } for _, k := range changedConfig { - if !shared.StringInSlice(k, protectedKeys) { + if !shared.ValueInSlice(k, protectedKeys) { continue } @@ -4288,7 +4288,7 @@ func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { } // If raw.lxc changed, re-validate the config. - if shared.StringInSlice("raw.lxc", changedConfig) && d.expandedConfig["raw.lxc"] != "" { + if shared.ValueInSlice("raw.lxc", changedConfig) && d.expandedConfig["raw.lxc"] != "" { // Get a new liblxc instance. cc, err := liblxc.NewContainer(d.name, d.state.OS.LxcPath) if err != nil { @@ -4307,14 +4307,14 @@ func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { } // If apparmor changed, re-validate the apparmor profile (even if not running). - if shared.StringInSlice("raw.apparmor", changedConfig) || shared.StringInSlice("security.nesting", changedConfig) { + if shared.ValueInSlice("raw.apparmor", changedConfig) || shared.ValueInSlice("security.nesting", changedConfig) { err = apparmor.InstanceValidate(d.state.OS, d) if err != nil { return fmt.Errorf("Parse AppArmor profile: %w", err) } } - if shared.StringInSlice("security.idmap.isolated", changedConfig) || shared.StringInSlice("security.idmap.base", changedConfig) || shared.StringInSlice("security.idmap.size", changedConfig) || shared.StringInSlice("raw.idmap", changedConfig) || shared.StringInSlice("security.privileged", changedConfig) { + if shared.ValueInSlice("security.idmap.isolated", changedConfig) || shared.ValueInSlice("security.idmap.base", changedConfig) || shared.ValueInSlice("security.idmap.size", changedConfig) || shared.ValueInSlice("raw.idmap", changedConfig) || shared.ValueInSlice("security.privileged", changedConfig) { var idmap *idmap.IdmapSet base := int64(0) if !d.IsPrivileged() { @@ -4362,7 +4362,7 @@ func (d *lxc) Update(args db.InstanceArgs, userRequested bool) error { // Update MAAS (must run after the MAC addresses have been generated). updateMAAS := false for _, key := range []string{"maas.subnet.ipv4", "maas.subnet.ipv6", "ipv4.address", "ipv6.address"} { - if shared.StringInSlice(key, allUpdatedKeys) { + if shared.ValueInSlice(key, allUpdatedKeys) { updateMAAS = true break } @@ -5299,7 +5299,7 @@ func (d *lxc) MigrateSend(args instance.MigrateSendArgs) error { // Ensure that only the requested snapshots are included in the migration index header. volSourceArgs.Info.Config.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(volSourceArgs.Snapshots)) for i := range allSnapshots { - if shared.StringInSlice(allSnapshots[i].Name, volSourceArgs.Snapshots) { + if shared.ValueInSlice(allSnapshots[i].Name, volSourceArgs.Snapshots) { volSourceArgs.Info.Config.VolumeSnapshots = append(volSourceArgs.Info.Config.VolumeSnapshots, allSnapshots[i]) } } @@ -5382,7 +5382,7 @@ func (d *lxc) MigrateSend(args instance.MigrateSendArgs) error { // Setup rsync options (used for CRIU state transfers). rsyncBwlimit := pool.Driver().Config()["rsync.bwlimit"] rsyncFeatures := respHeader.GetRsyncFeaturesSlice() - if !shared.StringInSlice("bidirectional", rsyncFeatures) { + if !shared.ValueInSlice("bidirectional", rsyncFeatures) { // If no bi-directional support, assume LXD 3.7 level. // NOTE: Do NOT extend this list of arguments. rsyncFeatures = []string{"xattrs", "delete", "compress"} @@ -7796,7 +7796,7 @@ func (d *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfi // Include all static interface names for _, dev := range d.expandedDevices.Sorted() { - if dev.Config["name"] != "" && !shared.StringInSlice(dev.Config["name"], devNames) { + if dev.Config["name"] != "" && !shared.ValueInSlice(dev.Config["name"], devNames) { devNames = append(devNames, dev.Config["name"]) } } @@ -7812,7 +7812,7 @@ func (d *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfi continue } - if fields[2] != "name" || shared.StringInSlice(v, devNames) { + if fields[2] != "name" || shared.ValueInSlice(v, devNames) { continue } @@ -7828,7 +7828,7 @@ func (d *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfi interfaces, err := cc.Interfaces() if err == nil { for _, name := range interfaces { - if shared.StringInSlice(name, devNames) { + if shared.ValueInSlice(name, devNames) { continue } @@ -7847,7 +7847,7 @@ func (d *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfi } // Find a free device name - if !shared.StringInSlice(name, devNames) { + if !shared.ValueInSlice(name, devNames) { return name, nil } @@ -7861,7 +7861,7 @@ func (d *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfi } // Fill in the MAC address. - if !shared.StringInSlice(nicType, []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" { + if !shared.ValueInSlice(nicType, []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" { configKey := fmt.Sprintf("volatile.%s.hwaddr", name) volatileHwaddr := d.localConfig[configKey] if volatileHwaddr == "" { diff --git a/lxd/instance/drivers/driver_qemu.go b/lxd/instance/drivers/driver_qemu.go index 9a784f5423dc..44e07c5f51a0 100644 --- a/lxd/instance/drivers/driver_qemu.go +++ b/lxd/instance/drivers/driver_qemu.go @@ -398,7 +398,7 @@ func (d *qemu) getMonitorEventHandler() func(event string, data map[string]any) state := d.state return func(event string, data map[string]any) { - if !shared.StringInSlice(event, []string{qmp.EventVMShutdown, qmp.EventAgentStarted}) { + if !shared.ValueInSlice(event, []string{qmp.EventVMShutdown, qmp.EventAgentStarted}) { return // Don't bother loading the instance from DB if we aren't going to handle the event. } @@ -1913,7 +1913,7 @@ func (d *qemu) AgentCertificate() *x509.Certificate { } func (d *qemu) architectureSupportsUEFI(arch int) bool { - return shared.IntInSlice(arch, []int{osarch.ARCH_64BIT_INTEL_X86, osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN}) + return shared.ValueInSlice(arch, []int{osarch.ARCH_64BIT_INTEL_X86, osarch.ARCH_64BIT_ARMV8_LITTLE_ENDIAN}) } func (d *qemu) setupNvram() error { @@ -2203,7 +2203,7 @@ func (d *qemu) deviceAttachNIC(deviceName string, configCopy map[string]string, qemuDev := make(map[string]string) // PCIe and PCI require a port device name to hotplug the NIC into. - if shared.StringInSlice(qemuBus, []string{"pcie", "pci"}) { + if shared.ValueInSlice(qemuBus, []string{"pcie", "pci"}) { pciDevID := qemuPCIDeviceIDStart // Iterate through all the instance devices in the same sorted order as is used when allocating the @@ -2336,7 +2336,7 @@ func (d *qemu) deviceDetachNIC(deviceName string) error { return err } - if shared.StringInSlice(qemuBus, []string{"pcie", "pci"}) { + if shared.ValueInSlice(qemuBus, []string{"pcie", "pci"}) { // Wait until the device is actually removed (or we timeout waiting). waitDuration := time.Duration(time.Second * time.Duration(10)) waitUntil := time.Now().Add(waitDuration) @@ -2849,7 +2849,7 @@ func (d *qemu) generateQemuConfigFile(cpuInfo *cpuTopology, mountInfo *storagePo } // Allow disabling the UEFI firmware. - if shared.StringInSlice("-bios", rawOptions) || shared.StringInSlice("-kernel", rawOptions) { + if shared.ValueInSlice("-bios", rawOptions) || shared.ValueInSlice("-kernel", rawOptions) { d.logger.Warn("Starting VM without default firmware (-bios or -kernel in raw.qemu)") } else if d.architectureSupportsUEFI(d.architecture) { // Open the UEFI NVRAM file and pass it via file descriptor to QEMU. @@ -3088,7 +3088,7 @@ func (d *qemu) generateQemuConfigFile(cpuInfo *cpuTopology, mountInfo *storagePo // Dynamic devices. base := 0 - if shared.StringInSlice("-kernel", rawOptions) { + if shared.ValueInSlice("-kernel", rawOptions) { base = 1 } @@ -3131,7 +3131,7 @@ func (d *qemu) generateQemuConfigFile(cpuInfo *cpuTopology, mountInfo *storagePo // Add network device. if len(runConf.NetworkInterface) > 0 { qemuDev := make(map[string]string) - if shared.StringInSlice(bus.name, []string{"pcie", "pci"}) { + if shared.ValueInSlice(bus.name, []string{"pcie", "pci"}) { // Allocate a PCI(e) port and write it to the config file so QMP can "hotplug" the // NIC into it later. devBus, devAddr, multi := bus.allocate(busFunctionGroupNone) @@ -3401,7 +3401,7 @@ func (d *qemu) addDriveDirConfig(cfg *[]cfgSection, bus *qemuBus, fdFiles *[]*os agentMount.Options = append(agentMount.Options, "trans=virtio,msize=33554432") } - readonly := shared.StringInSlice("ro", driveConf.Opts) + readonly := shared.ValueInSlice("ro", driveConf.Opts) // Indicate to agent to mount this readonly. Note: This is purely to indicate to VM guest that this is // readonly, it should *not* be used as a security measure, as the VM guest could remount it R/W. @@ -3486,7 +3486,7 @@ func (d *qemu) addDriveConfig(bootIndexes map[string]int, driveConf deviceConfig info := DriverStatuses()[instancetype.VM].Info minVer, _ := version.NewDottedVersion("5.13.0") _, ioUring := info.Features["io_uring"] - if shared.StringInSlice(device.DiskIOUring, driveConf.Opts) && ioUring && d.state.OS.KernelVersion.Compare(minVer) >= 0 { + if shared.ValueInSlice(device.DiskIOUring, driveConf.Opts) && ioUring && d.state.OS.KernelVersion.Compare(minVer) >= 0 { aioMode = "io_uring" } @@ -3558,7 +3558,7 @@ func (d *qemu) addDriveConfig(bootIndexes map[string]int, driveConf deviceConfig // Only warn about using writeback cache if the drive image is writable. d.logger.Warn("Using writeback cache I/O", logger.Ctx{"device": driveConf.DevName, "devPath": srcDevPath, "fsType": fsType}) } - } else if !shared.StringInSlice(device.DiskDirectIO, driveConf.Opts) { + } else if !shared.ValueInSlice(device.DiskDirectIO, driveConf.Opts) { // If drive config indicates we need to use unsafe I/O then use it. d.logger.Warn("Using unsafe cache I/O", logger.Ctx{"device": driveConf.DevName, "devPath": srcDevPath}) aioMode = "threads" @@ -3690,7 +3690,7 @@ func (d *qemu) addDriveConfig(bootIndexes map[string]int, driveConf deviceConfig } } - readonly := shared.StringInSlice("ro", driveConf.Opts) + readonly := shared.ValueInSlice("ro", driveConf.Opts) if readonly { blockDev["read-only"] = true @@ -3835,7 +3835,7 @@ func (d *qemu) addNetDevConfig(busName string, qemuDev map[string]string, bootIn vectors := 2*queueCount + 2 if vectors > 0 { qemuDev["mq"] = "on" - if shared.StringInSlice(busName, []string{"pcie", "pci"}) { + if shared.ValueInSlice(busName, []string{"pcie", "pci"}) { qemuDev["vectors"] = strconv.Itoa(vectors) } } @@ -3909,7 +3909,7 @@ func (d *qemu) addNetDevConfig(busName string, qemuDev map[string]string, bootIn "vhost": vhostNetEnabled, } - if shared.StringInSlice(busName, []string{"pcie", "pci"}) { + if shared.ValueInSlice(busName, []string{"pcie", "pci"}) { qemuDev["driver"] = "virtio-net-pci" } else if busName == "ccw" { qemuDev["driver"] = "virtio-net-ccw" @@ -4018,7 +4018,7 @@ func (d *qemu) addNetDevConfig(busName string, qemuDev map[string]string, bootIn "queues": queues, } - if shared.StringInSlice(busName, []string{"pcie", "pci"}) { + if shared.ValueInSlice(busName, []string{"pcie", "pci"}) { qemuDev["driver"] = "virtio-net-pci" } else if busName == "ccw" { qemuDev["driver"] = "virtio-net-ccw" @@ -4039,7 +4039,7 @@ func (d *qemu) addNetDevConfig(busName string, qemuDev map[string]string, bootIn } } else if pciSlotName != "" { // Detect physical passthrough device. - if shared.StringInSlice(busName, []string{"pcie", "pci"}) { + if shared.ValueInSlice(busName, []string{"pcie", "pci"}) { qemuDev["driver"] = "vfio-pci" } else if busName == "ccw" { qemuDev["driver"] = "vfio-ccw" @@ -4941,11 +4941,11 @@ func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error { checkedProfiles := []string{} for _, profile := range args.Profiles { - if !shared.StringInSlice(profile.Name, profiles) { + if !shared.ValueInSlice(profile.Name, profiles) { return fmt.Errorf("Requested profile '%s' doesn't exist", profile.Name) } - if shared.StringInSlice(profile.Name, checkedProfiles) { + if shared.ValueInSlice(profile.Name, checkedProfiles) { return fmt.Errorf("Duplicate profile found in request") } @@ -5038,7 +5038,7 @@ func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error { changedConfig := []string{} for key := range oldExpandedConfig { if oldExpandedConfig[key] != d.expandedConfig[key] { - if !shared.StringInSlice(key, changedConfig) { + if !shared.ValueInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } @@ -5046,7 +5046,7 @@ func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error { for key := range d.expandedConfig { if oldExpandedConfig[key] != d.expandedConfig[key] { - if !shared.StringInSlice(key, changedConfig) { + if !shared.ValueInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } @@ -5125,7 +5125,7 @@ func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error { } // If apparmor changed, re-validate the apparmor profile (even if not running). - if shared.StringInSlice("raw.apparmor", changedConfig) { + if shared.ValueInSlice("raw.apparmor", changedConfig) { err = apparmor.InstanceValidate(d.state.OS, d) if err != nil { return fmt.Errorf("Parse AppArmor profile: %w", err) @@ -5172,7 +5172,7 @@ func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error { return d.architectureSupportsCPUHotplug() } - if shared.StringInSlice(key, liveUpdateKeys) { + if shared.ValueInSlice(key, liveUpdateKeys) { return true } @@ -5243,7 +5243,7 @@ func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error { // Update MAAS (must run after the MAC addresses have been generated). updateMAAS := false for _, key := range []string{"maas.subnet.ipv4", "maas.subnet.ipv6", "ipv4.address", "ipv6.address"} { - if shared.StringInSlice(key, allUpdatedKeys) { + if shared.ValueInSlice(key, allUpdatedKeys) { updateMAAS = true break } @@ -5256,7 +5256,7 @@ func (d *qemu) Update(args db.InstanceArgs, userRequested bool) error { } } - if d.architectureSupportsUEFI(d.architecture) && (shared.StringInSlice("security.secureboot", changedConfig) || shared.StringInSlice("security.csm", changedConfig)) { + if d.architectureSupportsUEFI(d.architecture) && (shared.ValueInSlice("security.secureboot", changedConfig) || shared.ValueInSlice("security.csm", changedConfig)) { // Re-generate the NVRAM. err = d.setupNvram() if err != nil { @@ -6098,7 +6098,7 @@ func (d *qemu) MigrateSend(args instance.MigrateSendArgs) error { // Ensure that only the requested snapshots are included in the migration index header. volSourceArgs.Info.Config.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(volSourceArgs.Snapshots)) for i := range allSnapshots { - if shared.StringInSlice(allSnapshots[i].Name, volSourceArgs.Snapshots) { + if shared.ValueInSlice(allSnapshots[i].Name, volSourceArgs.Snapshots) { volSourceArgs.Info.Config.VolumeSnapshots = append(volSourceArgs.Info.Config.VolumeSnapshots, allSnapshots[i]) } } @@ -7678,7 +7678,7 @@ func (d *qemu) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConf } // Fill in the MAC address. - if !shared.StringInSlice(nicType, []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" { + if !shared.ValueInSlice(nicType, []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" { configKey := fmt.Sprintf("volatile.%s.hwaddr", name) volatileHwaddr := d.localConfig[configKey] if volatileHwaddr == "" { @@ -7781,7 +7781,7 @@ func (d *qemu) cpuTopology(limit string) (*cpuTopology, error) { sockets[cpu.Socket] = []uint64{} } - if !shared.Uint64InSlice(core.Core, sockets[cpu.Socket]) { + if !shared.ValueInSlice(core.Core, sockets[cpu.Socket]) { sockets[cpu.Socket] = append(sockets[cpu.Socket], core.Core) } @@ -7791,7 +7791,7 @@ func (d *qemu) cpuTopology(limit string) (*cpuTopology, error) { cores[core.Core] = []uint64{} } - if !shared.Uint64InSlice(thread.Thread, cores[core.Core]) { + if !shared.ValueInSlice(thread.Thread, cores[core.Core]) { cores[core.Core] = append(cores[core.Core], thread.Thread) } @@ -8100,7 +8100,7 @@ func (d *qemu) checkFeatures(hostArch int, qemuPath string) (map[string]any, err parts := strings.Split(string(cmdline), " ") // Check if SME is enabled in the kernel command line. - if shared.StringInSlice("mem_encrypt=on", parts) { + if shared.ValueInSlice("mem_encrypt=on", parts) { features["sme"] = struct{}{} } diff --git a/lxd/instance/drivers/load.go b/lxd/instance/drivers/load.go index cf77591ae2c1..6bc51b658b93 100644 --- a/lxd/instance/drivers/load.go +++ b/lxd/instance/drivers/load.go @@ -86,7 +86,7 @@ func validDevices(state *state.State, p api.Project, instanceType instancetype.T checkDevices := func(devices deviceConfig.Devices, expanded bool) error { // Check each device individually using the device package. for deviceName, deviceConfig := range devices { - if expanded && shared.StringInSlice(deviceName, checkedDevices) { + if expanded && shared.ValueInSlice(deviceName, checkedDevices) { continue // Don't check the device twice if present in both local and expanded. } diff --git a/lxd/instance/instance_utils.go b/lxd/instance/instance_utils.go index 343ca72dcd0a..f7db021a40f6 100644 --- a/lxd/instance/instance_utils.go +++ b/lxd/instance/instance_utils.go @@ -252,22 +252,22 @@ func lxcValidConfig(rawLxc string) error { if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 2, 1, 0) { // lxc.network.X.ipv4 or lxc.network.X.ipv6 - if len(fields) == 4 && shared.StringInSlice(fields[3], []string{"ipv4", "ipv6"}) { + if len(fields) == 4 && shared.ValueInSlice(fields[3], []string{"ipv4", "ipv6"}) { continue } // lxc.network.X.ipv4.gateway or lxc.network.X.ipv6.gateway - if len(fields) == 5 && shared.StringInSlice(fields[3], []string{"ipv4", "ipv6"}) && fields[4] == "gateway" { + if len(fields) == 5 && shared.ValueInSlice(fields[3], []string{"ipv4", "ipv6"}) && fields[4] == "gateway" { continue } } else { // lxc.net.X.ipv4.address or lxc.net.X.ipv6.address - if len(fields) == 5 && shared.StringInSlice(fields[3], []string{"ipv4", "ipv6"}) && fields[4] == "address" { + if len(fields) == 5 && shared.ValueInSlice(fields[3], []string{"ipv4", "ipv6"}) && fields[4] == "address" { continue } // lxc.net.X.ipv4.gateway or lxc.net.X.ipv6.gateway - if len(fields) == 5 && shared.StringInSlice(fields[3], []string{"ipv4", "ipv6"}) && fields[4] == "gateway" { + if len(fields) == 5 && shared.ValueInSlice(fields[3], []string{"ipv4", "ipv6"}) && fields[4] == "gateway" { continue } } @@ -566,7 +566,7 @@ func ResolveImage(ctx context.Context, tx *db.ClusterTx, projectName string, sou // A nil list indicates that we can't tell at this stage, typically for private images. func SuitableArchitectures(ctx context.Context, s *state.State, tx *db.ClusterTx, projectName string, sourceInst *cluster.Instance, sourceImageRef string, req api.InstancesPost) ([]int, error) { // Handle cases where the architecture is already provided. - if shared.StringInSlice(req.Source.Type, []string{"migration", "none"}) && req.Architecture != "" { + if shared.ValueInSlice(req.Source.Type, []string{"migration", "none"}) && req.Architecture != "" { id, err := osarch.ArchitectureId(req.Architecture) if err != nil { return nil, err @@ -616,7 +616,7 @@ func SuitableArchitectures(ctx context.Context, s *state.State, tx *db.ClusterTx var err error var remote lxd.ImageServer - if shared.StringInSlice(req.Source.Protocol, []string{"", "lxd"}) { + if shared.ValueInSlice(req.Source.Protocol, []string{"", "lxd"}) { // Remote LXD image server. remote, err = lxd.ConnectPublicLXD(req.Source.Server, &lxd.ConnectionArgs{ TLSServerCert: req.Source.Certificate, @@ -791,7 +791,7 @@ func CreateInternal(s *state.State, args db.InstanceArgs, clearLogDir bool) (Ins return nil, nil, nil, err } - if !shared.IntInSlice(args.Architecture, s.OS.Architectures) { + if !shared.ValueInSlice(args.Architecture, s.OS.Architectures) { return nil, nil, nil, fmt.Errorf("Requested architecture isn't supported by this host") } @@ -803,7 +803,7 @@ func CreateInternal(s *state.State, args db.InstanceArgs, clearLogDir bool) (Ins checkedProfiles := map[string]bool{} for _, profile := range args.Profiles { - if !shared.StringInSlice(profile.Name, profiles) { + if !shared.ValueInSlice(profile.Name, profiles) { return nil, nil, nil, fmt.Errorf("Requested profile %q doesn't exist", profile.Name) } diff --git a/lxd/instance_console.go b/lxd/instance_console.go index 133cb172f01a..a735db5860db 100644 --- a/lxd/instance_console.go +++ b/lxd/instance_console.go @@ -469,7 +469,7 @@ func instanceConsolePost(d *Daemon, r *http.Request) response.Response { } // Basic parameter validation. - if !shared.StringInSlice(post.Type, []string{instance.ConsoleTypeConsole, instance.ConsoleTypeVGA}) { + if !shared.ValueInSlice(post.Type, []string{instance.ConsoleTypeConsole, instance.ConsoleTypeVGA}) { return response.BadRequest(fmt.Errorf("Unknown console type %q", post.Type)) } diff --git a/lxd/instance_file.go b/lxd/instance_file.go index efb06f28e18b..583cece80319 100644 --- a/lxd/instance_file.go +++ b/lxd/instance_file.go @@ -440,7 +440,7 @@ func instanceFilePost(s *state.State, inst instance.Instance, path string, r *ht // Extract file ownership and mode from headers uid, gid, mode, type_, write := shared.ParseLXDFileHeaders(r.Header) - if !shared.StringInSlice(write, []string{"overwrite", "append"}) { + if !shared.ValueInSlice(write, []string{"overwrite", "append"}) { return response.BadRequest(fmt.Errorf("Bad file write mode: %s", write)) } diff --git a/lxd/instances_post.go b/lxd/instances_post.go index 9956e7346f03..be2c316caa4d 100644 --- a/lxd/instances_post.go +++ b/lxd/instances_post.go @@ -1011,7 +1011,7 @@ func instancesPost(d *Daemon, r *http.Request) response.Response { for { i++ req.Name = strings.ToLower(petname.Generate(2, "-")) - if !shared.StringInSlice(req.Name, names) { + if !shared.ValueInSlice(req.Name, names) { break } diff --git a/lxd/logging.go b/lxd/logging.go index 88aef3dcb438..b3f9312b5ec8 100644 --- a/lxd/logging.go +++ b/lxd/logging.go @@ -112,7 +112,7 @@ func expireLogs(ctx context.Context, state *state.State) error { } // Check if the instance still exists. - if shared.StringInSlice(fi.Name(), names) { + if shared.ValueInSlice(fi.Name(), names) { instDirEntries, err := os.ReadDir(shared.LogPath(fi.Name())) if err != nil { return err diff --git a/lxd/loki/loki.go b/lxd/loki/loki.go index 25585a3bc1f5..0feb094faaf7 100644 --- a/lxd/loki/loki.go +++ b/lxd/loki/loki.go @@ -229,7 +229,7 @@ func (c *Client) Stop() { // HandleEvent handles the event received from the internal event listener. func (c *Client) HandleEvent(event api.Event) { - if !shared.StringInSlice(event.Type, c.cfg.types) { + if !shared.ValueInSlice(event.Type, c.cfg.types) { return } @@ -285,7 +285,7 @@ func (c *Client) HandleEvent(event api.Event) { // Add key-value pairs as labels but don't override any labels. for k, v := range context { - if shared.StringInSlice(k, c.cfg.labels) { + if shared.ValueInSlice(k, c.cfg.labels) { _, ok := entry.labels[k] if !ok { // Label names may not contain any hyphens. @@ -337,7 +337,7 @@ func (c *Client) HandleEvent(event api.Event) { // Add key-value pairs as labels but don't override any labels. for k, v := range context { - if shared.StringInSlice(k, c.cfg.labels) { + if shared.ValueInSlice(k, c.cfg.labels) { _, ok := entry.labels[k] if !ok { entry.labels[k] = v diff --git a/lxd/lxd-metadata/lxd_metadata.go b/lxd/lxd-metadata/lxd_metadata.go index 5c93863ce91b..9bd42da46110 100644 --- a/lxd/lxd-metadata/lxd_metadata.go +++ b/lxd/lxd-metadata/lxd_metadata.go @@ -117,7 +117,7 @@ func parse(path string, outputJSONPath string, excludedPaths []string) (*doc, er } // Skip excluded paths - if shared.StringInSlice(path, excludedPaths) { + if shared.ValueInSlice(path, excludedPaths) { if info.IsDir() { log.Printf("Skipping excluded directory: %v", path) return filepath.SkipDir @@ -176,7 +176,7 @@ func parse(path string, outputJSONPath string, excludedPaths []string) (*doc, er mdKey := mdKVMatch[1] mdValue := mdKVMatch[2] // check that the metadata key is among the expected ones - if !shared.StringInSlice(mdKey, mdKeys) { + if !shared.ValueInSlice(mdKey, mdKeys) { continue } @@ -355,7 +355,7 @@ func writeDocFile(inputJSONPath, outputTxtPath string) error { configContentValueStr, ok := configContentValue.(string) if ok { - if (strings.HasSuffix(configContentValueStr, "`") && strings.HasPrefix(configContentValueStr, "`")) || shared.StringInSlice(configContentValueStr, specialChars) { + if (strings.HasSuffix(configContentValueStr, "`") && strings.HasPrefix(configContentValueStr, "`")) || shared.ValueInSlice(configContentValueStr, specialChars) { configContentValueStr = fmt.Sprintf("\"%s\"", configContentValueStr) } } else { diff --git a/lxd/main_cluster.go b/lxd/main_cluster.go index 8776b335da32..a674443b080f 100644 --- a/lxd/main_cluster.go +++ b/lxd/main_cluster.go @@ -432,7 +432,7 @@ Do you want to proceed? (yes/no): `) input, _ := reader.ReadString('\n') input = strings.TrimSuffix(input, "\n") - if !shared.StringInSlice(strings.ToLower(input), []string{"yes"}) { + if !shared.ValueInSlice(strings.ToLower(input), []string{"yes"}) { return fmt.Errorf("Recover operation aborted") } @@ -496,7 +496,7 @@ Do you want to proceed? (yes/no): `) input, _ := reader.ReadString('\n') input = strings.TrimSuffix(input, "\n") - if !shared.StringInSlice(strings.ToLower(input), []string{"yes"}) { + if !shared.ValueInSlice(strings.ToLower(input), []string{"yes"}) { return fmt.Errorf("Remove raft node operation aborted") } diff --git a/lxd/main_init_auto.go b/lxd/main_init_auto.go index b2bfa62a03e8..9862e71491c2 100644 --- a/lxd/main_init_auto.go +++ b/lxd/main_init_auto.go @@ -15,11 +15,11 @@ import ( func (c *cmdInit) RunAuto(cmd *cobra.Command, args []string, d lxd.InstanceServer, server *api.Server) (*api.InitPreseed, error) { // Quick checks. - if c.flagStorageBackend != "" && !shared.StringInSlice(c.flagStorageBackend, storageDrivers.AllDriverNames()) { + if c.flagStorageBackend != "" && !shared.ValueInSlice(c.flagStorageBackend, storageDrivers.AllDriverNames()) { return nil, fmt.Errorf("The requested backend '%s' isn't supported by lxd init", c.flagStorageBackend) } - if c.flagStorageBackend != "" && !shared.StringInSlice(c.flagStorageBackend, util.AvailableStorageDrivers(server.Environment.StorageSupportedDrivers, util.PoolTypeAny)) { + if c.flagStorageBackend != "" && !shared.ValueInSlice(c.flagStorageBackend, util.AvailableStorageDrivers(server.Environment.StorageSupportedDrivers, util.PoolTypeAny)) { return nil, fmt.Errorf("The requested backend '%s' isn't available on your system (missing tools)", c.flagStorageBackend) } diff --git a/lxd/main_init_interactive.go b/lxd/main_init_interactive.go index 50957e42ef25..84d5d2e84026 100644 --- a/lxd/main_init_interactive.go +++ b/lxd/main_init_interactive.go @@ -131,7 +131,7 @@ func (c *cmdInit) askClustering(config *api.InitPreseed, d lxd.InstanceServer, s address := util.CanonicalNetworkAddress(value, shared.HTTPSDefaultPort) host, _, _ := net.SplitHostPort(address) - if shared.StringInSlice(host, []string{"", "[::]", "0.0.0.0"}) { + if shared.ValueInSlice(host, []string{"", "[::]", "0.0.0.0"}) { return fmt.Errorf("Invalid IP address or DNS name") } @@ -186,9 +186,9 @@ func (c *cmdInit) askClustering(config *api.InitPreseed, d lxd.InstanceServer, s } validInput := func(input string) error { - if shared.StringInSlice(strings.ToLower(input), []string{"yes", "y"}) { + if shared.ValueInSlice(strings.ToLower(input), []string{"yes", "y"}) { return nil - } else if shared.StringInSlice(strings.ToLower(input), []string{"no", "n"}) { + } else if shared.ValueInSlice(strings.ToLower(input), []string{"no", "n"}) { return nil } else if validJoinToken(input) != nil { return fmt.Errorf("Not yes/no, or invalid join token") @@ -202,8 +202,8 @@ func (c *cmdInit) askClustering(config *api.InitPreseed, d lxd.InstanceServer, s return err } - if !shared.StringInSlice(strings.ToLower(clusterJoinToken), []string{"no", "n"}) { - if shared.StringInSlice(strings.ToLower(clusterJoinToken), []string{"yes", "y"}) { + if !shared.ValueInSlice(strings.ToLower(clusterJoinToken), []string{"no", "n"}) { + if shared.ValueInSlice(strings.ToLower(clusterJoinToken), []string{"yes", "y"}) { clusterJoinToken, err = c.global.asker.AskString("Please provide join token: ", "", validJoinToken) if err != nil { return err @@ -271,9 +271,9 @@ func (c *cmdInit) askClustering(config *api.InitPreseed, d lxd.InstanceServer, s validator := func(input string) error { if input == certDigest { return nil - } else if shared.StringInSlice(strings.ToLower(input), []string{"yes", "y"}) { + } else if shared.ValueInSlice(strings.ToLower(input), []string{"yes", "y"}) { return nil - } else if shared.StringInSlice(strings.ToLower(input), []string{"no", "n"}) { + } else if shared.ValueInSlice(strings.ToLower(input), []string{"no", "n"}) { return nil } @@ -285,7 +285,7 @@ func (c *cmdInit) askClustering(config *api.InitPreseed, d lxd.InstanceServer, s return err } - if shared.StringInSlice(strings.ToLower(fingerprintCorrect), []string{"no", "n"}) { + if shared.ValueInSlice(strings.ToLower(fingerprintCorrect), []string{"no", "n"}) { return fmt.Errorf("User aborted configuration") } @@ -574,7 +574,7 @@ func (c *cmdInit) askNetworking(config *api.InitPreseed, d lxd.InstanceServer) e // IPv4 net.Config["ipv4.address"], err = c.global.asker.AskString("What IPv4 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: ", "auto", func(value string) error { - if shared.StringInSlice(value, []string{"auto", "none"}) { + if shared.ValueInSlice(value, []string{"auto", "none"}) { return nil } @@ -584,7 +584,7 @@ func (c *cmdInit) askNetworking(config *api.InitPreseed, d lxd.InstanceServer) e return err } - if !shared.StringInSlice(net.Config["ipv4.address"], []string{"auto", "none"}) { + if !shared.ValueInSlice(net.Config["ipv4.address"], []string{"auto", "none"}) { netIPv4UseNAT, err := c.global.asker.AskBool("Would you like LXD to NAT IPv4 traffic on your bridge? [default=yes]: ", "yes") if err != nil { return err @@ -595,7 +595,7 @@ func (c *cmdInit) askNetworking(config *api.InitPreseed, d lxd.InstanceServer) e // IPv6 net.Config["ipv6.address"], err = c.global.asker.AskString("What IPv6 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: ", "auto", func(value string) error { - if shared.StringInSlice(value, []string{"auto", "none"}) { + if shared.ValueInSlice(value, []string{"auto", "none"}) { return nil } @@ -605,7 +605,7 @@ func (c *cmdInit) askNetworking(config *api.InitPreseed, d lxd.InstanceServer) e return err } - if !shared.StringInSlice(net.Config["ipv6.address"], []string{"auto", "none"}) { + if !shared.ValueInSlice(net.Config["ipv6.address"], []string{"auto", "none"}) { netIPv6UseNAT, err := c.global.asker.AskBool("Would you like LXD to NAT IPv6 traffic on your bridge? [default=yes]: ", "yes") if err != nil { return err @@ -681,11 +681,11 @@ func (c *cmdInit) askStoragePool(config *api.InitPreseed, d lxd.InstanceServer, } defaultStorage := "dir" - if backingFs == "btrfs" && shared.StringInSlice("btrfs", availableBackends) { + if backingFs == "btrfs" && shared.ValueInSlice("btrfs", availableBackends) { defaultStorage = "btrfs" - } else if shared.StringInSlice("zfs", availableBackends) { + } else if shared.ValueInSlice("zfs", availableBackends) { defaultStorage = "zfs" - } else if shared.StringInSlice("btrfs", availableBackends) { + } else if shared.ValueInSlice("btrfs", availableBackends) { defaultStorage = "btrfs" } @@ -726,7 +726,7 @@ func (c *cmdInit) askStoragePool(config *api.InitPreseed, d lxd.InstanceServer, if len(availableBackends) > 1 { defaultBackend := defaultStorage if poolType == util.PoolTypeRemote { - if shared.StringInSlice("ceph", availableBackends) { + if shared.ValueInSlice("ceph", availableBackends) { defaultBackend = "ceph" } else { defaultBackend = availableBackends[0] // Default to first remote driver. diff --git a/lxd/main_sql.go b/lxd/main_sql.go index 567774b119b8..7258c6542287 100644 --- a/lxd/main_sql.go +++ b/lxd/main_sql.go @@ -70,7 +70,7 @@ func (c *cmdSql) Run(cmd *cobra.Command, args []string) error { database := args[0] query := args[1] - if !shared.StringInSlice(database, []string{"local", "global"}) { + if !shared.ValueInSlice(database, []string{"local", "global"}) { _ = cmd.Help() return fmt.Errorf("Invalid database type") diff --git a/lxd/migrate_storage_volumes.go b/lxd/migrate_storage_volumes.go index a75c9e301ea1..d596553cc148 100644 --- a/lxd/migrate_storage_volumes.go +++ b/lxd/migrate_storage_volumes.go @@ -168,7 +168,7 @@ func (s *migrationSourceWs) DoStorage(state *state.State, projectName string, po // Ensure that only the requested snapshots are included in the migration index header. volSourceArgs.Info.Config.VolumeSnapshots = make([]*api.StorageVolumeSnapshot, 0, len(volSourceArgs.Snapshots)) for i := range allSnapshots { - if shared.StringInSlice(allSnapshots[i].Name, volSourceArgs.Snapshots) { + if shared.ValueInSlice(allSnapshots[i].Name, volSourceArgs.Snapshots) { volSourceArgs.Info.Config.VolumeSnapshots = append(volSourceArgs.Info.Config.VolumeSnapshots, allSnapshots[i]) } } diff --git a/lxd/migration/migration_volumes.go b/lxd/migration/migration_volumes.go index 64b201d0c276..ef7f34e40eb2 100644 --- a/lxd/migration/migration_volumes.go +++ b/lxd/migration/migration_volumes.go @@ -195,7 +195,7 @@ func MatchTypes(offer *MigrationHeader, fallbackType MigrationFSType, ourTypes [ offeredFeatures = offer.GetBtrfsFeaturesSlice() } else if offerFSType == MigrationFSType_RSYNC { offeredFeatures = offer.GetRsyncFeaturesSlice() - if !shared.StringInSlice("bidirectional", offeredFeatures) { + if !shared.ValueInSlice("bidirectional", offeredFeatures) { // If no bi-directional support, this means we are getting a response from // an old LXD server that doesn't support bidirectional negotiation, so // assume LXD 3.7 level. NOTE: Do NOT extend this list of arguments. @@ -206,19 +206,19 @@ func MatchTypes(offer *MigrationHeader, fallbackType MigrationFSType, ourTypes [ // Find common features in both our type and offered type. commonFeatures := []string{} for _, ourFeature := range ourType.Features { - if shared.StringInSlice(ourFeature, offeredFeatures) { + if shared.ValueInSlice(ourFeature, offeredFeatures) { commonFeatures = append(commonFeatures, ourFeature) } } if offer.GetRefresh() { // Optimized refresh with zfs only works if ZfsFeatureMigrationHeader is available. - if ourType.FSType == MigrationFSType_ZFS && !shared.StringInSlice(ZFSFeatureMigrationHeader, commonFeatures) { + if ourType.FSType == MigrationFSType_ZFS && !shared.ValueInSlice(ZFSFeatureMigrationHeader, commonFeatures) { continue } // Optimized refresh with btrfs only works if BtrfsFeatureSubvolumeUUIDs is available. - if ourType.FSType == MigrationFSType_BTRFS && !shared.StringInSlice(BTRFSFeatureSubvolumeUUIDs, commonFeatures) { + if ourType.FSType == MigrationFSType_BTRFS && !shared.ValueInSlice(BTRFSFeatureSubvolumeUUIDs, commonFeatures) { continue } } diff --git a/lxd/network/acl/acl_load.go b/lxd/network/acl/acl_load.go index b514eb5c689a..4da2c1b3789d 100644 --- a/lxd/network/acl/acl_load.go +++ b/lxd/network/acl/acl_load.go @@ -62,7 +62,7 @@ func Exists(s *state.State, projectName string, name ...string) error { checkedACLNames := make(map[string]struct{}, len(name)) for _, aclName := range name { - if !shared.StringInSlice(aclName, existingACLNames) { + if !shared.ValueInSlice(aclName, existingACLNames) { return fmt.Errorf("Network ACL %q does not exist", aclName) } @@ -99,7 +99,7 @@ func UsedBy(s *state.State, aclProjectName string, usageFunc func(matchedACLName netACLNames := shared.SplitNTrimSpace(network.Config["security.acls"], ",", -1, true) matchedACLNames := []string{} for _, netACLName := range netACLNames { - if shared.StringInSlice(netACLName, matchACLNames) { + if shared.ValueInSlice(netACLName, matchACLNames) { matchedACLNames = append(matchedACLNames, netACLName) } } @@ -178,7 +178,7 @@ func UsedBy(s *state.State, aclProjectName string, usageFunc func(matchedACLName for _, rule := range aclInfo.Ingress { for _, subject := range shared.SplitNTrimSpace(rule.Source, ",", -1, true) { // Look for new matching ACLs, but ignore our own ACL reference in our own rules. - if shared.StringInSlice(subject, matchACLNames) && !shared.StringInSlice(subject, matchedACLNames) && subject != aclInfo.Name { + if shared.ValueInSlice(subject, matchACLNames) && !shared.ValueInSlice(subject, matchedACLNames) && subject != aclInfo.Name { matchedACLNames = append(matchedACLNames, subject) } } @@ -188,7 +188,7 @@ func UsedBy(s *state.State, aclProjectName string, usageFunc func(matchedACLName for _, rule := range aclInfo.Egress { for _, subject := range shared.SplitNTrimSpace(rule.Destination, ",", -1, true) { // Look for new matching ACLs, but ignore our own ACL reference in our own rules. - if shared.StringInSlice(subject, matchACLNames) && !shared.StringInSlice(subject, matchedACLNames) && subject != aclInfo.Name { + if shared.ValueInSlice(subject, matchACLNames) && !shared.ValueInSlice(subject, matchedACLNames) && subject != aclInfo.Name { matchedACLNames = append(matchedACLNames, subject) } } @@ -246,7 +246,7 @@ func isInUseByDevice(d deviceConfig.Device, matchACLNames ...string) []string { } for _, nicACLName := range shared.SplitNTrimSpace(d["security.acls"], ",", -1, true) { - if shared.StringInSlice(nicACLName, matchACLNames) { + if shared.ValueInSlice(nicACLName, matchACLNames) { matchedACLNames = append(matchedACLNames, nicACLName) } } @@ -275,7 +275,7 @@ func NetworkUsage(s *state.State, aclProjectName string, aclNames []string, aclN return fmt.Errorf("Failed to load network %q: %w", nicConfig["network"], err) } - if shared.StringInSlice(network.Type, supportedNetTypes) { + if shared.ValueInSlice(network.Type, supportedNetTypes) { _, found := aclNets[network.Name] if !found { aclNets[network.Name] = NetworkACLUsage{ @@ -288,7 +288,7 @@ func NetworkUsage(s *state.State, aclProjectName string, aclNames []string, aclN } case *api.Network: - if shared.StringInSlice(u.Type, supportedNetTypes) { + if shared.ValueInSlice(u.Type, supportedNetTypes) { _, found := aclNets[u.Name] if !found { networkID, network, _, err := s.DB.Cluster.GetNetworkInAnyState(aclProjectName, u.Name) diff --git a/lxd/network/acl/acl_ovn.go b/lxd/network/acl/acl_ovn.go index ee1d35b9679b..36ed2f6b05e6 100644 --- a/lxd/network/acl/acl_ovn.go +++ b/lxd/network/acl/acl_ovn.go @@ -299,7 +299,7 @@ func ovnAddReferencedACLs(info *api.NetworkACL, referencedACLNames map[string]st continue // Skip subjects already seen. } - if shared.StringInSlice(subject, append(ruleSubjectInternalAliases, ruleSubjectExternalAliases...)) { + if shared.ValueInSlice(subject, append(ruleSubjectInternalAliases, ruleSubjectExternalAliases...)) { continue // Skip special reserved subjects that are not ACL names. } @@ -481,7 +481,7 @@ func ovnRuleCriteriaToOVNACLRule(direction string, rule *api.NetworkACLRule, por } // Add protocol filters. - if shared.StringInSlice(rule.Protocol, []string{"tcp", "udp"}) { + if shared.ValueInSlice(rule.Protocol, []string{"tcp", "udp"}) { matchParts = append(matchParts, rule.Protocol) if rule.SourcePort != "" { @@ -491,7 +491,7 @@ func ovnRuleCriteriaToOVNACLRule(direction string, rule *api.NetworkACLRule, por if rule.DestinationPort != "" { matchParts = append(matchParts, ovnRulePortToOVNACLMatch(rule.Protocol, "dst", shared.SplitNTrimSpace(rule.DestinationPort, ",", -1, false)...)) } - } else if shared.StringInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { + } else if shared.ValueInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { matchParts = append(matchParts, rule.Protocol) if rule.ICMPType != "" { @@ -567,13 +567,13 @@ func ovnRuleSubjectToOVNACLMatch(direction string, aclNameIDs map[string]int64, } else { // If not valid IP subnet, check if subject is ACL name or network peer name. var subjectPortSelector openvswitch.OVNPortGroup - if shared.StringInSlice(subjectCriterion, ruleSubjectInternalAliases) { + if shared.ValueInSlice(subjectCriterion, ruleSubjectInternalAliases) { // Use pseudo port group name for special reserved port selector types. // These will be expanded later for each network specific rule. // Convert deprecated #internal to non-deprecated @internal if needed. subjectPortSelector = openvswitch.OVNPortGroup(ruleSubjectInternal) networkSpecific = true - } else if shared.StringInSlice(subjectCriterion, ruleSubjectExternalAliases) { + } else if shared.ValueInSlice(subjectCriterion, ruleSubjectExternalAliases) { // Use pseudo port group name for special reserved port selector types. // These will be expanded later for each network specific rule. // Convert deprecated #external to non-deprecated @external if needed. @@ -906,7 +906,7 @@ func OVNPortGroupDeleteIfUnused(s *state.State, l logger.Logger, client *openvsw aclUsedACLS[matchedACLName] = make([]string, 0, 1) } - if !shared.StringInSlice(u.Name, aclUsedACLS[matchedACLName]) { + if !shared.ValueInSlice(u.Name, aclUsedACLS[matchedACLName]) { // Record as in use by another ACL entity. aclUsedACLS[matchedACLName] = append(aclUsedACLS[matchedACLName], u.Name) } @@ -974,11 +974,11 @@ func OVNPortGroupInstanceNICSchedule(portUUID openvswitch.OVNSwitchPortUUID, cha // OVNApplyInstanceNICDefaultRules applies instance NIC default rules to per-network port group. func OVNApplyInstanceNICDefaultRules(client *openvswitch.OVN, switchPortGroup openvswitch.OVNPortGroup, logPrefix string, nicPortName openvswitch.OVNSwitchPort, ingressAction string, ingressLogged bool, egressAction string, egressLogged bool) error { - if !shared.StringInSlice(ingressAction, ValidActions) { + if !shared.ValueInSlice(ingressAction, ValidActions) { return fmt.Errorf("Invalid ingress action %q", ingressAction) } - if !shared.StringInSlice(egressAction, ValidActions) { + if !shared.ValueInSlice(egressAction, ValidActions) { return fmt.Errorf("Invalid egress action %q", egressAction) } diff --git a/lxd/network/acl/driver_common.go b/lxd/network/acl/driver_common.go index 97410bfab8ab..d55c7b95565a 100644 --- a/lxd/network/acl/driver_common.go +++ b/lxd/network/acl/driver_common.go @@ -289,13 +289,13 @@ func (d *common) validateConfigMap(config map[string]string, rules map[string]fu // validateRule validates the rule supplied. func (d *common) validateRule(direction ruleDirection, rule api.NetworkACLRule) error { // Validate Action field (required). - if !shared.StringInSlice(rule.Action, ValidActions) { + if !shared.ValueInSlice(rule.Action, ValidActions) { return fmt.Errorf("Action must be one of: %s", strings.Join(ValidActions, ", ")) } // Validate State field (required). validStates := []string{"enabled", "disabled", "logged"} - if !shared.StringInSlice(rule.State, validStates) { + if !shared.ValueInSlice(rule.State, validStates) { return fmt.Errorf("State must be one of: %s", strings.Join(validStates, ", ")) } @@ -345,13 +345,13 @@ func (d *common) validateRule(direction ruleDirection, rule api.NetworkACLRule) // Validate Protocol field. if rule.Protocol != "" { validProtocols := []string{"icmp4", "icmp6", "tcp", "udp"} - if !shared.StringInSlice(rule.Protocol, validProtocols) { + if !shared.ValueInSlice(rule.Protocol, validProtocols) { return fmt.Errorf("Protocol must be one of: %s", strings.Join(validProtocols, ", ")) } } // Validate protocol dependent fields. - if shared.StringInSlice(rule.Protocol, []string{"tcp", "udp"}) { + if shared.ValueInSlice(rule.Protocol, []string{"tcp", "udp"}) { if rule.ICMPType != "" { return fmt.Errorf("ICMP type cannot be used with non-ICMP protocol") } @@ -375,7 +375,7 @@ func (d *common) validateRule(direction ruleDirection, rule api.NetworkACLRule) return fmt.Errorf("Invalid Destination port: %w", err) } } - } else if shared.StringInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { + } else if shared.ValueInSlice(rule.Protocol, []string{"icmp4", "icmp6"}) { if rule.SourcePort != "" { return fmt.Errorf("Source port cannot be used with %q protocol", rule.Protocol) } diff --git a/lxd/network/driver_bridge.go b/lxd/network/driver_bridge.go index 00f4e7fdd11c..b8c58fca11df 100644 --- a/lxd/network/driver_bridge.go +++ b/lxd/network/driver_bridge.go @@ -348,7 +348,7 @@ func (n *bridge) Validate(config map[string]string) error { for k, v := range config { key := k // Bridge mode checks - if bridgeMode == "fan" && strings.HasPrefix(key, "ipv4.") && !shared.StringInSlice(key, []string{"ipv4.dhcp.expiry", "ipv4.firewall", "ipv4.nat", "ipv4.nat.order"}) && v != "" { + if bridgeMode == "fan" && strings.HasPrefix(key, "ipv4.") && !shared.ValueInSlice(key, []string{"ipv4.dhcp.expiry", "ipv4.firewall", "ipv4.nat", "ipv4.nat.order"}) && v != "" { return fmt.Errorf("IPv4 configuration may not be set when in 'fan' mode") } @@ -719,7 +719,7 @@ func (n *bridge) setup(oldConfig map[string]string) error { } // IPv6 bridge configuration. - if !shared.StringInSlice(n.config["ipv6.address"], []string{"", "none"}) { + if !shared.ValueInSlice(n.config["ipv6.address"], []string{"", "none"}) { if !shared.PathExists("/proc/sys/net/ipv6") { return fmt.Errorf("Network has ipv6.address but kernel IPv6 support is missing") } @@ -899,7 +899,7 @@ func (n *bridge) setup(oldConfig map[string]string) error { } // Configure IPv4 firewall (includes fan). - if n.config["bridge.mode"] == "fan" || !shared.StringInSlice(n.config["ipv4.address"], []string{"", "none"}) { + if n.config["bridge.mode"] == "fan" || !shared.ValueInSlice(n.config["ipv4.address"], []string{"", "none"}) { if n.hasDHCPv4() && n.hasIPv4Firewall() { fwOpts.FeaturesV4.ICMPDHCPDNSAccess = true } @@ -952,7 +952,7 @@ func (n *bridge) setup(oldConfig map[string]string) error { } // Configure IPv4. - if !shared.StringInSlice(n.config["ipv4.address"], []string{"", "none"}) { + if !shared.ValueInSlice(n.config["ipv4.address"], []string{"", "none"}) { // Parse the subnet. ipAddress, subnet, err := net.ParseCIDR(n.config["ipv4.address"]) if err != nil { @@ -962,7 +962,7 @@ func (n *bridge) setup(oldConfig map[string]string) error { // Update the dnsmasq config. dnsmasqCmd = append(dnsmasqCmd, fmt.Sprintf("--listen-address=%s", ipAddress.String())) if n.DHCPv4Subnet() != nil { - if !shared.StringInSlice("--dhcp-no-override", dnsmasqCmd) { + if !shared.ValueInSlice("--dhcp-no-override", dnsmasqCmd) { dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-no-override", "--dhcp-authoritative", fmt.Sprintf("--dhcp-leasefile=%s", shared.VarPath("networks", n.name, "dnsmasq.leases")), fmt.Sprintf("--dhcp-hostsfile=%s", shared.VarPath("networks", n.name, "dnsmasq.hosts"))}...) } @@ -1077,7 +1077,7 @@ func (n *bridge) setup(oldConfig map[string]string) error { } // Configure IPv6. - if !shared.StringInSlice(n.config["ipv6.address"], []string{"", "none"}) { + if !shared.ValueInSlice(n.config["ipv6.address"], []string{"", "none"}) { // Enable IPv6 for the subnet. err := util.SysctlSet(fmt.Sprintf("net/ipv6/conf/%s/disable_ipv6", n.name), "0") if err != nil { @@ -1114,7 +1114,7 @@ func (n *bridge) setup(oldConfig map[string]string) error { } // Build DHCP configuration. - if !shared.StringInSlice("--dhcp-no-override", dnsmasqCmd) { + if !shared.ValueInSlice("--dhcp-no-override", dnsmasqCmd) { dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-no-override", "--dhcp-authoritative", fmt.Sprintf("--dhcp-leasefile=%s", shared.VarPath("networks", n.name, "dnsmasq.leases")), fmt.Sprintf("--dhcp-hostsfile=%s", shared.VarPath("networks", n.name, "dnsmasq.hosts"))}...) } @@ -1863,7 +1863,7 @@ func (n *bridge) Update(newNetwork api.NetworkPut, targetNode string, clientType }) // Bring the bridge down entirely if the driver has changed. - if shared.StringInSlice("bridge.driver", changedKeys) && n.isRunning() { + if shared.ValueInSlice("bridge.driver", changedKeys) && n.isRunning() { err = n.Stop() if err != nil { return err @@ -1871,7 +1871,7 @@ func (n *bridge) Update(newNetwork api.NetworkPut, targetNode string, clientType } // Detach any external interfaces should no longer be attached. - if shared.StringInSlice("bridge.external_interfaces", changedKeys) && n.isRunning() { + if shared.ValueInSlice("bridge.external_interfaces", changedKeys) && n.isRunning() { devices := []string{} for _, dev := range strings.Split(newNetwork.Config["bridge.external_interfaces"], ",") { dev = strings.TrimSpace(dev) @@ -1884,7 +1884,7 @@ func (n *bridge) Update(newNetwork api.NetworkPut, targetNode string, clientType continue } - if !shared.StringInSlice(dev, devices) && InterfaceExists(dev) { + if !shared.ValueInSlice(dev, devices) && InterfaceExists(dev) { err = DetachInterface(n.name, dev) if err != nil { return err @@ -2034,7 +2034,7 @@ func (n *bridge) getTunnels() []string { } fields := strings.Split(k, ".") - if !shared.StringInSlice(fields[1], tunnels) { + if !shared.ValueInSlice(fields[1], tunnels) { tunnels = append(tunnels, fields[1]) } } @@ -2254,7 +2254,7 @@ func (n *bridge) updateForkdnsServersFile(addresses []string) error { func (n *bridge) hasIPv4Firewall() bool { // IPv4 firewall is only enabled if there is a bridge ipv4.address or fan mode, and ipv4.firewall enabled. // When using fan bridge.mode, there can be an empty ipv4.address, so we assume it is active. - if (n.config["bridge.mode"] == "fan" || !shared.StringInSlice(n.config["ipv4.address"], []string{"", "none"})) && shared.IsTrueOrEmpty(n.config["ipv4.firewall"]) { + if (n.config["bridge.mode"] == "fan" || !shared.ValueInSlice(n.config["ipv4.address"], []string{"", "none"})) && shared.IsTrueOrEmpty(n.config["ipv4.firewall"]) { return true } @@ -2264,7 +2264,7 @@ func (n *bridge) hasIPv4Firewall() bool { // hasIPv6Firewall indicates whether the network has IPv6 firewall enabled. func (n *bridge) hasIPv6Firewall() bool { // IPv6 firewall is only enabled if there is a bridge ipv6.address and ipv6.firewall enabled. - if !shared.StringInSlice(n.config["ipv6.address"], []string{"", "none"}) && shared.IsTrueOrEmpty(n.config["ipv6.firewall"]) { + if !shared.ValueInSlice(n.config["ipv6.address"], []string{"", "none"}) && shared.IsTrueOrEmpty(n.config["ipv6.firewall"]) { return true } @@ -3085,7 +3085,7 @@ func (n *bridge) Leases(projectName string, clientType request.ClientType) ([]ap // Skip leases that don't match any of the instance MACs from the project (only when we // have populated the projectMacs list in ClientTypeNormal mode). Otherwise get all local // leases and they will be filtered on the server handling the end user request. - if clientType == request.ClientTypeNormal && macStr != "" && !shared.StringInSlice(macStr, projectMacs) { + if clientType == request.ClientTypeNormal && macStr != "" && !shared.ValueInSlice(macStr, projectMacs) { continue } @@ -3115,7 +3115,7 @@ func (n *bridge) Leases(projectName string, clientType request.ClientType) ([]ap // Add local leases from other members, filtering them for MACs that belong to the project. for _, lease := range memberLeases { - if lease.Hwaddr != "" && shared.StringInSlice(lease.Hwaddr, projectMacs) { + if lease.Hwaddr != "" && shared.ValueInSlice(lease.Hwaddr, projectMacs) { leases = append(leases, lease) } } @@ -3132,5 +3132,5 @@ func (n *bridge) Leases(projectName string, clientType request.ClientType) ([]ap // UsesDNSMasq indicates if network's config indicates if it needs to use dnsmasq. func (n *bridge) UsesDNSMasq() bool { - return n.config["bridge.mode"] == "fan" || !shared.StringInSlice(n.config["ipv4.address"], []string{"", "none"}) || !shared.StringInSlice(n.config["ipv6.address"], []string{"", "none"}) + return n.config["bridge.mode"] == "fan" || !shared.ValueInSlice(n.config["ipv4.address"], []string{"", "none"}) || !shared.ValueInSlice(n.config["ipv6.address"], []string{"", "none"}) } diff --git a/lxd/network/driver_common.go b/lxd/network/driver_common.go index deeb1483312a..c535153775cd 100644 --- a/lxd/network/driver_common.go +++ b/lxd/network/driver_common.go @@ -374,7 +374,7 @@ func (n *common) update(applyNetwork api.NetworkPut, targetNode string, clientTy sendNetwork.Config = make(map[string]string) for k, v := range applyNetwork.Config { // Don't forward node specific keys (these will be merged in on recipient node). - if shared.StringInSlice(k, db.NodeSpecificNetworkConfig) { + if shared.ValueInSlice(k, db.NodeSpecificNetworkConfig) { continue } @@ -427,7 +427,7 @@ func (n *common) configChanged(newNetwork api.NetworkPut) (bool, []string, api.N dbUpdateNeeded = true // Add non-user changed key to list of changed keys. - if !strings.HasPrefix(k, "user.") && !shared.StringInSlice(k, changedKeys) { + if !strings.HasPrefix(k, "user.") && !shared.ValueInSlice(k, changedKeys) { changedKeys = append(changedKeys, k) } } @@ -438,7 +438,7 @@ func (n *common) configChanged(newNetwork api.NetworkPut) (bool, []string, api.N dbUpdateNeeded = true // Add non-user changed key to list of changed keys. - if !strings.HasPrefix(k, "user.") && !shared.StringInSlice(k, changedKeys) { + if !strings.HasPrefix(k, "user.") && !shared.ValueInSlice(k, changedKeys) { changedKeys = append(changedKeys, k) } } @@ -674,7 +674,7 @@ func (n *common) bgpSetupPeers(oldConfig map[string]string) error { // Remove old peers. for _, peer := range oldPeers { - if shared.StringInSlice(peer, newPeers) { + if shared.ValueInSlice(peer, newPeers) { continue } @@ -688,7 +688,7 @@ func (n *common) bgpSetupPeers(oldConfig map[string]string) error { // Add new peers. for _, peer := range newPeers { - if shared.StringInSlice(peer, oldPeers) { + if shared.ValueInSlice(peer, oldPeers) { continue } @@ -768,7 +768,7 @@ func (n *common) bgpSetupPrefixes(oldConfig map[string]string) error { return err } } - } else if !shared.StringInSlice(n.config[fmt.Sprintf("ipv%d.address", ipVersion)], []string{"", "none"}) { + } else if !shared.ValueInSlice(n.config[fmt.Sprintf("ipv%d.address", ipVersion)], []string{"", "none"}) { // If network has NAT disabled, then export the network's subnet if specified. netAddress := n.config[fmt.Sprintf("ipv%d.address", ipVersion)] _, subnet, err := net.ParseCIDR(netAddress) @@ -796,7 +796,7 @@ func (n *common) bgpGetPeers(config map[string]string) []string { } fields := strings.Split(k, ".") - if !shared.StringInSlice(fields[2], peerNames) { + if !shared.ValueInSlice(fields[2], peerNames) { peerNames = append(peerNames, fields[2]) } } @@ -891,7 +891,7 @@ func (n *common) forwardValidate(listenAddress net.IP, forward *api.NetworkForwa // Maps portSpecID to a portMap struct. portMaps := make([]*forwardPortMap, 0, len(forward.Ports)) for portSpecID, portSpec := range forward.Ports { - if !shared.StringInSlice(portSpec.Protocol, validPortProcols) { + if !shared.ValueInSlice(portSpec.Protocol, validPortProcols) { return nil, fmt.Errorf("Invalid port protocol in port specification %d, protocol must be one of: %s", portSpecID, strings.Join(validPortProcols, ", ")) } @@ -1225,7 +1225,7 @@ func (n *common) loadBalancerValidate(listenAddress net.IP, forward *api.Network // Check ports config. portMaps := make([]*loadBalancerPortMap, 0, len(forward.Ports)) for portSpecID, portSpec := range forward.Ports { - if !shared.StringInSlice(portSpec.Protocol, validPortProcols) { + if !shared.ValueInSlice(portSpec.Protocol, validPortProcols) { return nil, fmt.Errorf("Invalid port protocol in port specification %d, protocol must be one of: %s", portSpecID, strings.Join(validPortProcols, ", ")) } @@ -1392,7 +1392,7 @@ func (n *common) peerValidate(peerName string, peer *api.NetworkPeerPut) error { return err } - if shared.StringInSlice(peerName, acl.ReservedNetworkSubects) { + if shared.ValueInSlice(peerName, acl.ReservedNetworkSubects) { return fmt.Errorf("Name cannot be one of the reserved network subjects: %v", acl.ReservedNetworkSubects) } diff --git a/lxd/network/driver_ovn.go b/lxd/network/driver_ovn.go index cec85d71f4dd..a949cf731ff1 100644 --- a/lxd/network/driver_ovn.go +++ b/lxd/network/driver_ovn.go @@ -1753,7 +1753,7 @@ func (n *ovn) allowedUplinkNetworks(p *api.Project) ([]string, error) { allowedRestrictedUplinks := shared.SplitNTrimSpace(p.Config["restricted.networks.uplinks"], ",", -1, false) for _, allowedRestrictedUplink := range allowedRestrictedUplinks { - if shared.StringInSlice(allowedRestrictedUplink, uplinkNetworkNames) { + if shared.ValueInSlice(allowedRestrictedUplink, uplinkNetworkNames) { allowedUplinkNetworkNames = append(allowedUplinkNetworkNames, allowedRestrictedUplink) } } @@ -1771,7 +1771,7 @@ func (n *ovn) validateUplinkNetwork(p *api.Project, uplinkNetworkName string) (s } if uplinkNetworkName != "" { - if !shared.StringInSlice(uplinkNetworkName, allowedUplinkNetworks) { + if !shared.ValueInSlice(uplinkNetworkName, allowedUplinkNetworks) { return "", fmt.Errorf(`Option "network" value %q is not one of the allowed uplink networks in project`, uplinkNetworkName) } @@ -2441,7 +2441,7 @@ func (n *ovn) logicalRouterPolicySetup(client *openvswitch.OVN, excludePeers ... // This prevents source address spoofing of peer connection routes from the external network, which in // turn allows us to use the peer connection's address set for referencing traffic from the peer in ACL. err := n.forPeers(func(targetOVNNet *ovn) error { - if shared.Int64InSlice(targetOVNNet.ID(), excludePeers) { + if shared.ValueInSlice(targetOVNNet.ID(), excludePeers) { return nil // Don't setup rules for this peer network connection. } @@ -2909,7 +2909,7 @@ func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType re }) // Stop network before new config applied if uplink network is changing. - if shared.StringInSlice("network", changedKeys) { + if shared.ValueInSlice("network", changedKeys) { err = n.Stop() if err != nil { return err @@ -2938,14 +2938,14 @@ func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType re newACLs := shared.SplitNTrimSpace(newNetwork.Config["security.acls"], ",", -1, true) removedACLs := []string{} for _, oldACL := range oldACLs { - if !shared.StringInSlice(oldACL, newACLs) { + if !shared.ValueInSlice(oldACL, newACLs) { removedACLs = append(removedACLs, oldACL) } } addedACLs := []string{} for _, newACL := range newACLs { - if !shared.StringInSlice(newACL, oldACLs) { + if !shared.ValueInSlice(newACL, oldACLs) { addedACLs = append(addedACLs, newACL) } } @@ -2954,7 +2954,7 @@ func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType re defaultRuleKeys := []string{"security.acls.default.ingress.action", "security.acls.default.egress.action", "security.acls.default.ingress.logged", "security.acls.default.egress.logged"} changedDefaultRuleKeys := []string{} for _, k := range defaultRuleKeys { - if shared.StringInSlice(k, changedKeys) { + if shared.ValueInSlice(k, changedKeys) { changedDefaultRuleKeys = append(changedDefaultRuleKeys, k) } } @@ -2999,7 +2999,7 @@ func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType re if aclConfigChanged { // Check whether we need to add any of the new ACLs to the NIC. for _, addedACL := range addedACLs { - if shared.StringInSlice(addedACL, nicACLs) { + if shared.ValueInSlice(addedACL, nicACLs) { continue // NIC already has this ACL applied directly, so no need to add. } @@ -3016,7 +3016,7 @@ func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType re // Check whether we need to remove any of the removed ACLs from the NIC. for _, removedACL := range removedACLs { - if shared.StringInSlice(removedACL, nicACLs) { + if shared.ValueInSlice(removedACL, nicACLs) { continue // NIC still has this ACL applied directly, so don't remove. } @@ -3109,7 +3109,7 @@ func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType re // Remove any old unused subnet addresses from the internal switch's address set. rebuildPeers := false for _, key := range []string{"ipv4.address", "ipv6.address"} { - if shared.StringInSlice(key, changedKeys) { + if shared.ValueInSlice(key, changedKeys) { rebuildPeers = true _, oldRouterIntPortIPNet, _ := net.ParseCIDR(oldNetwork.Config[key]) if oldRouterIntPortIPNet != nil { @@ -3143,7 +3143,7 @@ func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType re } // If uplink network is changing, start network after config applied. - if shared.StringInSlice("network", changedKeys) { + if shared.ValueInSlice("network", changedKeys) { err = n.Start() if err != nil { return err @@ -3213,7 +3213,7 @@ func (n *ovn) InstanceDevicePortValidateExternalRoutes(deviceInstance instance.I } // Check port's external routes are suffciently small when using l2proxy ingress mode on uplink. - if shared.StringInSlice(uplink.Config["ovn.ingress_mode"], []string{"l2proxy", ""}) { + if shared.ValueInSlice(uplink.Config["ovn.ingress_mode"], []string{"l2proxy", ""}) { for _, portExternalRoute := range portExternalRoutes { rOnes, rBits := portExternalRoute.Mask.Size() if rBits > 32 && rOnes < 122 { @@ -3619,7 +3619,7 @@ func (n *ovn) InstanceDevicePortStart(opts *OVNInstanceNICSetupOpts, securityACL } // Publish NIC's IPs on uplink network if NAT is disabled and using l2proxy ingress mode on uplink. - if shared.StringInSlice(opts.UplinkConfig["ovn.ingress_mode"], []string{"l2proxy", ""}) { + if shared.ValueInSlice(opts.UplinkConfig["ovn.ingress_mode"], []string{"l2proxy", ""}) { for _, k := range []string{"ipv4.nat", "ipv6.nat"} { if shared.IsTrue(n.config[k]) { continue @@ -3699,7 +3699,7 @@ func (n *ovn) InstanceDevicePortStart(opts *OVNInstanceNICSetupOpts, securityACL // knowledge this is the only way to get the OVN router to respond to ARP/NDP requests for IPs that // it doesn't actually have). However we have to add each IP in the external route individually as // DNAT doesn't support whole subnets. - if shared.StringInSlice(opts.UplinkConfig["ovn.ingress_mode"], []string{"l2proxy", ""}) { + if shared.ValueInSlice(opts.UplinkConfig["ovn.ingress_mode"], []string{"l2proxy", ""}) { err = SubnetIterate(externalRoute, func(ip net.IP) error { err = client.LogicalRouterDNATSNATAdd(n.getRouterName(), ip, ip, true, true) if err != nil { @@ -3791,7 +3791,7 @@ func (n *ovn) InstanceDevicePortStart(opts *OVNInstanceNICSetupOpts, securityACL nicACLNames := shared.SplitNTrimSpace(opts.DeviceConfig["security.acls"], ",", -1, true) for _, aclName := range netACLNames { - if !shared.StringInSlice(aclName, nicACLNames) { + if !shared.ValueInSlice(aclName, nicACLNames) { nicACLNames = append(nicACLNames, aclName) } } @@ -3848,7 +3848,7 @@ func (n *ovn) InstanceDevicePortStart(opts *OVNInstanceNICSetupOpts, securityACL for _, aclName := range securityACLsRemove { // Don't remove ACLs that are in the add ACLs list (there are possibly added from // the network assigned ACLs). - if shared.StringInSlice(aclName, nicACLNames) { + if shared.ValueInSlice(aclName, nicACLNames) { continue } @@ -4020,7 +4020,7 @@ func (n *ovn) InstanceDevicePortStop(ovsExternalOVNPort openvswitch.OVNSwitchPor removeRoutes = append(removeRoutes, *externalRoute) // Remove the DNAT rules when using l2proxy ingress mode on uplink. - if shared.StringInSlice(uplink.Config["ovn.ingress_mode"], []string{"l2proxy", ""}) { + if shared.ValueInSlice(uplink.Config["ovn.ingress_mode"], []string{"l2proxy", ""}) { err = SubnetIterate(externalRoute, func(ip net.IP) error { removeNATIPs = append(removeNATIPs, ip) @@ -4315,7 +4315,7 @@ func (n *ovn) uplinkHasIngressRoutedAnycastIPv6(uplink *api.Network) bool { func (n *ovn) handleDependencyChange(uplinkName string, uplinkConfig map[string]string, changedKeys []string) error { // Detect changes that need to be applied to the network. for _, k := range []string{"dns.nameservers"} { - if shared.StringInSlice(k, changedKeys) { + if shared.ValueInSlice(k, changedKeys) { n.logger.Debug("Applying changes from uplink network", logger.Ctx{"uplink": uplinkName}) // Re-setup logical network in order to apply uplink changes. @@ -4329,7 +4329,7 @@ func (n *ovn) handleDependencyChange(uplinkName string, uplinkConfig map[string] } // Add or remove the instance NIC l2proxy DNAT_AND_SNAT rules if uplink's ovn.ingress_mode has changed. - if shared.StringInSlice("ovn.ingress_mode", changedKeys) { + if shared.ValueInSlice("ovn.ingress_mode", changedKeys) { n.logger.Debug("Applying ingress mode changes from uplink network to instance NICs", logger.Ctx{"uplink": uplinkName}) client, err := openvswitch.NewOVN(n.state) @@ -4337,7 +4337,7 @@ func (n *ovn) handleDependencyChange(uplinkName string, uplinkConfig map[string] return fmt.Errorf("Failed to get OVN client: %w", err) } - if shared.StringInSlice(uplinkConfig["ovn.ingress_mode"], []string{"l2proxy", ""}) { + if shared.ValueInSlice(uplinkConfig["ovn.ingress_mode"], []string{"l2proxy", ""}) { // Get list of active switch ports (avoids repeated querying of OVN NB). activePorts, err := client.LogicalSwitchPorts(n.getIntSwitchName()) if err != nil { diff --git a/lxd/network/driver_physical.go b/lxd/network/driver_physical.go index 30914ea48452..127101b197cf 100644 --- a/lxd/network/driver_physical.go +++ b/lxd/network/driver_physical.go @@ -294,7 +294,7 @@ func (n *physical) Update(newNetwork api.NetworkPut, targetNode string, clientTy revert := revert.New() defer revert.Fail() - hostNameChanged := shared.StringInSlice("vlan", changedKeys) || shared.StringInSlice("parent", changedKeys) + hostNameChanged := shared.ValueInSlice("vlan", changedKeys) || shared.ValueInSlice("parent", changedKeys) // We only need to check in the database once, not on every clustered node. if clientType == request.ClientTypeNormal { diff --git a/lxd/network/network_utils.go b/lxd/network/network_utils.go index eeba64d31e9d..0ac3411d16e9 100644 --- a/lxd/network/network_utils.go +++ b/lxd/network/network_utils.go @@ -409,7 +409,7 @@ func UpdateDNSMasqStatic(s *state.State, networkName string) error { } // Skip devices not connected to managed networks. - if !shared.StringInSlice(d["parent"], networks) { + if !shared.ValueInSlice(d["parent"], networks) { continue } @@ -1361,7 +1361,7 @@ func ProxyParseAddr(data string) (*deviceConfig.ProxyAddress, error) { // Split into and
. fields := strings.SplitN(data, ":", 2) - if !shared.StringInSlice(fields[0], []string{"tcp", "udp", "unix"}) { + if !shared.ValueInSlice(fields[0], []string{"tcp", "udp", "unix"}) { return nil, fmt.Errorf("Unknown protocol type %q", fields[0]) } @@ -1388,7 +1388,7 @@ func ProxyParseAddr(data string) (*deviceConfig.ProxyAddress, error) { } // Validate that it's a valid address. - if shared.StringInSlice(newProxyAddr.ConnType, []string{"udp", "tcp"}) { + if shared.ValueInSlice(newProxyAddr.ConnType, []string{"udp", "tcp"}) { err := validate.Optional(validate.IsNetworkAddress)(address) if err != nil { return nil, err diff --git a/lxd/network/openvswitch/ovn.go b/lxd/network/openvswitch/ovn.go index 4dcad662f503..bae7169225bf 100644 --- a/lxd/network/openvswitch/ovn.go +++ b/lxd/network/openvswitch/ovn.go @@ -1539,7 +1539,7 @@ func (o *OVN) ChassisGroupChassisDelete(haChassisGroupName OVNChassisGroup, chas members := shared.SplitNTrimSpace(lines[1], " ", -1, true) // Remove chassis from group if exists. - if existingChassisGroup == string(haChassisGroupName) && shared.StringInSlice(chassisID, members) { + if existingChassisGroup == string(haChassisGroupName) && shared.ValueInSlice(chassisID, members) { _, err := o.nbctl("ha-chassis-group-remove-chassis", string(haChassisGroupName), chassisID) if err != nil { return err diff --git a/lxd/network/zone/record.go b/lxd/network/zone/record.go index 1d5853c5e592..a08d44352bfa 100644 --- a/lxd/network/zone/record.go +++ b/lxd/network/zone/record.go @@ -134,7 +134,7 @@ func (d *zone) validateEntries(info api.NetworkZoneRecordPut) error { } entryID := entry.Type + "/" + entry.Value - if shared.StringInSlice(entryID, uniqueEntries) { + if shared.ValueInSlice(entryID, uniqueEntries) { return fmt.Errorf("Duplicate record for type %q and value %q", entry.Type, entry.Value) } diff --git a/lxd/network/zone/zone.go b/lxd/network/zone/zone.go index 8ba81106ea1f..2fdd42350511 100644 --- a/lxd/network/zone/zone.go +++ b/lxd/network/zone/zone.go @@ -76,7 +76,7 @@ func (d *zone) Info() *api.NetworkZone { func (d *zone) networkUsesZone(netConfig map[string]string) bool { for _, key := range []string{"dns.zone.forward", "dns.zone.reverse.ipv4", "dns.zone.reverse.ipv6"} { zoneNames := shared.SplitNTrimSpace(netConfig[key], ",", -1, true) - if shared.StringInSlice(d.info.Name, zoneNames) { + if shared.ValueInSlice(d.info.Name, zoneNames) { return true } } diff --git a/lxd/network_allocations.go b/lxd/network_allocations.go index af2c72a8cb3e..d1a7a68b1ee5 100644 --- a/lxd/network_allocations.go +++ b/lxd/network_allocations.go @@ -150,7 +150,7 @@ func networkAllocationsGet(d *Daemon, r *http.Request) response.Response { } for _, lease := range leases { - if shared.StringInSlice(lease.Type, []string{"static", "dynamic"}) { + if shared.ValueInSlice(lease.Type, []string{"static", "dynamic"}) { cidrAddr, nat, err := ipToCIDR(lease.Address, netConf) if err != nil { return response.SmartError(err) diff --git a/lxd/networks.go b/lxd/networks.go index 76eaad2af70c..b4ff754359c1 100644 --- a/lxd/networks.go +++ b/lxd/networks.go @@ -201,7 +201,7 @@ func networksGet(d *Daemon, r *http.Request) response.Response { } // Append to the list of networks if a managed network of same name doesn't exist. - if !shared.StringInSlice(iface.Name, networkNames) { + if !shared.ValueInSlice(iface.Name, networkNames) { networkNames = append(networkNames, iface.Name) } } @@ -338,7 +338,7 @@ func networksPost(d *Daemon, r *http.Request) response.Response { // Only check network limits if the new network name doesn't exist already in networks list. // If it does then this create request will either be for adding a target node to an existing // pending network or it will fail anyway as it is a duplicate. - if !shared.StringInSlice(req.Name, networks) && len(networks) >= networksLimit { + if !shared.ValueInSlice(req.Name, networks) && len(networks) >= networksLimit { return response.BadRequest(fmt.Errorf("Networks limit has been reached for project")) } } @@ -374,7 +374,7 @@ func networksPost(d *Daemon, r *http.Request) response.Response { // A targetNode was specified, let's just define the node's network without actually creating it. // Check that only NodeSpecificNetworkConfig keys are specified. for key := range req.Config { - if !shared.StringInSlice(key, db.NodeSpecificNetworkConfig) { + if !shared.ValueInSlice(key, db.NodeSpecificNetworkConfig) { return response.BadRequest(fmt.Errorf("Config key %q may not be used as member-specific key", key)) } } @@ -492,7 +492,7 @@ func networkPartiallyCreated(netInfo *api.Network) bool { // If the network has global config keys, then it has previously been created by having its global config // inserted, and this means it is partialled created. for key := range netInfo.Config { - if !shared.StringInSlice(key, db.NodeSpecificNetworkConfig) { + if !shared.ValueInSlice(key, db.NodeSpecificNetworkConfig) { return true } } @@ -506,7 +506,7 @@ func networkPartiallyCreated(netInfo *api.Network) bool { func networksPostCluster(s *state.State, projectName string, netInfo *api.Network, req api.NetworksPost, clientType clusterRequest.ClientType, netType network.Type) error { // Check that no node-specific config key has been supplied in request. for key := range req.Config { - if shared.StringInSlice(key, db.NodeSpecificNetworkConfig) { + if shared.ValueInSlice(key, db.NodeSpecificNetworkConfig) { return fmt.Errorf("Config key %q is cluster member specific", key) } } @@ -1112,7 +1112,7 @@ func networkPost(d *Daemon, r *http.Request) response.Response { return response.InternalError(err) } - if shared.StringInSlice(req.Name, networks) { + if shared.ValueInSlice(req.Name, networks) { return response.Conflict(fmt.Errorf("Network %q already exists", req.Name)) } @@ -1240,7 +1240,7 @@ func networkPut(d *Daemon, r *http.Request) response.Response { if targetNode == "" { // If no target is specified, then ensure only non-node-specific config keys are changed. for k := range req.Config { - if shared.StringInSlice(k, db.NodeSpecificNetworkConfig) { + if shared.ValueInSlice(k, db.NodeSpecificNetworkConfig) { return response.BadRequest(fmt.Errorf("Config key %q is cluster member specific", k)) } } @@ -1249,7 +1249,7 @@ func networkPut(d *Daemon, r *http.Request) response.Response { // If a target is specified, then ensure only node-specific config keys are changed. for k, v := range req.Config { - if !shared.StringInSlice(k, db.NodeSpecificNetworkConfig) && curConfig[k] != v { + if !shared.ValueInSlice(k, db.NodeSpecificNetworkConfig) && curConfig[k] != v { return response.BadRequest(fmt.Errorf("Config key %q may not be used as member-specific key", k)) } } @@ -1323,7 +1323,7 @@ func doNetworkUpdate(projectName string, n network.Network, req api.NetworkPut, // node-specific network config with the submitted config to allow validation. // This allows removal of non-node specific keys when they are absent from request config. for k, v := range n.Config() { - if shared.StringInSlice(k, db.NodeSpecificNetworkConfig) { + if shared.ValueInSlice(k, db.NodeSpecificNetworkConfig) { req.Config[k] = v } } diff --git a/lxd/patches.go b/lxd/patches.go index 40ddd5ab69cb..6389f3c74cdb 100644 --- a/lxd/patches.go +++ b/lxd/patches.go @@ -127,7 +127,7 @@ func patchesApply(d *Daemon, stage patchStage) error { return fmt.Errorf("Patch %q has no stage set: %d", patch.name, patch.stage) } - if shared.StringInSlice(patch.name, appliedPatches) { + if shared.ValueInSlice(patch.name, appliedPatches) { continue } diff --git a/lxd/profiles.go b/lxd/profiles.go index 14eb7a8cf0b3..9422fc9d9e71 100644 --- a/lxd/profiles.go +++ b/lxd/profiles.go @@ -267,7 +267,7 @@ func profilesPost(d *Daemon, r *http.Request) response.Response { return response.BadRequest(fmt.Errorf("Profile names may not contain slashes")) } - if shared.StringInSlice(req.Name, []string{".", ".."}) { + if shared.ValueInSlice(req.Name, []string{".", ".."}) { return response.BadRequest(fmt.Errorf("Invalid profile name %q", req.Name)) } @@ -725,7 +725,7 @@ func profilePost(d *Daemon, r *http.Request) response.Response { return response.BadRequest(fmt.Errorf("Profile names may not contain slashes")) } - if shared.StringInSlice(req.Name, []string{".", ".."}) { + if shared.ValueInSlice(req.Name, []string{".", ".."}) { return response.BadRequest(fmt.Errorf("Invalid profile name %q", req.Name)) } diff --git a/lxd/project/permissions.go b/lxd/project/permissions.go index 06312efb817c..15354c419f1a 100644 --- a/lxd/project/permissions.go +++ b/lxd/project/permissions.go @@ -67,7 +67,7 @@ func AllowInstanceCreation(tx *db.ClusterTx, projectName string, req api.Instanc // Special case restriction checks on volatile.* keys. strip := false - if shared.StringInSlice(req.Source.Type, []string{"copy", "migration"}) { + if shared.ValueInSlice(req.Source.Type, []string{"copy", "migration"}) { // Allow stripping volatile keys if dealing with a copy or migration. strip = true } @@ -179,7 +179,7 @@ func checkRestrictionsOnVolatileConfig(project api.Project, instanceType instanc // Checker for safe volatile keys. isSafeKey := func(key string) bool { - if shared.StringInSlice(key, []string{"volatile.apply_template", "volatile.base_image", "volatile.last_state.power"}) { + if shared.ValueInSlice(key, []string{"volatile.apply_template", "volatile.base_image", "volatile.last_state.power"}) { return true } @@ -312,7 +312,7 @@ func checkRestrictionsAndAggregateLimits(tx *db.ClusterTx, info *projectInfo) er aggregateKeys := []string{} isRestricted := false for key, value := range info.Project.Config { - if shared.StringInSlice(key, allAggregateLimits) { + if shared.ValueInSlice(key, allAggregateLimits) { aggregateKeys = append(aggregateKeys, key) continue } @@ -823,11 +823,11 @@ var allowableIntercept = []string{ // Return true if a low-level container option is forbidden. func isContainerLowLevelOptionForbidden(key string) bool { - if strings.HasPrefix(key, "security.syscalls.intercept") && !shared.StringInSlice(key, allowableIntercept) { + if strings.HasPrefix(key, "security.syscalls.intercept") && !shared.ValueInSlice(key, allowableIntercept) { return true } - if shared.StringInSlice(key, []string{ + if shared.ValueInSlice(key, []string{ "boot.host_shutdown_timeout", "linux.kernel_modules", "raw.apparmor", @@ -846,7 +846,7 @@ func isContainerLowLevelOptionForbidden(key string) bool { // Return true if a low-level VM option is forbidden. func isVMLowLevelOptionForbidden(key string) bool { - return shared.StringInSlice(key, []string{ + return shared.ValueInSlice(key, []string{ "boot.host_shutdown_timeout", "limits.memory.hugepages", "raw.idmap", @@ -1526,7 +1526,7 @@ func AllowClusterMember(p *api.Project, member *db.NodeInfo) error { if shared.IsTrue(p.Config["restricted"]) && len(clusterGroupsAllowed) > 0 { for _, memberGroupName := range member.Groups { - if shared.StringInSlice(memberGroupName, clusterGroupsAllowed) { + if shared.ValueInSlice(memberGroupName, clusterGroupsAllowed) { return nil } } @@ -1546,7 +1546,7 @@ func AllowClusterGroup(p *api.Project, groupName string) error { return nil } - if len(clusterGroupsAllowed) > 0 && !shared.StringInSlice(groupName, clusterGroupsAllowed) { + if len(clusterGroupsAllowed) > 0 && !shared.ValueInSlice(groupName, clusterGroupsAllowed) { return fmt.Errorf("Project isn't allowed to use this cluster group: %q", groupName) } diff --git a/lxd/project/project.go b/lxd/project/project.go index 650342d7f99d..00feba4231c2 100644 --- a/lxd/project/project.go +++ b/lxd/project/project.go @@ -210,7 +210,7 @@ func NetworkAllowed(reqProjectConfig map[string]string, networkName string, isMa } // Don't allow access to unmanaged networks if only managed network access is allowed. - if shared.StringInSlice(reqProjectConfig["restricted.devices.nic"], []string{"managed", ""}) && !isManaged { + if shared.ValueInSlice(reqProjectConfig["restricted.devices.nic"], []string{"managed", ""}) && !isManaged { return false } @@ -221,7 +221,7 @@ func NetworkAllowed(reqProjectConfig map[string]string, networkName string, isMa // Check if reqquested network is in list of allowed networks. allowedRestrictedNetworks := shared.SplitNTrimSpace(reqProjectConfig["restricted.networks.access"], ",", -1, false) - return shared.StringInSlice(networkName, allowedRestrictedNetworks) + return shared.ValueInSlice(networkName, allowedRestrictedNetworks) } // ProfileProject returns the effective project to use for the profile based on the requested project. diff --git a/lxd/resources/cpu.go b/lxd/resources/cpu.go index 9eda0586c1d8..35816fe267d4 100644 --- a/lxd/resources/cpu.go +++ b/lxd/resources/cpu.go @@ -12,6 +12,7 @@ import ( "github.com/digitalocean/go-smbios/smbios" "golang.org/x/sys/unix" + "github.com/canonical/lxd/shared" "github.com/canonical/lxd/shared/api" ) @@ -440,7 +441,7 @@ func GetCPU() (*api.ResourcesCPU, error) { } } thread.ID = threadNumber - thread.Isolated = int64InSlice(threadNumber, isolated) + thread.Isolated = shared.ValueInSlice(threadNumber, isolated) thread.Thread = uint64(len(resCore.Threads)) // NUMA node diff --git a/lxd/resources/gpu.go b/lxd/resources/gpu.go index b91f3c70df39..59b9ff412cb8 100644 --- a/lxd/resources/gpu.go +++ b/lxd/resources/gpu.go @@ -14,6 +14,7 @@ import ( "github.com/jaypipes/pcidb" "golang.org/x/sys/unix" + "github.com/canonical/lxd/shared" "github.com/canonical/lxd/shared/api" ) @@ -477,7 +478,7 @@ func GetGPU() (*api.ResourcesGPU, error) { card.PCIAddress = pciAddr // Skip devices we already know about - if stringInSlice(card.PCIAddress, pciKnown) { + if shared.ValueInSlice(card.PCIAddress, pciKnown) { continue } @@ -525,7 +526,7 @@ func GetGPU() (*api.ResourcesGPU, error) { devicePath := filepath.Join(sysBusPci, entryName) // Skip devices we already know about - if stringInSlice(entryName, pciKnown) { + if shared.ValueInSlice(entryName, pciKnown) { continue } diff --git a/lxd/resources/network.go b/lxd/resources/network.go index 20983a395c5c..6a4cfa609607 100644 --- a/lxd/resources/network.go +++ b/lxd/resources/network.go @@ -12,6 +12,7 @@ import ( "github.com/jaypipes/pcidb" "golang.org/x/sys/unix" + "github.com/canonical/lxd/shared" "github.com/canonical/lxd/shared/api" ) @@ -354,7 +355,7 @@ func GetNetwork() (*api.ResourcesNetwork, error) { card.PCIAddress = pciAddr // Skip devices we already know about - if stringInSlice(card.PCIAddress, pciKnown) { + if shared.ValueInSlice(card.PCIAddress, pciKnown) { continue } @@ -402,7 +403,7 @@ func GetNetwork() (*api.ResourcesNetwork, error) { devicePath := filepath.Join(sysBusPci, entryName) // Skip devices we already know about - if stringInSlice(entryName, pciKnown) { + if shared.ValueInSlice(entryName, pciKnown) { continue } diff --git a/lxd/resources/utils.go b/lxd/resources/utils.go index 2c0f16f04027..5b3347b3fc6f 100644 --- a/lxd/resources/utils.go +++ b/lxd/resources/utils.go @@ -48,24 +48,6 @@ func readInt(path string) (int64, error) { return value, nil } -func stringInSlice(key string, list []string) bool { - for _, entry := range list { - if entry == key { - return true - } - } - return false -} - -func int64InSlice(key int64, list []int64) bool { - for _, entry := range list { - if entry == key { - return true - } - } - return false -} - func sysfsExists(path string) bool { _, err := os.Lstat(path) return err == nil diff --git a/lxd/rsync/rsync.go b/lxd/rsync/rsync.go index 488958fb7534..bfd320140862 100644 --- a/lxd/rsync/rsync.go +++ b/lxd/rsync/rsync.go @@ -414,18 +414,18 @@ func Recv(path string, conn io.ReadWriteCloser, tracker *ioprogress.ProgressTrac func rsyncFeatureArgs(features []string) []string { args := []string{} - if shared.StringInSlice("xattrs", features) { + if shared.ValueInSlice("xattrs", features) { args = append(args, "--xattrs") if AtLeast("3.1.3") { args = append(args, "--filter=-x security.selinux") } } - if shared.StringInSlice("delete", features) { + if shared.ValueInSlice("delete", features) { args = append(args, "--delete") } - if shared.StringInSlice("compress", features) { + if shared.ValueInSlice("compress", features) { args = append(args, "--compress") args = append(args, "--compress-level=2") } diff --git a/lxd/scriptlet/load/load.go b/lxd/scriptlet/load/load.go index 87fac433ff55..96083768ec3a 100644 --- a/lxd/scriptlet/load/load.go +++ b/lxd/scriptlet/load/load.go @@ -15,7 +15,7 @@ const nameInstancePlacement = "instance_placement" // InstancePlacementCompile compiles the instance placement scriptlet. func InstancePlacementCompile(src string) (*starlark.Program, error) { isPreDeclared := func(name string) bool { - return shared.StringInSlice(name, []string{ + return shared.ValueInSlice(name, []string{ "log_info", "log_warn", "log_error", diff --git a/lxd/storage.go b/lxd/storage.go index 5cdf1fde25ea..226b1ebfb1e3 100644 --- a/lxd/storage.go +++ b/lxd/storage.go @@ -178,7 +178,7 @@ func storagePoolDriversCacheUpdate(s *state.State) { Remote: entry.Remote, }) - if shared.StringInSlice(entry.Name, drivers) { + if shared.ValueInSlice(entry.Name, drivers) { usedDrivers[entry.Name] = entry.Version } } diff --git a/lxd/storage/backend_lxd.go b/lxd/storage/backend_lxd.go index 86e7a5f21ec7..14542a95ec7d 100644 --- a/lxd/storage/backend_lxd.go +++ b/lxd/storage/backend_lxd.go @@ -3095,7 +3095,7 @@ func (b *lxdBackend) RestoreInstanceSnapshot(inst instance.Instance, src instanc // Go through all the snapshots. for _, snap := range snaps { _, snapName, _ := api.GetParentAndSnapshotName(snap.Name()) - if !shared.StringInSlice(snapName, snapErr.Snapshots) { + if !shared.ValueInSlice(snapName, snapErr.Snapshots) { continue } @@ -6245,7 +6245,7 @@ func (b *lxdBackend) detectUnknownInstanceVolume(vol *drivers.Volume, projectVol fullSnapshotName := drivers.GetSnapshotVolumeName(instName, snapshot.Name) // Check if an entry for the instance already exists in the DB. - if shared.StringInSlice(fullSnapshotName, instSnapshots) { + if shared.ValueInSlice(fullSnapshotName, instSnapshots) { return fmt.Errorf("Instance %q snapshot %q in project %q already has instance DB record", instName, snapshot.Name, projectName) } diff --git a/lxd/storage/backend_lxd_patches.go b/lxd/storage/backend_lxd_patches.go index bf1613195109..d580247339a3 100644 --- a/lxd/storage/backend_lxd_patches.go +++ b/lxd/storage/backend_lxd_patches.go @@ -163,7 +163,7 @@ DELETE FROM storage_volumes WHERE id IN ( // the corresponding project name as a prefix. func patchBucketNames(b *lxdBackend) error { // Apply patch only for btrfs, dir, lvm, and zfs drivers. - if !shared.StringInSlice(b.driver.Info().Name, []string{"btrfs", "dir", "lvm", "zfs"}) { + if !shared.ValueInSlice(b.driver.Info().Name, []string{"btrfs", "dir", "lvm", "zfs"}) { return nil } diff --git a/lxd/storage/drivers/driver_btrfs_volumes.go b/lxd/storage/drivers/driver_btrfs_volumes.go index c9486e826c65..2888c76c3748 100644 --- a/lxd/storage/drivers/driver_btrfs_volumes.go +++ b/lxd/storage/drivers/driver_btrfs_volumes.go @@ -502,7 +502,7 @@ func (d *btrfs) CreateVolumeFromMigration(vol Volume, conn io.ReadWriteCloser, v var syncSubvolumes []BTRFSSubVolume // Inspect negotiated features to see if we are expecting to get a metadata migration header frame. - if shared.StringInSlice(migration.BTRFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) { + if shared.ValueInSlice(migration.BTRFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) { buf, err := io.ReadAll(conn) if err != nil { return fmt.Errorf("Failed reading BTRFS migration header: %w", err) @@ -531,7 +531,7 @@ func (d *btrfs) CreateVolumeFromMigration(vol Volume, conn io.ReadWriteCloser, v }) } - if volTargetArgs.Refresh && shared.StringInSlice(migration.BTRFSFeatureSubvolumeUUIDs, volTargetArgs.MigrationType.Features) { + if volTargetArgs.Refresh && shared.ValueInSlice(migration.BTRFSFeatureSubvolumeUUIDs, volTargetArgs.MigrationType.Features) { snapshots, err := d.volumeSnapshotsSorted(vol, op) if err != nil { return err @@ -1263,7 +1263,7 @@ func (d *btrfs) MigrateVolume(vol Volume, conn io.ReadWriteCloser, volSrcArgs *m // If we haven't negotiated subvolume support, check if we have any subvolumes in source and fail, // otherwise we would end up not materialising all of the source's files on the target. - if !shared.StringInSlice(migration.BTRFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) || !shared.StringInSlice(migration.BTRFSFeatureSubvolumes, volSrcArgs.MigrationType.Features) { + if !shared.ValueInSlice(migration.BTRFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) || !shared.ValueInSlice(migration.BTRFSFeatureSubvolumes, volSrcArgs.MigrationType.Features) { for _, subVol := range migrationHeader.Subvolumes { if subVol.Path != string(filepath.Separator) { return fmt.Errorf("Subvolumes detected in source but target does not support receiving subvolumes") @@ -1272,7 +1272,7 @@ func (d *btrfs) MigrateVolume(vol Volume, conn io.ReadWriteCloser, volSrcArgs *m } // Send metadata migration header frame with subvolume info if we have negotiated that feature. - if shared.StringInSlice(migration.BTRFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) { + if shared.ValueInSlice(migration.BTRFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) { headerJSON, err := json.Marshal(migrationHeader) if err != nil { return fmt.Errorf("Failed encoding BTRFS migration header: %w", err) @@ -1291,7 +1291,7 @@ func (d *btrfs) MigrateVolume(vol Volume, conn io.ReadWriteCloser, volSrcArgs *m d.logger.Debug("Sent migration meta data header", logger.Ctx{"name": vol.name}) } - if volSrcArgs.Refresh && shared.StringInSlice(migration.BTRFSFeatureSubvolumeUUIDs, volSrcArgs.MigrationType.Features) { + if volSrcArgs.Refresh && shared.ValueInSlice(migration.BTRFSFeatureSubvolumeUUIDs, volSrcArgs.MigrationType.Features) { migrationHeader = &BTRFSMetaDataHeader{} buf, err := io.ReadAll(conn) @@ -1344,7 +1344,7 @@ func (d *btrfs) migrateVolumeOptimized(vol Volume, conn io.ReadWriteCloser, volS continue // Only sending subvolumes related to snapshot name (empty for main vol). } - if subVolume.Path != string(filepath.Separator) && !shared.StringInSlice(migration.BTRFSFeatureSubvolumes, volSrcArgs.MigrationType.Features) { + if subVolume.Path != string(filepath.Separator) && !shared.ValueInSlice(migration.BTRFSFeatureSubvolumes, volSrcArgs.MigrationType.Features) { continue // Skip sending subvolumes of volume if subvolumes feature not negotiated. } diff --git a/lxd/storage/drivers/driver_ceph_utils.go b/lxd/storage/drivers/driver_ceph_utils.go index 69f2ebbd0d10..22a7d40309a7 100644 --- a/lxd/storage/drivers/driver_ceph_utils.go +++ b/lxd/storage/drivers/driver_ceph_utils.go @@ -1064,7 +1064,7 @@ func (d *ceph) getRBDMappedDevPath(vol Volume, mapIfMissing bool) (bool, string, if len(rbdNameParts) == 2 && rbdNameParts[1] == devSnapName { return false, fmt.Sprintf("/dev/rbd%d", idx), nil // We found a match. } - } else if shared.StringInSlice(devSnapName, []string{"-", ""}) { + } else if shared.ValueInSlice(devSnapName, []string{"-", ""}) { // Volume is not a snapshot and neither is this device. return false, fmt.Sprintf("/dev/rbd%d", idx), nil // We found a match. } diff --git a/lxd/storage/drivers/driver_common.go b/lxd/storage/drivers/driver_common.go index cffdc505ccbd..2968bd91895d 100644 --- a/lxd/storage/drivers/driver_common.go +++ b/lxd/storage/drivers/driver_common.go @@ -494,7 +494,7 @@ func (d *common) ValidateBucketKey(keyName string, creds S3Credentials, roleName } validRoles := []string{"admin", "read-only"} - if !shared.StringInSlice(roleName, validRoles) { + if !shared.ValueInSlice(roleName, validRoles) { return fmt.Errorf("Invalid key role") } diff --git a/lxd/storage/drivers/driver_lvm.go b/lxd/storage/drivers/driver_lvm.go index 7d013015f9eb..bf87d2755e80 100644 --- a/lxd/storage/drivers/driver_lvm.go +++ b/lxd/storage/drivers/driver_lvm.go @@ -312,7 +312,7 @@ func (d *lvm) Create() error { } // Check the tags on the volume group to check it is not already being used by LXD. - if shared.StringInSlice(lvmVgPoolMarker, vgTags) { + if shared.ValueInSlice(lvmVgPoolMarker, vgTags) { return fmt.Errorf("Volume group %q is already used by LXD", d.config["lvm.vg_name"]) } } @@ -458,7 +458,7 @@ func (d *lvm) Delete(op *operations.Operation) error { d.logger.Debug("Volume group removed", logger.Ctx{"vg_name": d.config["lvm.vg_name"]}) } else { // Otherwise just remove the lvmVgPoolMarker tag to indicate LXD no longer uses this VG. - if shared.StringInSlice(lvmVgPoolMarker, vgTags) { + if shared.ValueInSlice(lvmVgPoolMarker, vgTags) { _, err = shared.TryRunCommand("vgchange", "--deltag", lvmVgPoolMarker, d.config["lvm.vg_name"]) if err != nil { return fmt.Errorf("Failed to remove marker tag on volume group for the lvm storage pool: %w", err) diff --git a/lxd/storage/drivers/driver_zfs.go b/lxd/storage/drivers/driver_zfs.go index 64f9be811de5..6b1a2b491362 100644 --- a/lxd/storage/drivers/driver_zfs.go +++ b/lxd/storage/drivers/driver_zfs.go @@ -153,7 +153,7 @@ func (d zfs) ensureInitialDatasets(warnOnExistingPolicyApplyError bool) error { for _, dataset := range d.initialDatasets() { properties := []string{"mountpoint=legacy"} - if shared.StringInSlice(dataset, []string{"virtual-machines", "deleted/virtual-machines"}) { + if shared.ValueInSlice(dataset, []string{"virtual-machines", "deleted/virtual-machines"}) { properties = append(properties, "volmode=none") } @@ -386,7 +386,7 @@ func (d *zfs) Delete(op *operations.Operation) error { for _, dataset := range datasets { dataset = strings.TrimPrefix(dataset, "/") - if shared.StringInSlice(dataset, initialDatasets) { + if shared.ValueInSlice(dataset, initialDatasets) { continue } diff --git a/lxd/storage/drivers/driver_zfs_utils.go b/lxd/storage/drivers/driver_zfs_utils.go index 585202b082b0..134741c8213d 100644 --- a/lxd/storage/drivers/driver_zfs_utils.go +++ b/lxd/storage/drivers/driver_zfs_utils.go @@ -338,7 +338,7 @@ func (d *zfs) sendDataset(dataset string, parent string, volSrcArgs *migration.V } } - if shared.StringInSlice("compress", volSrcArgs.MigrationType.Features) { + if shared.ValueInSlice("compress", volSrcArgs.MigrationType.Features) { args = append(args, "-c") args = append(args, "-L") } diff --git a/lxd/storage/drivers/driver_zfs_volumes.go b/lxd/storage/drivers/driver_zfs_volumes.go index 378c2b048edd..d993fc20f4d7 100644 --- a/lxd/storage/drivers/driver_zfs_volumes.go +++ b/lxd/storage/drivers/driver_zfs_volumes.go @@ -780,7 +780,7 @@ func (d *zfs) CreateVolumeFromCopy(vol Volume, srcVol Volume, copySnapshots bool // Check if expected snapshot. if strings.Contains(entry, "@snapshot-") { name := strings.Split(entry, "@snapshot-")[1] - if shared.StringInSlice(name, snapshots) { + if shared.ValueInSlice(name, snapshots) { continue } } @@ -889,7 +889,7 @@ func (d *zfs) CreateVolumeFromMigration(vol Volume, conn io.ReadWriteCloser, vol // 2) Snapshots shouldn't be copied (--instance-only flag) volumeOnly := len(volTargetArgs.Snapshots) == 0 - if shared.StringInSlice(migration.ZFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) { + if shared.ValueInSlice(migration.ZFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) { // The source will send all of its snapshots with their respective GUID. buf, err := io.ReadAll(conn) if err != nil { @@ -903,7 +903,7 @@ func (d *zfs) CreateVolumeFromMigration(vol Volume, conn io.ReadWriteCloser, vol } // If we're refreshing, send back all snapshots of the target. - if volTargetArgs.Refresh && shared.StringInSlice(migration.ZFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) { + if volTargetArgs.Refresh && shared.ValueInSlice(migration.ZFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) { snapshots, err := vol.Snapshots(op) if err != nil { return fmt.Errorf("Failed getting volume snapshots: %w", err) @@ -2383,7 +2383,7 @@ func (d *zfs) MigrateVolume(vol Volume, conn io.ReadWriteCloser, volSrcArgs *mig var srcMigrationHeader *ZFSMetaDataHeader // The target will validate the GUIDs and if successful proceed with the refresh. - if shared.StringInSlice(migration.ZFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) { + if shared.ValueInSlice(migration.ZFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) { snapshots, err := d.VolumeSnapshots(vol, op) if err != nil { return err @@ -2413,14 +2413,14 @@ func (d *zfs) MigrateVolume(vol Volume, conn io.ReadWriteCloser, volSrcArgs *mig } // If we haven't negotiated zvol support, ensure volume is not a zvol. - if !shared.StringInSlice(migration.ZFSFeatureZvolFilesystems, volSrcArgs.MigrationType.Features) && d.isBlockBacked(vol) { + if !shared.ValueInSlice(migration.ZFSFeatureZvolFilesystems, volSrcArgs.MigrationType.Features) && d.isBlockBacked(vol) { return fmt.Errorf("Filesystem zvol detected in source but target does not support receiving zvols") } incrementalStream := true var migrationHeader ZFSMetaDataHeader - if volSrcArgs.Refresh && shared.StringInSlice(migration.ZFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) { + if volSrcArgs.Refresh && shared.ValueInSlice(migration.ZFSFeatureMigrationHeader, volSrcArgs.MigrationType.Features) { buf, err := io.ReadAll(conn) if err != nil { return fmt.Errorf("Failed reading ZFS migration header: %w", err) diff --git a/lxd/storage/drivers/utils.go b/lxd/storage/drivers/utils.go index 273f32216b4f..564a85244e8d 100644 --- a/lxd/storage/drivers/utils.go +++ b/lxd/storage/drivers/utils.go @@ -420,7 +420,7 @@ func filesystemTypeCanBeShrunk(fsType string) bool { fsType = DefaultFilesystem } - if shared.StringInSlice(fsType, []string{"ext4", "btrfs"}) { + if shared.ValueInSlice(fsType, []string{"ext4", "btrfs"}) { return true } diff --git a/lxd/storage/drivers/volume.go b/lxd/storage/drivers/volume.go index 5535214de798..4cadcd454457 100644 --- a/lxd/storage/drivers/volume.go +++ b/lxd/storage/drivers/volume.go @@ -360,13 +360,13 @@ func (v Volume) SnapshotsMatch(snapNames []string, op *operations.Operation) err } for _, snapName := range snapNames { - if !shared.StringInSlice(snapName, snapshots) { + if !shared.ValueInSlice(snapName, snapshots) { return fmt.Errorf("Snapshot %q expected but not in storage", snapName) } } for _, snapshot := range snapshots { - if !shared.StringInSlice(snapshot, snapNames) { + if !shared.ValueInSlice(snapshot, snapNames) { return fmt.Errorf("Snapshot %q in storage but not expected", snapshot) } } diff --git a/lxd/storage/storage.go b/lxd/storage/storage.go index 64de9a316c16..1070a7fae287 100644 --- a/lxd/storage/storage.go +++ b/lxd/storage/storage.go @@ -143,7 +143,7 @@ func UsedBy(ctx context.Context, s *state.State, pool Pool, firstOnly bool, memb for _, vol := range volumes { var u *api.URL - if shared.StringInSlice(vol.Type, ignoreVolumeType) { + if shared.ValueInSlice(vol.Type, ignoreVolumeType) { continue } diff --git a/lxd/storage/utils.go b/lxd/storage/utils.go index 9a5a66f9c29a..c27e0dc8088c 100644 --- a/lxd/storage/utils.go +++ b/lxd/storage/utils.go @@ -44,7 +44,7 @@ func ConfigDiff(oldConfig map[string]string, newConfig map[string]string) ([]str userOnly = false } - if !shared.StringInSlice(key, changedConfig) { + if !shared.ValueInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } @@ -56,7 +56,7 @@ func ConfigDiff(oldConfig map[string]string, newConfig map[string]string) ([]str userOnly = false } - if !shared.StringInSlice(key, changedConfig) { + if !shared.ValueInSlice(key, changedConfig) { changedConfig = append(changedConfig, key) } } diff --git a/lxd/storage_pools.go b/lxd/storage_pools.go index ecec42a766d5..a39755e47fd0 100644 --- a/lxd/storage_pools.go +++ b/lxd/storage_pools.go @@ -307,7 +307,7 @@ func storagePoolsPost(d *Daemon, r *http.Request) response.Response { // A targetNode was specified, let's just define the node's storage without actually creating it. // The only legal key values for the storage config are the ones in NodeSpecificStorageConfig. for key := range req.Config { - if !shared.StringInSlice(key, db.NodeSpecificStorageConfig) { + if !shared.ValueInSlice(key, db.NodeSpecificStorageConfig) { return response.SmartError(fmt.Errorf("Config key %q may not be used as member-specific key", key)) } } @@ -375,7 +375,7 @@ func storagePoolPartiallyCreated(pool *api.StoragePool) bool { // If the pool has global config keys, then it has previously been created by having its global config // inserted, and this means it is partialled created. for key := range pool.Config { - if !shared.StringInSlice(key, db.NodeSpecificStorageConfig) { + if !shared.ValueInSlice(key, db.NodeSpecificStorageConfig) { return true } } @@ -388,7 +388,7 @@ func storagePoolPartiallyCreated(pool *api.StoragePool) bool { func storagePoolsPostCluster(s *state.State, pool *api.StoragePool, req api.StoragePoolsPost, clientType clusterRequest.ClientType) error { // Check that no node-specific config key has been defined. for key := range req.Config { - if shared.StringInSlice(key, db.NodeSpecificStorageConfig) { + if shared.ValueInSlice(key, db.NodeSpecificStorageConfig) { return fmt.Errorf("Config key %q is cluster member specific", key) } } @@ -731,7 +731,7 @@ func storagePoolPut(d *Daemon, r *http.Request) response.Response { if targetNode == "" { // If no target is specified, then ensure only non-node-specific config keys are changed. for k := range req.Config { - if shared.StringInSlice(k, db.NodeSpecificStorageConfig) { + if shared.ValueInSlice(k, db.NodeSpecificStorageConfig) { return response.BadRequest(fmt.Errorf("Config key %q is cluster member specific", k)) } } @@ -740,7 +740,7 @@ func storagePoolPut(d *Daemon, r *http.Request) response.Response { // If a target is specified, then ensure only node-specific config keys are changed. for k, v := range req.Config { - if !shared.StringInSlice(k, db.NodeSpecificStorageConfig) && curConfig[k] != v { + if !shared.ValueInSlice(k, db.NodeSpecificStorageConfig) && curConfig[k] != v { return response.BadRequest(fmt.Errorf("Config key %q may not be used as cluster member specific key", k)) } } @@ -820,7 +820,7 @@ func doStoragePoolUpdate(s *state.State, pool storagePools.Pool, req api.Storage // node-specific network config with the submitted config to allow validation. // This allows removal of non-node specific keys when they are absent from request config. for k, v := range pool.Driver().Config() { - if shared.StringInSlice(k, db.NodeSpecificStorageConfig) { + if shared.ValueInSlice(k, db.NodeSpecificStorageConfig) { req.Config[k] = v } } @@ -852,7 +852,7 @@ func doStoragePoolUpdate(s *state.State, pool storagePools.Pool, req api.Storage sendPool.Config = make(map[string]string) for k, v := range req.Config { // Don't forward node specific keys (these will be merged in on recipient node). - if shared.StringInSlice(k, db.NodeSpecificStorageConfig) { + if shared.ValueInSlice(k, db.NodeSpecificStorageConfig) { continue } diff --git a/lxd/storage_volumes.go b/lxd/storage_volumes.go index bd15dc07edb9..029d05233d91 100644 --- a/lxd/storage_volumes.go +++ b/lxd/storage_volumes.go @@ -468,7 +468,7 @@ func filterVolumes(volumes []*db.StorageVolume, clauses *filter.ClauseSet, allPr filtered := []*db.StorageVolume{} for _, volume := range volumes { // Filter out image volumes that are not used by this project. - if volume.Type == db.StoragePoolVolumeTypeNameImage && !allProjects && !shared.StringInSlice(volume.Name, filterProjectImages) { + if volume.Type == db.StoragePoolVolumeTypeNameImage && !allProjects && !shared.ValueInSlice(volume.Name, filterProjectImages) { continue } @@ -1357,7 +1357,7 @@ func storagePoolVolumeGet(d *Daemon, r *http.Request) response.Response { } // Check that the storage volume type is valid. - if !shared.IntInSlice(volumeType, supportedVolumeTypes) { + if !shared.ValueInSlice(volumeType, supportedVolumeTypes) { return response.BadRequest(fmt.Errorf("Invalid storage volume type %q", volumeTypeName)) } @@ -1477,7 +1477,7 @@ func storagePoolVolumePut(d *Daemon, r *http.Request) response.Response { } // Check that the storage volume type is valid. - if !shared.IntInSlice(volumeType, supportedVolumeTypes) { + if !shared.ValueInSlice(volumeType, supportedVolumeTypes) { return response.BadRequest(fmt.Errorf("Invalid storage volume type %q", volumeTypeName)) } @@ -1784,7 +1784,7 @@ func storagePoolVolumeDelete(d *Daemon, r *http.Request) response.Response { } // Check that the storage volume type is valid. - if !shared.IntInSlice(volumeType, supportedVolumeTypes) { + if !shared.ValueInSlice(volumeType, supportedVolumeTypes) { return response.BadRequest(fmt.Errorf("Invalid storage volume type %q", volumeTypeName)) } diff --git a/lxd/storage_volumes_snapshot.go b/lxd/storage_volumes_snapshot.go index 31ddd990a363..71b0c5f3d65b 100644 --- a/lxd/storage_volumes_snapshot.go +++ b/lxd/storage_volumes_snapshot.go @@ -373,7 +373,7 @@ func storagePoolVolumeSnapshotsTypeGet(d *Daemon, r *http.Request) response.Resp } // Check that the storage volume type is valid. - if !shared.IntInSlice(volumeType, supportedVolumeTypes) { + if !shared.ValueInSlice(volumeType, supportedVolumeTypes) { return response.BadRequest(fmt.Errorf("Invalid storage volume type %q", volumeTypeName)) } diff --git a/lxd/storage_volumes_state.go b/lxd/storage_volumes_state.go index 0be2d265ed6b..18540a728a16 100644 --- a/lxd/storage_volumes_state.go +++ b/lxd/storage_volumes_state.go @@ -96,7 +96,7 @@ func storagePoolVolumeTypeStateGet(d *Daemon, r *http.Request) response.Response } // Check that the storage volume type is valid. - if !shared.IntInSlice(volumeType, []int{db.StoragePoolVolumeTypeCustom, db.StoragePoolVolumeTypeContainer, db.StoragePoolVolumeTypeVM}) { + if !shared.ValueInSlice(volumeType, []int{db.StoragePoolVolumeTypeCustom, db.StoragePoolVolumeTypeContainer, db.StoragePoolVolumeTypeVM}) { return response.BadRequest(fmt.Errorf("Invalid storage volume type %q", volumeTypeName)) } diff --git a/lxd/storage_volumes_utils.go b/lxd/storage_volumes_utils.go index 0b3d501ea08c..5b234269c0c8 100644 --- a/lxd/storage_volumes_utils.go +++ b/lxd/storage_volumes_utils.go @@ -58,7 +58,7 @@ func storagePoolVolumeUpdateUsers(s *state.State, projectName string, oldPoolNam // Update all profiles that are using the volume with a device. err = storagePools.VolumeUsedByProfileDevices(s, oldPoolName, projectName, oldVol, func(profileID int64, profile api.Profile, p api.Project, usedByDevices []string) error { for name, dev := range profile.Devices { - if shared.StringInSlice(name, usedByDevices) { + if shared.ValueInSlice(name, usedByDevices) { dev["pool"] = newPoolName dev["source"] = newVol.Name } diff --git a/lxd/util/config.go b/lxd/util/config.go index 076a017c6e70..4d5720c9f1a9 100644 --- a/lxd/util/config.go +++ b/lxd/util/config.go @@ -16,7 +16,7 @@ func CompareConfigs(config1, config2 map[string]string, exclude []string) error delta := []string{} for key, value := range config1 { - if shared.StringInSlice(key, exclude) { + if shared.ValueInSlice(key, exclude) { continue } @@ -25,7 +25,7 @@ func CompareConfigs(config1, config2 map[string]string, exclude []string) error } } for key, value := range config2 { - if shared.StringInSlice(key, exclude) { + if shared.ValueInSlice(key, exclude) { continue } diff --git a/lxd/util/kernel.go b/lxd/util/kernel.go index f33cf4839713..c2329dd6c380 100644 --- a/lxd/util/kernel.go +++ b/lxd/util/kernel.go @@ -73,7 +73,7 @@ func HugepagesPath() (string, error) { } if len(matches) > 1 { - if shared.StringInSlice("/dev/hugepages", matches) { + if shared.ValueInSlice("/dev/hugepages", matches) { return "/dev/hugepages", nil } diff --git a/shared/cmd/ask.go b/shared/cmd/ask.go index be6a69d3d265..ddeb890295f9 100644 --- a/shared/cmd/ask.go +++ b/shared/cmd/ask.go @@ -29,9 +29,9 @@ func (a *Asker) AskBool(question string, defaultAnswer string) (bool, error) { return false, err } - if shared.StringInSlice(strings.ToLower(answer), []string{"yes", "y"}) { + if shared.ValueInSlice(strings.ToLower(answer), []string{"yes", "y"}) { return true, nil - } else if shared.StringInSlice(strings.ToLower(answer), []string{"no", "n"}) { + } else if shared.ValueInSlice(strings.ToLower(answer), []string{"no", "n"}) { return false, nil } @@ -47,7 +47,7 @@ func (a *Asker) AskChoice(question string, choices []string, defaultAnswer strin return "", err } - if shared.StringInSlice(answer, choices) { + if shared.ValueInSlice(answer, choices) { return answer, nil } diff --git a/shared/filter/clause.go b/shared/filter/clause.go index bd79a6d360b4..a20dff5bc466 100644 --- a/shared/filter/clause.go +++ b/shared/filter/clause.go @@ -100,7 +100,7 @@ func Parse(s string, op OperatorSet) (*ClauseSet, error) { clause.PrevLogical = prevLogical if index < len(parts) { prevLogical = parts[index] - if !shared.StringInSlice(prevLogical, []string{op.And, op.Or}) { + if !shared.ValueInSlice(prevLogical, []string{op.And, op.Or}) { return nil, fmt.Errorf("invalid clause composition") } diff --git a/shared/idmap/idmapset_linux.go b/shared/idmap/idmapset_linux.go index bb92cc06812c..6e8c2aa06b62 100644 --- a/shared/idmap/idmapset_linux.go +++ b/shared/idmap/idmapset_linux.go @@ -473,7 +473,7 @@ func (m IdmapSet) ToLxcString() []string { var lines []string for _, e := range m.Idmap { for _, l := range e.ToLxcString() { - if !shared.StringInSlice(l, lines) { + if !shared.ValueInSlice(l, lines) { lines = append(lines, l) } } diff --git a/shared/simplestreams/products.go b/shared/simplestreams/products.go index a07e4d5b1b5b..4cc474cb6c51 100644 --- a/shared/simplestreams/products.go +++ b/shared/simplestreams/products.go @@ -100,7 +100,7 @@ func (s *Products) ToLXD() ([]api.Image, map[string][][]string) { addImage := func(meta *ProductVersionItem, root *ProductVersionItem) error { // Look for deltas deltas := []ProductVersionItem{} - if root != nil && shared.StringInSlice(root.FileType, []string{"squashfs", "disk-kvm.img"}) { + if root != nil && shared.ValueInSlice(root.FileType, []string{"squashfs", "disk-kvm.img"}) { for _, item := range version.Items { if item.FileType == fmt.Sprintf("%s.vcdiff", root.FileType) { deltas = append(deltas, item) @@ -244,7 +244,7 @@ func (s *Products) ToLXD() ([]api.Image, map[string][][]string) { // Locate source image fingerprint var srcFingerprint string for _, item := range srcImage.Items { - if !shared.StringInSlice(item.FileType, lxdCompatItems) { + if !shared.ValueInSlice(item.FileType, lxdCompatItems) { continue } @@ -274,17 +274,17 @@ func (s *Products) ToLXD() ([]api.Image, map[string][][]string) { // Locate a valid LXD image for _, item := range version.Items { - if shared.StringInSlice(item.FileType, lxdCompatCombinedItems) { + if shared.ValueInSlice(item.FileType, lxdCompatCombinedItems) { err := addImage(&item, nil) if err != nil { continue } break // Stop at first compatible item found. - } else if shared.StringInSlice(item.FileType, lxdCompatItems) { + } else if shared.ValueInSlice(item.FileType, lxdCompatItems) { // Locate the root files for _, subItem := range version.Items { - if shared.StringInSlice(subItem.FileType, []string{"disk1.img", "disk-kvm.img", "uefi1.img", "root.tar.xz", "squashfs"}) { + if shared.ValueInSlice(subItem.FileType, []string{"disk1.img", "disk-kvm.img", "uefi1.img", "root.tar.xz", "squashfs"}) { err := addImage(&item, &subItem) if err != nil { continue diff --git a/shared/util.go b/shared/util.go index 43213c33311a..ce2394e22efb 100644 --- a/shared/util.go +++ b/shared/util.go @@ -625,12 +625,14 @@ func HasKey[K comparable, V any](key K, m map[K]V) bool { return found } -func StringInSlice(key string, list []string) bool { +// ValueInSlice returns true if key is in list. +func ValueInSlice[T comparable](key T, list []T) bool { for _, entry := range list { if entry == key { return true } } + return false } @@ -645,9 +647,9 @@ func StringPrefixInSlice(key string, list []string) bool { return false } -// RemoveElementsFromStringSlice returns a slice equivalent to removing the given elements from the given list. +// RemoveElementsFromSlice returns a slice equivalent to removing the given elements from the given list. // Elements not present in the list are ignored. -func RemoveElementsFromStringSlice(list []string, elements ...string) []string { +func RemoveElementsFromSlice[T comparable](list []T, elements ...T) []T { for i := len(elements) - 1; i >= 0; i-- { element := elements[i] match := false @@ -677,36 +679,9 @@ func StringHasPrefix(value string, prefixes ...string) bool { return false } -func IntInSlice(key int, list []int) bool { - for _, entry := range list { - if entry == key { - return true - } - } - return false -} - -func Int64InSlice(key int64, list []int64) bool { - for _, entry := range list { - if entry == key { - return true - } - } - return false -} - -func Uint64InSlice(key uint64, list []uint64) bool { - for _, entry := range list { - if entry == key { - return true - } - } - return false -} - // IsTrue returns true if value is "true", "1", "yes" or "on" (case insensitive). func IsTrue(value string) bool { - return StringInSlice(strings.ToLower(value), []string{"true", "1", "yes", "on"}) + return ValueInSlice(strings.ToLower(value), []string{"true", "1", "yes", "on"}) } // IsTrueOrEmpty returns true if value is empty or if IsTrue() returns true. @@ -716,7 +691,7 @@ func IsTrueOrEmpty(value string) bool { // IsFalse returns true if value is "false", "0", "no" or "off" (case insensitive). func IsFalse(value string) bool { - return StringInSlice(strings.ToLower(value), []string{"false", "0", "no", "off"}) + return ValueInSlice(strings.ToLower(value), []string{"false", "0", "no", "off"}) } // IsFalseOrEmpty returns true if value is empty or if IsFalse() returns true. diff --git a/shared/util_test.go b/shared/util_test.go index 989b64a49303..2c9b177c7e7e 100644 --- a/shared/util_test.go +++ b/shared/util_test.go @@ -250,7 +250,7 @@ func TestRemoveElementsFromStringSlice(t *testing.T) { } for _, tt := range tests { - gotList := RemoveElementsFromStringSlice(tt.list, tt.elementsToRemove...) + gotList := RemoveElementsFromSlice(tt.list, tt.elementsToRemove...) assert.ElementsMatch(t, tt.expectedList, gotList) } }