utils

package
v0.0.0-...-6243be3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 20, 2025 License: Apache-2.0 Imports: 50 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InventoryDatabase     = "postgres"
	InventoryResource     = "resource"
	InventoryAlarms       = "alarms"
	InventoryCluster      = "cluster"
	InventoryArtifacts    = "artifacts"
	InventoryProvisioning = "provisioning"
)

Base resource names

View Source
const (
	InventoryDatabaseServerName     = InventoryDatabase + serverSuffix
	InventoryResourceServerName     = InventoryResource + serverSuffix
	InventoryAlarmServerName        = InventoryAlarms + serverSuffix
	InventoryClusterServerName      = InventoryCluster + serverSuffix
	InventoryArtifactsServerName    = InventoryArtifacts + serverSuffix
	InventoryProvisioningServerName = InventoryProvisioning + serverSuffix
)

Deployment names

View Source
const (
	UPDATE = "Update"
	PATCH  = "Patch"
)

Resource operations

View Source
const (
	DefaultInventoryCR      = "default"
	DefaultNamespace        = "oran-o2ims"
	DefaultNamespaceEnvName = "OCLOUD_MANAGER_NAMESPACE"
	ImagePullPolicyEnvName  = "IMAGE_PULL_POLICY"
)

Defines information related to the operator instance in a namespace

View Source
const (
	SearchApiLabelKey   = "search-monitor"
	SearchApiLabelValue = "search-api"
)

Search API attributes

View Source
const (
	DefaultBackendTokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token" // nolint: gosec // hardcoded path only

	DefaultServiceCAFile = "/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt" // nolint: gosec // hardcoded path only
)

Default values for backend URL and token:

View Source
const (
	DefaultHardwareProvisioningTimeout = 90 * time.Minute
	DefaultClusterInstallationTimeout  = 90 * time.Minute
	DefaultClusterConfigurationTimeout = 30 * time.Minute
)

Default timeout values

View Source
const (
	HardwareProvisioningTimeoutConfigKey = "hardwareProvisioningTimeout"
	ClusterInstallationTimeoutConfigKey  = "clusterInstallationTimeout"
	ClusterConfigurationTimeoutConfigKey = "clusterConfigurationTimeout"
)

These are optional keys in the respective ConfigMaps defined in ClusterTemplate spec.templates, used to configure the timeout values for each operation. If not specified, the default timeout values will be applied.

View Source
const (
	TemplateParamNodeClusterName = "nodeClusterName"
	TemplateParamOCloudSiteId    = "oCloudSiteId"
	TemplateParamClusterInstance = "clusterInstanceParameters"
	TemplateParamPolicyConfig    = "policyTemplateParameters"
)

Required template schema parameters

View Source
const (
	ClusterInstanceTemplateName                 = "ClusterInstance"
	ClusterInstanceTemplatePath                 = "controllers/clusterinstance-template.yaml"
	ClusterInstanceTemplateDefaultsConfigmapKey = "clusterinstance-defaults"
)

ClusterInstance template constants

View Source
const (
	PolicyTemplateDefaultsConfigmapKey = "policytemplate-defaults"
	ClusterVersionLabelKey             = "cluster-version"
)

PolicyTemplate constants

View Source
const (
	ClusterZtpDone    = "ZTP Done"
	ClusterZtpNotDone = "ZTP Not Done"
)

Cluster status

View Source
const (
	HwTemplatePluginMgr      = "hwMgrId"
	HwTemplateNodePool       = "node-pools-data"
	HwTemplateBootIfaceLabel = "bootInterfaceLabel"
	HwTemplateExtensions     = "extensions"
)

Hardeware template constants

View Source
const (
	OperationTypeCreated = "created"
	OperationTypeUpdated = "updated"
	OperationTypeDryRun  = "validated with dry-run"
)
View Source
const (
	TLSSkipVerifyEnvName      = "INSECURE_SKIP_VERIFY"
	TLSSkipVerifyDefaultValue = false
)

Environment variable names

View Source
const (
	ChildPolicyRootPolicyLabel       = "policy.open-cluster-management.io/root-policy"
	ChildPolicyClusterNameLabel      = "policy.open-cluster-management.io/cluster-name"
	ChildPolicyClusterNamespaceLabel = "policy.open-cluster-management.io/cluster-namespace"
)

Label specific to ACM child policies.

View Source
const (
	UnitTestHwmgrID        = "hwmgr"
	UnitTestHwmgrNamespace = "hwmgr"
	DefaultPluginNamespace = "oran-hwmgr-plugin"
)

Hardware Manager plugin constants

View Source
const (
	MigrationContainerName    = "migration"
	RbacContainerName         = "rbac"
	ServerContainerName       = "server"
	InternalRbacContainerName = "internal-rbac"
)

POD Container Names

View Source
const (
	DefaultServicePort       = 8000
	DefaultServiceTargetPort = "https"
	DefaultContainerPort     = 8000
	DefaultProxyPort         = 8443

	InternalServicePort       = 9000
	InternalServiceTargetPort = "internal-https"
	InternalProxyPort         = 6443

	DatabaseServicePort = 5432
	DatabaseTargetPort  = "database"
)

POD Port Values

View Source
const (
	ServerImageName           = "IMAGE"
	KubeRbacProxyImageName    = "KUBE_RBAC_PROXY_IMAGE"
	PostgresImageName         = "POSTGRES_IMAGE"
	HwMgrPluginNameSpace      = "HWMGR_PLUGIN_NAMESPACE"
	InternalServicePortName   = "INTERNAL_SERVICE_PORT"
	RegisterOnRestartsEnvName = "REGISTER_ON_RESTART"
)

Environment values

View Source
const (
	AdminPasswordEnvName     = "POSTGRESQL_ADMIN_PASSWORD"     // nolint: gosec
	AlarmsPasswordEnvName    = "ORAN_O2IMS_ALARMS_PASSWORD"    // nolint: gosec
	ResourcesPasswordEnvName = "ORAN_O2IMS_RESOURCES_PASSWORD" // nolint: gosec
	ClustersPasswordEnvName  = "ORAN_O2IMS_CLUSTERS_PASSWORD"  // nolint: gosec

	DatabaseHostnameEnvVar = "POSTGRES_HOSTNAME"
)

Postgres values

View Source
const (
	ClusterModelExtension             = "model"
	ClusterVersionExtension           = "version"
	ClusterVendorExtension            = "vendor"
	ClusterAlarmDictionaryIDExtension = "alarmDictionaryID"

	ClusterModelHubCluster     = "hub-cluster"
	ClusterModelManagedCluster = "managed-cluster"

	OpenshiftVersionLabelName = "openshiftVersion"
	ClusterIDLabelName        = "clusterID"
	LocalClusterLabelName     = "local-cluster"

	ClusterTemplateArtifactsLabel = "clustertemplates.o2ims.provisioning.oran.org/templateId"
	HardwareManagerIdLabel        = "hardwaremanagers.hwmgr-plugin.oran.openshift.io/hwMgrId"
	HardwareManagerNodeIdLabel    = "hardwaremanagers.hwmgr-plugin.oran.openshift.io/hwMgrNodeId"
)

NodeCluster/ClusterResource extensions

View Source
const (
	AlertmanagerObjectName = "alertmanager"
	AlertmanagerNamespace  = "open-cluster-management-observability"
	AlertmanagerSA         = "alertmanager"
)

Alertmanager values

View Source
const (
	TLSClientMountPath = "/secrets/smo/tls"
	CABundleMountPath  = "/secrets/smo/certs"
	CABundleFilename   = "ca-bundle.crt"
)

SMO TLS Mount Paths

View Source
const (
	OAuthClientIDEnvName     = "SMO_OAUTH_CLIENT_ID"
	OAuthClientSecretEnvName = "SMO_OAUTH_CLIENT_SECRET" // nolint: gosec
)

SMO OAuth specific environment variables. These values are stored in environment variables to avoid them being visible in the command line arguments.

View Source
const AlarmDefinitionSeverityField = "severity"

AlarmDefinitionSeverityField severity field within additional fields of alarm definition

View Source
const ClusterInstanceParamsSubSchemaForNoHWTemplate = `` /* 871-byte string literal not displayed */

ClusterInstanceParamsSubSchemaForNoHWTemplate is the expected subschema for the ClusterInstanceParams when no hardware template is provided.

View Source
const ClusterVersionName = "version"

ClusterVersionName is the name given to the default ClusterVersion object

View Source
const DefaultAppName = "o2ims"

DefaultAppName defines the name prepended to the ingress host to form our FQDN hostname.

View Source
const DefaultOCloudID = "undefined"

DefaultOCloudID defines the default Global O-Cloud ID to be used until the end user configures this value.

View Source
const IngressClassName = "openshift-default"

IngressClassName defines the ingress controller class to be used

View Source
const IngressName = "oran-o2ims-ingress"

IngressName defines the name of our ingress controller

View Source
const IngressPortName = "api"

IngressPortName defines the name of service port to which our ingress controller directs traffic to

View Source
const (
	InventoryNamespace = "oran-o2ims"
)

Default namespace

View Source
const MinimumProxyLogLevel = 10

MinimumProxyLogLevel defines the minimum log-level set on the proxies

View Source
const MinimumProxyTLSVersion = "VersionTLS12"

MinimumProxyTLSVersion defines the minimum value we accept for incoming TLS connections to the proxies

View Source
const (
	PropertiesString = "properties"
)
View Source
const (
	UpgradeDefaultsConfigmapKey = "ibgu"
)

Upgrade constants

Variables

View Source
var (
	AlarmServerArgs = []string{
		"alarms-server",
		"serve",
		"--api-listener-address=127.0.0.1:8000",
	}

	ArtifactsServerArgs = []string{
		"artifacts-server",
		"serve",
		"--api-listener-address=127.0.0.1:8000",
	}

	ResourceServerArgs = []string{
		"resource-server",
		"serve",
		"--api-listener-address=127.0.0.1:8000",
	}

	ClusterServerArgs = []string{
		"cluster-server",
		"serve",
		"--api-listener-address=127.0.0.1:8000",
	}

	ProvisioningServerArgs = []string{
		"provisioning-server",
		"serve",
		"--api-listener-address=127.0.0.1:8000",
	}
)

Container arguments

View Source
var (
	// AllowedClusterInstanceFields contains path patterns for fields that are allowed to be updated.
	// The wildcard "*" is used to match any index in a list.
	AllowedClusterInstanceFields = [][]string{

		{"extraAnnotations"},
		{"extraLabels"},

		{"nodes", "*", "extraAnnotations"},
		{"nodes", "*", "extraLabels"},
	}

	// IgnoredClusterInstanceFields contains path patterns for fields that should be ignored.
	// The wildcard "*" is used to match any index in a list.
	IgnoredClusterInstanceFields = [][]string{

		{"nodes", "*", "bmcAddress"},
		{"nodes", "*", "bmcCredentialsName"},
		{"nodes", "*", "bootMACAddress"},
		{"nodes", "*", "nodeNetwork", "interfaces", "*", "macAddress"},

		{"suppressedManifests"},
	}
)
View Source
var (
	CRDsToBeSuppressedForUpgrade = []string{
		"AgentClusterInstall",
	}
)

CRDs needed to be suppressed in ClusterInstance for upgrade

View Source
var InventoryConditionReasons = struct {
	DeploymentsReady                  InventoryConditionReason
	ErrorGettingDeploymentInformation InventoryConditionReason
	DatabaseDeploymentFailed          InventoryConditionReason
	DeploymentNotFound                InventoryConditionReason
	ServerArgumentsError              InventoryConditionReason
	SmoRegistrationSuccessful         InventoryConditionReason
	SmoRegistrationFailed             InventoryConditionReason
	SmoNotConfigured                  InventoryConditionReason
	OAuthClientIDNotConfigured        InventoryConditionReason
}{
	DatabaseDeploymentFailed:          "DatabaseDeploymentFailed",
	DeploymentsReady:                  "AllDeploymentsReady",
	ErrorGettingDeploymentInformation: "ErrorGettingDeploymentInformation",
	DeploymentNotFound:                "DeploymentNotFound",
	ServerArgumentsError:              "ServerArgumentsError",
	SmoRegistrationSuccessful:         "SmoRegistrationSuccessful",
	SmoRegistrationFailed:             "SmoRegistrationFailed",
	SmoNotConfigured:                  "SmoNotConfigured",
	OAuthClientIDNotConfigured:        "OAuthClientIDNotConfigured",
}
View Source
var InventoryConditionTypes = struct {
	Ready                    InventoryConditionType
	NotReady                 InventoryConditionType
	Error                    InventoryConditionType
	Available                InventoryConditionType
	SmoRegistrationCompleted InventoryConditionType

	AlarmServerError        InventoryConditionType
	ArtifactsServerError    InventoryConditionType
	ClusterServerError      InventoryConditionType
	DatabaseServerError     InventoryConditionType
	ResourceServerError     InventoryConditionType
	ProvisioningServerError InventoryConditionType

	AlarmServerAvailable        InventoryConditionType
	ArtifactsServerAvailable    InventoryConditionType
	ClusterServerAvailable      InventoryConditionType
	DatabaseServerAvailable     InventoryConditionType
	ResourceServerAvailable     InventoryConditionType
	ProvisioningServerAvailable InventoryConditionType
}{
	Ready:                    "InventoryReady",
	NotReady:                 "InventoryConditionType",
	Error:                    "Error",
	Available:                "Available",
	SmoRegistrationCompleted: "SmoRegistrationCompleted",

	AlarmServerError:        "AlarmServerError",
	ArtifactsServerError:    "ArtifactsServerError",
	ClusterServerError:      "ClusterServerError",
	DatabaseServerError:     "DatabaseServerError",
	ResourceServerError:     "ResourceServerError",
	ProvisioningServerError: "ProvisioningServerError",

	AlarmServerAvailable:        "AlarmServerAvailable",
	ArtifactsServerAvailable:    "ArtifactsServerAvailable",
	ClusterServerAvailable:      "ClusterServerAvailable",
	DatabaseServerAvailable:     "DatabaseServerAvailable",
	ResourceServerAvailable:     "ResourceServerAvailable",
	ProvisioningServerAvailable: "ProvisioningServerAvailable",
}
View Source
var MapAvailableDeploymentNameConditionType = map[string]InventoryConditionType{
	InventoryAlarmServerName:        InventoryConditionTypes.AlarmServerAvailable,
	InventoryArtifactsServerName:    InventoryConditionTypes.ArtifactsServerAvailable,
	InventoryClusterServerName:      InventoryConditionTypes.ClusterServerAvailable,
	InventoryDatabaseServerName:     InventoryConditionTypes.DatabaseServerAvailable,
	InventoryResourceServerName:     InventoryConditionTypes.ResourceServerAvailable,
	InventoryProvisioningServerName: InventoryConditionTypes.ProvisioningServerAvailable,
}
View Source
var MapErrorDeploymentNameConditionType = map[string]InventoryConditionType{
	InventoryAlarmServerName:        InventoryConditionTypes.AlarmServerError,
	InventoryArtifactsServerName:    InventoryConditionTypes.ArtifactsServerError,
	InventoryClusterServerName:      InventoryConditionTypes.ClusterServerError,
	InventoryDatabaseServerName:     InventoryConditionTypes.DatabaseServerError,
	InventoryResourceServerName:     InventoryConditionTypes.ResourceServerError,
	InventoryProvisioningServerName: InventoryConditionTypes.ProvisioningServerError,
}

Functions

func AddOAuthArgsForProxy

func AddOAuthArgsForProxy(inventory *inventoryv1alpha1.Inventory, clientID string, args []string) []string

AddOAuthArgsForProxy adds the OAuth specific arguments to the kube-rbac-proxy command line args

func AssignMacAddress

func AssignMacAddress(clusterInput map[string]any, hwInterfacess []*hwv1alpha1.Interface,
	nodeSpec *siteconfig.NodeSpec) error

AssignMacAddress assigns a MAC address to a node interface based on matching criteria. Parameters:

  • clusterInput: A map containing the merged cluster input data. It should include a "nodes" key with a slice of node data that specifies interface details.
  • hwInterfaces: A slice of hardware interfaces containing MAC address and label information.
  • nodeSpec: A reference to the node specification where the MAC address will be assigned.

Returns: - error: An error if any unexpected structure or data is encountered; otherwise, nil.

func ClusterIsReadyForPolicyConfig

func ClusterIsReadyForPolicyConfig(
	ctx context.Context, c client.Client, clusterInstanceName string) (bool, error)

ClusterIsReadyForPolicyConfig checks if a cluster is ready for policy configuration by looking at its availability, joined status and hub acceptance.

func CollectNodeDetails

func CollectNodeDetails(ctx context.Context, c client.Client,
	nodePool *hwv1alpha1.NodePool) (map[string][]NodeInfo, error)

CollectNodeDetails collects BMC and node interfaces details

func CompareHardwareTemplateWithNodePool

func CompareHardwareTemplateWithNodePool(hardwareTemplate *hwv1alpha1.HardwareTemplate, nodePool *hwv1alpha1.NodePool) (bool, error)

CompareHardwareTemplateWithNodePool checks if there are any changes in the hardware template resource

func ConvertMapAnyToString

func ConvertMapAnyToString(input map[string]any) map[string]string

ConvertMapAnyToString converts a map of any to a map of strings. Values not of type string are ignored.

func CopyBMCSecrets

func CopyBMCSecrets(ctx context.Context, c client.Client, hwNodes map[string][]NodeInfo,
	nodePool *hwv1alpha1.NodePool) error

CopyBMCSecrets copies BMC secrets from the plugin namespace to the cluster namespace.

func CopyK8sSecret

func CopyK8sSecret(ctx context.Context, c client.Client, secretName, sourceNamespace, targetNamespace string) error

CopyK8sSecret copies a secret from one namespace to another.

func CreateConfigMapFromEmbeddedFile

func CreateConfigMapFromEmbeddedFile(ctx context.Context, c client.Client, ownerObject client.Object, fs embed.FS, path, namespace, name, key string) error

CreateConfigMapFromEmbeddedFile extracts a file from an embedded file system and builds a ConfigMap. If the file does not exist or is not accessible then an error is returned.

func CreateDefaultInventoryCR

func CreateDefaultInventoryCR(ctx context.Context, c client.Client) error

CreateDefaultInventoryCR creates the default Inventory CR so that the system has running servers

func CreateHwMgrPluginNamespace

func CreateHwMgrPluginNamespace(ctx context.Context, c client.Client, name string) error

CreateHwMgrPluginNamespace creates the namespace of the hardware manager plugin where the node pools resource resides

func CreateK8sCR

func CreateK8sCR(ctx context.Context, c client.Client,
	newObject client.Object, ownerObject client.Object,
	operation string) (err error)

CreateK8sCR creates/updates/patches an object.

func CreateSecretFromLiterals

func CreateSecretFromLiterals(ctx context.Context, c client.Client, ownerObject client.Object, namespace, name string, literals map[string][]byte) error

CreateSecretFromLiterals takes a map of key value pairs and produces a Secret.

func DeepMergeMaps

func DeepMergeMaps[K comparable, V any](dst, src map[K]V, checkType bool) error

DeepMergeMaps performs a deep merge of the src map into the dst map. Merge rules:

  1. If a key exists in both src and dst maps: a. If the values are of different types and matched type is required, it returns an error, otherwise, the src values overrides the dst element. b. If the values are both maps, recursively merge them. c. If the values are both slices, deeply merge the slices. d. For other types, the src value overrides the dst value.
  2. If a key exists only in src, add it to dst.
  3. If a key exists only in dst, preserve it.

func DeepMergeSlices

func DeepMergeSlices[K comparable, V any](dst, src []V, checkType bool) ([]V, error)

DeepMergeSlices performs a deep indexing merge of the src slice into the dst slice. Merge rules:

  1. For elements present in both src and dst slices at the same index: a. If the elements are of different types and matched type is required, it returns an error, otherwise, the src element overrides the dst element. b. If the elements are both maps, deeply merge them. c. For other types, the src element overrides the dst element.
  2. If the src slice is longer, append the additional elements from src to dst.
  3. If the dst slice is longer, preserve the additional elements from dst.

func DoesK8SResourceExist

func DoesK8SResourceExist(ctx context.Context, c client.Client, name, namespace string, obj client.Object) (resourceExists bool, err error)

func ExtractBeforeDot

func ExtractBeforeDot(s string) string

ExtractBeforeDot returns the strubstring before the first dot.

func ExtractSchemaRequired

func ExtractSchemaRequired(mainSchema []byte) (required []string, err error)

ExtractSchemaRequired extracts the required field of a subschema

func ExtractTemplateDataFromConfigMap

func ExtractTemplateDataFromConfigMap[T any](cm *corev1.ConfigMap, expectedKey string) (T, error)

ExtractTemplateDataFromConfigMap extracts the template data associated with the specified key from the provided ConfigMap. The data is expected to be in YAML format.

func ExtractTimeoutFromConfigMap

func ExtractTimeoutFromConfigMap(cm *corev1.ConfigMap, key string) (time.Duration, error)

ExtractTimeoutFromConfigMap extracts the timeout config from the ConfigMap by key if exits. converting it from duration string to time.Duration. Returns an error if the value is not a valid duration string.

func GenerateSearchApiUrl

func GenerateSearchApiUrl(backendURL string) (string, error)

GenerateSearchApiUrl appends graphql path to the backend URL to form the fully qualified search path

func GetBackendTokenArg

func GetBackendTokenArg(backendToken string) string

func GetBootMacAddress

func GetBootMacAddress(interfaces []*hwv1alpha1.Interface, nodePool *hwv1alpha1.NodePool) (string, error)

GetBootMacAddress selects the boot interface based on label and return the interface MAC address

func GetClusterID

func GetClusterID(ctx context.Context, c client.Client, name string) (string, error)

GetClusterID retrieves the UUID value for the cluster specified by name

func GetConfigMapField

func GetConfigMapField(cm *corev1.ConfigMap, fieldName string) (string, error)

GetConfigMapField attempts to retrieve the value of the field using the provided field name

func GetConfigmap

func GetConfigmap(ctx context.Context, c client.Client, name, namespace string) (*corev1.ConfigMap, error)

GetConfigmap attempts to retrieve a ConfigMap object for the given name

func GetDatabaseHostname

func GetDatabaseHostname() string

GetDatabaseHostname returns the URL used to access the database service

func GetDefaultBackendTransport

func GetDefaultBackendTransport() (http.RoundTripper, error)

GetDefaultBackendTransport returns an HTTP transport with the proper TLS defaults set.

func GetDefaultTLSConfig

func GetDefaultTLSConfig(config *tls.Config) (*tls.Config, error)

GetDefaultTLSConfig sets the TLS configuration attributes appropriately to enable communication between internal services and accessing the public facing API endpoints.

func GetDefaultsFromConfigMap

func GetDefaultsFromConfigMap(ctx context.Context, c client.Client, configMapName string, configMapNamespace string,
	configMapKey string, schema []byte, schemaKey string) (map[string]interface{}, error)

GetDefaultsFromConfigMap returns the data of a defaults ConfigMap with its content separated in 2 sections:

  • immutable: the values for configuration that is not exposed through the ClusterTemplate.
  • editable : the values for configuration is exposed through the ClusterTemplate and can later be changed through the ProvisioningRequest.

If any error is encountered, the default data is returned as it is in the ConfigMap, without any further separation.

func GetDefaultsFromMaps

func GetDefaultsFromMaps[K comparable, V any](
	mapDefaults map[K]V, mapSchema map[K]V) (map[K]V, map[K]V, error)

GetDefaultsFromMaps separates the values from a map into 2 maps: one with elements that match the passed schema and one with the elements that do not match the schema.

func GetDefaultsFromSlices

func GetDefaultsFromSlices[K comparable, V any](
	sliceDefaults []V, mapSchema map[K]V) ([]V, []V, error)

GetDefaultsFromSlices separates the values from a slice into 2 lists: one with elements that match the passed schema and one with the elements that do not match the schema.

func GetDeploymentVolumeMounts

func GetDeploymentVolumeMounts(serverName string, inventory *inventoryv1alpha1.Inventory) []corev1.VolumeMount

GetDeploymentVolumeMounts builds the list of volume mounts applicable to the specified server

func GetDeploymentVolumes

func GetDeploymentVolumes(serverName string, inventory *inventoryv1alpha1.Inventory) []corev1.Volume

GetDeploymentVolumes builds the list of volumes applicable to the specified server

func GetEnvOrDefault

func GetEnvOrDefault(name, defaultValue string) string

GetEnvOrDefault returns the value of the named environment variable or the supplied default value if the environment variable is not set.

func GetHardwareTemplate

func GetHardwareTemplate(ctx context.Context, c client.Client, hwTemplateName string) (*hwv1alpha1.HardwareTemplate, error)

GetHardwareTemplate retrieves the hardware template resource for a given name

func GetHwMgrPluginNS

func GetHwMgrPluginNS() string

GetHwMgrPluginNS returns the value of environment variable HWMGR_PLUGIN_NAMESPACE

func GetIBGUFromUpgradeDefaultsConfigmap

func GetIBGUFromUpgradeDefaultsConfigmap(
	ctx context.Context,
	c client.Client,
	cmName string,
	cmNamespace string,
	cmKey string,
	clusterName string,
	ibguName string,
	ibguNamespace string,
) (*ibguv1alpha1.ImageBasedGroupUpgrade, error)

func GetIngressDomain

func GetIngressDomain(ctx context.Context, c client.Client) (string, error)

GetIngressDomain will determine the network domain of the default ingress controller

func GetKeyPairFromSecret

func GetKeyPairFromSecret(ctx context.Context, c client.Client, name, namespace string) ([]byte, []byte, error)

GetKeyPairFromSecret retrieves a certificate and its associated private key from a Secret.

func GetParentPolicyNameAndNamespace

func GetParentPolicyNameAndNamespace(childPolicyName string) (policyName, policyNamespace string)

GetParentPolicyNameAndNamespace extracts the parent policy name and namespace from the child policy name. The child policy name follows the format: "<parent_policy_namespace>.<parent_policy_name>". Since the namespace is disallowed to contain ".", splitting the string with "." into two substrings is safe.

func GetPasswordOrRandom

func GetPasswordOrRandom(envName string) string

GetPasswordOrRandom attempts to query a password from the environment and generates a random password if none was found matching the supplied environment variable name.

func GetRoleToGroupNameMap

func GetRoleToGroupNameMap(nodePool *hwv1alpha1.NodePool) map[string]string

GetRoleToGroupNameMap creates a mapping of Role to Group Name from NodePool

func GetSearchAPI

func GetSearchAPI(ctx context.Context, c client.Client) (*corev1.Service, error)

GetSearchAPI attempts to find the search-api service using its label selector

func GetSearchURL

func GetSearchURL(ctx context.Context, c client.Client) (string, error)

GetSearchURL attempts to build the Search API service URL by dynamically looking up the service.

func GetSecret

func GetSecret(ctx context.Context, c client.Client, name, namespace string) (*corev1.Secret, error)

GetSecret attempts to retrieve a Secret object for the given name

func GetSecretField

func GetSecretField(secret *corev1.Secret, fieldName string) (string, error)

GetSecretField attempts to retrieve the value of the field using the provided field name

func GetServerArgs

func GetServerArgs(inventory *inventoryv1alpha1.Inventory, serverName string) (result []string, err error)

func GetServerDatabasePasswordName

func GetServerDatabasePasswordName(serverName string) (string, error)

GetServerDatabasePasswordName retrieves name of the environment variable used to store the server's database password

func GetServiceURL

func GetServiceURL(serverName string) string

GetServiceURL constructs the default service URL for a server

func GetStatusMessage

func GetStatusMessage(condition hwv1alpha1.ConditionType) string

GetStatusMessage returns a status message based on the given condition typ

func GetTLSSkipVerify

func GetTLSSkipVerify() bool

GetTLSSkipVerify returns the current requested value of the TLS Skip Verify setting

func GetTimeoutFromHWTemplate

func GetTimeoutFromHWTemplate(ctx context.Context, c client.Client, name string) (time.Duration, error)

GetTimeoutFromHWTemplate retrieves the timeout value from the hardware template resource. converting it from duration string to time.Duration. Returns an error if the value is not a valid duration string.

func HandleHardwareTimeout

func HandleHardwareTimeout(
	condition hwv1alpha1.ConditionType,
	provisioningStartTime *metav1.Time,
	configurationStartTime *metav1.Time,
	timeout time.Duration,
	currentReason string,
	currentMessage string) (bool, string, string)

HandleHardwareTimeout checks for provisioning or configuration timeout

func HasApiEndpoints

func HasApiEndpoints(serverName string) bool

HasApiEndpoints determines whether a server exposes a set of API endpoints

func HasDatabase

func HasDatabase(serverName string) bool

HasDatabase determines whether a server owns a logical database instance

func HwMgrPluginNamespaceExists

func HwMgrPluginNamespaceExists(ctx context.Context, c client.Client, name string) (bool, error)

HwMgrPluginNamespaceExists checks if the namespace of the hardware manager plugin exists

func IsClusterProvisionCompleted

func IsClusterProvisionCompleted(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterProvisionCompleted checks if the cluster provision condition status is completed. The staleCondition is set when the ClusterDeployment's spec.installed has become true, but its status conditions have not been properly updated due to the known issue (https://issues.redhat.com/browse/ACM-13064). In this case, the cluster has actually been successfully installed and is ready for configuration, but the status wasn't updated correctly. Therefore, we treat it as completed so that the provisioningStatus be updated properly. This workaround can be removed after ACM 2.12 GA.

func IsClusterProvisionFailed

func IsClusterProvisionFailed(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterProvisionFailed checks if the cluster provision condition status is failed

func IsClusterProvisionInProgress

func IsClusterProvisionInProgress(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterProvisionInProgress checks if the cluster provision condition status is in progress.

func IsClusterProvisionPresent

func IsClusterProvisionPresent(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterProvisionPresent checks if the cluster provision condition is present

func IsClusterProvisionTimedOutOrFailed

func IsClusterProvisionTimedOutOrFailed(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterProvisionTimedOutOrFailed checks if the cluster provision condition status is timedout or failed

func IsClusterUpgradeCompleted

func IsClusterUpgradeCompleted(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterUpgradeCompleted checks if the cluster upgrade is completed

func IsClusterUpgradeInProgress

func IsClusterUpgradeInProgress(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterUpgradeInProgress checks if the cluster upgrade condition status is in progress

func IsClusterUpgradeInitiated

func IsClusterUpgradeInitiated(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsClusterUpgradeInitiated checks if the cluster upgrade is initiated

func IsConditionDoesNotExistsErr

func IsConditionDoesNotExistsErr(err error) bool

IsConditionDoesNotExistsErr checks if the given error is of type ConditionDoesNotExistsErr

func IsInputError

func IsInputError(err error) bool

func IsOAuthEnabled

func IsOAuthEnabled(inventory *inventoryv1alpha1.Inventory) bool

IsOAuthEnabled determines if the Inventory CR has OAuth attributes provided.

func IsParentPolicyInZtpClusterTemplateNs

func IsParentPolicyInZtpClusterTemplateNs(policyNamespace, ctNamespace string) bool

IsParentPolicyInZtpClusterTemplateNs checks whether the parent policy resides in the namespace "ztp-<clustertemplate-ns>".

func IsProvisioningStateFulfilled

func IsProvisioningStateFulfilled(cr *provisioningv1alpha1.ProvisioningRequest) bool

IsProvisioningStateFulfilled checks if the provisioning status is fulfilled

func IsSmoRegistrationCompleted

func IsSmoRegistrationCompleted(cr *inventoryv1alpha1.Inventory) bool

IsSmoRegistrationCompleted checks if registration with SMO has been completed

func MakeUUIDFromNames

func MakeUUIDFromNames(namespace string, cloudID uuid.UUID, names ...string) uuid.UUID

MakeUUIDFromNames generates a namespaced uuid value from the specified namespace and name values. The values are scoped to a `cloudID` to avoid conflicts with other systems.

func MapKeysToSlice

func MapKeysToSlice(inputMap map[string]bool) []string

MapKeysToSlice takes a map[string]bool and returns a slice of strings containing the keys

func NeedsOAuthAccess

func NeedsOAuthAccess(serverName string) bool

NeedsOAuthAccess determines whether a server requires access to the Authorization server. This can be either because it needs to get a token to communicate with the SMO or to validate a token against the authorization server directly.

func NewNodeGroup

func NewNodeGroup(group hwv1alpha1.NodePoolData, roleCounts map[string]int) hwv1alpha1.NodeGroup

NewNodeGroup populates NodeGroup

func RenderTemplateForK8sCR

func RenderTemplateForK8sCR(templateName, templatePath string, templateDataObj map[string]any) (*unstructured.Unstructured, error)

RenderTemplateForK8sCR returns a rendered K8s resource with an given template and object data

func RequiresInternalProxy

func RequiresInternalProxy(serverName string) bool

RequiresInternalProxy determines whether a server expects its API to be accessed by another server. If this is the case, then in an OAuth configuration we run a second RBAC proxy for that server which handles authenticating using a Kubernetes service account token rather than an OAuth token.

func RetryOnConflictOrRetriable

func RetryOnConflictOrRetriable(backoff wait.Backoff, fn func() error) error

func RetryOnConflictOrRetriableOrNotFound

func RetryOnConflictOrRetriableOrNotFound(backoff wait.Backoff, fn func() error) error

func SetNodePoolAnnotations

func SetNodePoolAnnotations(nodePool *hwv1alpha1.NodePool, name, value string)

SetNodePoolAnnotations sets annotations on the NodePool

func SetNodePoolLabels

func SetNodePoolLabels(nodePool *hwv1alpha1.NodePool, label, value string)

SetNodePoolLabels sets labels on the NodePool

func SetProvisioningStateDeleting

func SetProvisioningStateDeleting(cr *provisioningv1alpha1.ProvisioningRequest)

SetProvisioningStateDeleting updates the provisioning state to deleting with detailed message

func SetProvisioningStateFailed

func SetProvisioningStateFailed(cr *provisioningv1alpha1.ProvisioningRequest, message string)

SetProvisioningStateFailed updates the provisioning state to failed with detailed message

func SetProvisioningStateFulfilled

func SetProvisioningStateFulfilled(cr *provisioningv1alpha1.ProvisioningRequest)

SetProvisioningStateFulfilled updates the provisioning state to fulfilled with detailed message

func SetProvisioningStateInProgress

func SetProvisioningStateInProgress(cr *provisioningv1alpha1.ProvisioningRequest, message string)

SetProvisioningStateInProgress updates the provisioning state to progressing with detailed message

func SetProvisioningStatePending

func SetProvisioningStatePending(cr *provisioningv1alpha1.ProvisioningRequest, message string)

SetProvisioningStatePending updates the provisioning state to pending with detailed message

func SetStatusCondition

func SetStatusCondition(
	existingConditions *[]metav1.Condition,
	conditionType provisioningv1alpha1.ConditionType,
	conditionReason provisioningv1alpha1.ConditionReason,
	conditionStatus metav1.ConditionStatus,
	message string,
)

SetStatusCondition is a convenience wrapper for meta.SetStatusCondition that takes in the types defined here and converts them to strings

func SetupOAuthClient

func SetupOAuthClient(ctx context.Context, config *OAuthClientConfig) (*http.Client, error)

SetupOAuthClient creates an HTTP client capable of acquiring an OAuth token used to authorize client requests. If the config excludes the OAuth specific sections then the client produced is a simple HTTP client without OAuth capabilities.

func TimeoutExceeded

func TimeoutExceeded(startTime time.Time, timeout time.Duration) bool

TimeoutExceeded returns true if it's been more time than the timeout configuration.

func UpdateHardwareTemplateStatusCondition

func UpdateHardwareTemplateStatusCondition(ctx context.Context, c client.Client, hardwareTemplate *hwv1alpha1.HardwareTemplate,
	conditionType provisioningv1alpha1.ConditionType, conditionReason provisioningv1alpha1.ConditionReason,
	conditionStatus metav1.ConditionStatus, message string) error

UpdateHardwareTemplateStatusCondition updates the status condition of the HardwareTemplate resource

func UpdateK8sCRStatus

func UpdateK8sCRStatus(ctx context.Context, c client.Client, object client.Object) error

func UpdateNodeStatusWithHostname

func UpdateNodeStatusWithHostname(ctx context.Context, c client.Client, nodeName, hostname, namespace string) error

UpdateNodeStatusWithHostname updates the Node status with the hostname after BMC information has been assigned.

func ValidateDefaultInterfaces

func ValidateDefaultInterfaces[T any](data T) error

ValidateDefaultInterfaces verifies that each interface has a specified label field, as labels are not part of the ClusterInstance structure by default.

Types

type AvailableNotification

type AvailableNotification struct {
	GlobalCloudId string `json:"globalCloudId"`
	OCloudId      string `json:"oCloudId"`
	ImsEndpoint   string `json:"IMS_EP"`
}

AvailableNotification represents the data sent to the SMO once the O2IMS is ready to accept API calls. This is from table 3.6.5.1.2-1 in the O-RAN.WG6.O2IMS-INTERFACE-R003-v06.00 document, and presumably will be formally defined in an OpenAPI that we can just import at some point.

type ConditionDoesNotExistsErr

type ConditionDoesNotExistsErr struct {
	ConditionName string
}

ConditionDoesNotExistsErr represents an error when a specific condition is missing

func (*ConditionDoesNotExistsErr) Error

func (e *ConditionDoesNotExistsErr) Error() string

Error implements the error interface for ConditionDoesNotExistsErr, returning a formatted error message

type InputError

type InputError struct {
	// contains filtered or unexported fields
}

InputError wraps a standard error and provides a custom error type for input-related errors

func NewInputError

func NewInputError(format string, args ...interface{}) *InputError

func (*InputError) Error

func (i *InputError) Error() string

type InventoryConditionReason

type InventoryConditionReason string

type InventoryConditionType

type InventoryConditionType string

InventoryConditionType defines conditions of an Inventory deployment.

type NodeInfo

type NodeInfo struct {
	BmcAddress     string
	BmcCredentials string
	NodeName       string
	Interfaces     []*hwv1alpha1.Interface
}

type OAuthClientConfig

type OAuthClientConfig struct {
	OAuthConfig *OAuthConfig
	// The TLS related configuration attributes
	TLSConfig *TLSConfig
}

OAuthClientConfig defines the parameters required to establish an HTTP Client capable of acquiring an OAuth Token from an OAuth capable authorization server.

type OAuthConfig

type OAuthConfig struct {
	// Defines the OAuth client-id attribute to be used when acquiring a token.  If not provided (for debug/testing)
	// then a normal HTTP client without OAuth capabilities will be created
	ClientID string
	// Defines the OAuth client-secret attribute to be used when acquiring a token.
	ClientSecret string
	// The absolute URL of the API endpoint to be used to acquire a token
	// (e.g., http://example.com/realms/oran/protocol/openid-connect/token)
	TokenURL string
	// The list of OAuth scopes requested by the client.  These will be dictated by what the SMO is expecting to see in
	// the token.
	Scopes []string
}

OAuthConfig defines the OAuth config attributes related to an OAuth client configuration

type StaticKeyPairLoader

type StaticKeyPairLoader struct {
	// contains filtered or unexported fields
}

StaticKeyPairLoader provides a means by which we can use a static certificate as input into the dynamic content provider interface. We limit the use of this to clients that are a one-shot implementation that would get re-created periodically and wouldn't need to worry about certificates getting renewed as part of a long lived client.

func NewStaticKeyPairLoader

func NewStaticKeyPairLoader(cert, key []byte) *StaticKeyPairLoader

func (*StaticKeyPairLoader) AddListener

AddListener is a no-op for static providers.

func (*StaticKeyPairLoader) CurrentCertKeyContent

func (s *StaticKeyPairLoader) CurrentCertKeyContent() ([]byte, []byte)

CurrentCertKeyContent loads the key pair from the dynamic source. In this case it is static data so we always load the same data.

func (*StaticKeyPairLoader) Name

func (s *StaticKeyPairLoader) Name() string

Name is a simple name to identify this provider

type TLSConfig

type TLSConfig struct {
	// The client certificate to be used when initiating connection to the server.
	ClientCert dynamiccertificates.CertKeyContentProvider
	// Defines a PEM encoded set of CA certificates used to validate server certificates.  If not provided then the
	// default root CA bundle will be used.
	CaBundle []byte
}

TLSConfig defines the TLS config attributes related to a OAuth client configuration

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL