Skip to content

Commit

Permalink
Merge pull request #2470 from mrueg/better-align
Browse files Browse the repository at this point in the history
chore: Memory align structs
  • Loading branch information
k8s-ci-robot authored Aug 25, 2024
2 parents 518a39a + 0a86b24 commit 8e4a2ec
Show file tree
Hide file tree
Showing 11 changed files with 102 additions and 98 deletions.
12 changes: 6 additions & 6 deletions internal/discovery/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,18 @@ type kindPlural struct {

// CRDiscoverer provides a cache of the collected GVKs, along with helper utilities.
type CRDiscoverer struct {
// m is a mutex to protect the cache.
m sync.RWMutex
// Map is a cache of the collected GVKs.
Map map[string]map[string][]kindPlural
// ShouldUpdate is a flag that indicates whether the cache was updated.
WasUpdated bool
// CRDsAddEventsCounter tracks the number of times that the CRD informer triggered the "add" event.
CRDsAddEventsCounter prometheus.Counter
// CRDsDeleteEventsCounter tracks the number of times that the CRD informer triggered the "remove" event.
CRDsDeleteEventsCounter prometheus.Counter
// CRDsCacheCountGauge tracks the net amount of CRDs affecting the cache at this point.
CRDsCacheCountGauge prometheus.Gauge
// Map is a cache of the collected GVKs.
Map map[string]map[string][]kindPlural
// m is a mutex to protect the cache.
m sync.RWMutex
// ShouldUpdate is a flag that indicates whether the cache was updated.
WasUpdated bool
}

// SafeRead executes the given function while holding a read lock.
Expand Down
18 changes: 9 additions & 9 deletions internal/store/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,24 +65,24 @@ var _ ksmtypes.BuilderInterface = &Builder{}
// Builder helps to build store. It follows the builder pattern
// (https://en.wikipedia.org/wiki/Builder_pattern).
type Builder struct {
kubeClient clientset.Interface
customResourceClients map[string]interface{}
namespaces options.NamespaceList
// namespaceFilter is inside fieldSelectorFilter
fieldSelectorFilter string
kubeClient clientset.Interface
ctx context.Context
enabledResources []string
familyGeneratorFilter generator.FamilyGeneratorFilter
customResourceClients map[string]interface{}
listWatchMetrics *watch.ListWatchMetrics
shardingMetrics *sharding.Metrics
shard int32
totalShards int
buildStoresFunc ksmtypes.BuildStoresFunc
buildCustomResourceStoresFunc ksmtypes.BuildCustomResourceStoresFunc
allowAnnotationsList map[string][]string
allowLabelsList map[string][]string
useAPIServerCache bool
utilOptions *options.Options
// namespaceFilter is inside fieldSelectorFilter
fieldSelectorFilter string
namespaces options.NamespaceList
enabledResources []string
totalShards int
shard int32
useAPIServerCache bool
}

// NewBuilder returns a new builder.
Expand Down
20 changes: 10 additions & 10 deletions internal/store/pod.go
Original file line number Diff line number Diff line change
Expand Up @@ -1349,14 +1349,14 @@ func createPodStatusPhaseFamilyGenerator() generator.FamilyGenerator {
}

phases := []struct {
v bool
n string
v bool
}{
{phase == v1.PodPending, string(v1.PodPending)},
{phase == v1.PodSucceeded, string(v1.PodSucceeded)},
{phase == v1.PodFailed, string(v1.PodFailed)},
{phase == v1.PodUnknown, string(v1.PodUnknown)},
{phase == v1.PodRunning, string(v1.PodRunning)},
{string(v1.PodPending), phase == v1.PodPending},
{string(v1.PodSucceeded), phase == v1.PodSucceeded},
{string(v1.PodFailed), phase == v1.PodFailed},
{string(v1.PodUnknown), phase == v1.PodUnknown},
{string(v1.PodRunning), phase == v1.PodRunning},
}

ms := make([]*metric.Metric, len(phases))
Expand Down Expand Up @@ -1475,12 +1475,12 @@ func createPodStatusQosClassFamilyGenerator() generator.FamilyGenerator {
}

qosClasses := []struct {
v bool
n string
v bool
}{
{class == v1.PodQOSBestEffort, string(v1.PodQOSBestEffort)},
{class == v1.PodQOSBurstable, string(v1.PodQOSBurstable)},
{class == v1.PodQOSGuaranteed, string(v1.PodQOSGuaranteed)},
{string(v1.PodQOSBestEffort), class == v1.PodQOSBestEffort},
{string(v1.PodQOSBurstable), class == v1.PodQOSBurstable},
{string(v1.PodQOSGuaranteed), class == v1.PodQOSGuaranteed},
}

ms := make([]*metric.Metric, len(qosClasses))
Expand Down
4 changes: 2 additions & 2 deletions internal/store/testutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ import (

type generateMetricsTestCase struct {
Obj interface{}
Func func(interface{}) []metric.FamilyInterface
Want string
MetricNames []string
AllowAnnotationsList []string
AllowLabelsList []string
Want string
Headers []string
Func func(interface{}) []metric.FamilyInterface
}

func (testCase *generateMetricsTestCase) run() error {
Expand Down
25 changes: 13 additions & 12 deletions pkg/customresourcestate/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ type MetricsSpec struct {

// Resource configures a custom resource for metric generation.
type Resource struct {

// Labels are added to all metrics. If the same key is used in a metric, the value from the metric will overwrite the value here.
Labels `yaml:",inline" json:",inline"`

// MetricNamePrefix defines a prefix for all metrics of the resource.
// If set to "", no prefix will be added.
// Example: If set to "foo", MetricNamePrefix will be "foo_<metric>".
Expand All @@ -57,16 +61,13 @@ type Resource struct {
// GroupVersionKind of the custom resource to be monitored.
GroupVersionKind GroupVersionKind `yaml:"groupVersionKind" json:"groupVersionKind"`

// Labels are added to all metrics. If the same key is used in a metric, the value from the metric will overwrite the value here.
Labels `yaml:",inline" json:",inline"`
// ResourcePlural sets the plural name of the resource. Defaults to the plural version of the Kind according to flect.Pluralize.
ResourcePlural string `yaml:"resourcePlural" json:"resourcePlural"`

// Metrics are the custom resource fields to be collected.
Metrics []Generator `yaml:"metrics" json:"metrics"`
// ErrorLogV defines the verbosity threshold for errors logged for this resource.
ErrorLogV klog.Level `yaml:"errorLogV" json:"errorLogV"`

// ResourcePlural sets the plural name of the resource. Defaults to the plural version of the Kind according to flect.Pluralize.
ResourcePlural string `yaml:"resourcePlural" json:"resourcePlural"`
}

// GetMetricNamePrefix returns the prefix to use for metrics.
Expand Down Expand Up @@ -132,25 +133,22 @@ func (l Labels) Merge(other Labels) Labels {

// Generator describes a unique metric name.
type Generator struct {
// Name of the metric. Subject to prefixing based on the configuration of the Resource.
Name string `yaml:"name" json:"name"`
// Help text for the metric.
Help string `yaml:"help" json:"help"`
// Each targets a value or values from the resource.
Each Metric `yaml:"each" json:"each"`

// Labels are added to all metrics. Labels from Each will overwrite these if using the same key.
Labels `yaml:",inline" json:",inline"` // json will inline because it is already tagged
// Name of the metric. Subject to prefixing based on the configuration of the Resource.
Name string `yaml:"name" json:"name"`
// Help text for the metric.
Help string `yaml:"help" json:"help"`
// ErrorLogV defines the verbosity threshold for errors logged for this metric. Must be non-zero to override the resource setting.
ErrorLogV klog.Level `yaml:"errorLogV" json:"errorLogV"`
}

// Metric defines a metric to expose.
// +union
type Metric struct {
// Type defines the type of the metric.
// +unionDiscriminator
Type metric.Type `yaml:"type" json:"type"`

// Gauge defines a gauge metric.
// +optional
Expand All @@ -161,6 +159,9 @@ type Metric struct {
// Info defines an info metric.
// +optional
Info *MetricInfo `yaml:"info" json:"info"`
// Type defines the type of the metric.
// +unionDiscriminator
Type metric.Type `yaml:"type" json:"type"`
}

// ConfigDecoder is for use with FromConfig.
Expand Down
8 changes: 4 additions & 4 deletions pkg/customresourcestate/config_metrics_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,22 @@ type MetricMeta struct {
// MetricGauge targets a Path that may be a single value, array, or object. Arrays and objects will generate a metric per element.
// Ref: https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#gauge
type MetricGauge struct {
MetricMeta `yaml:",inline" json:",inline"`
// LabelFromKey adds a label with the given name if Path is an object. The label value will be the object key.
LabelFromKey string `yaml:"labelFromKey" json:"labelFromKey"`
MetricMeta `yaml:",inline" json:",inline"`

// ValueFrom is the path to a numeric field under Path that will be the metric value.
ValueFrom []string `yaml:"valueFrom" json:"valueFrom"`
// LabelFromKey adds a label with the given name if Path is an object. The label value will be the object key.
LabelFromKey string `yaml:"labelFromKey" json:"labelFromKey"`
// NilIsZero indicates that if a value is nil it will be treated as zero value.
NilIsZero bool `yaml:"nilIsZero" json:"nilIsZero"`
}

// MetricInfo is a metric which is used to expose textual information.
// Ref: https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#info
type MetricInfo struct {
MetricMeta `yaml:",inline" json:",inline"`
// LabelFromKey adds a label with the given name if Path is an object. The label value will be the object key.
LabelFromKey string `yaml:"labelFromKey" json:"labelFromKey"`
MetricMeta `yaml:",inline" json:",inline"`
}

// MetricStateSet is a metric which represent a series of related boolean values, also called a bitset.
Expand Down
12 changes: 6 additions & 6 deletions pkg/customresourcestate/registry_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ type compiledEach compiledMetric

type compiledCommon struct {
labelFromPath map[string]valuePath
path valuePath
t metric.Type
path valuePath
}

func (c compiledCommon) Path() valuePath {
Expand Down Expand Up @@ -211,9 +211,9 @@ func newCompiledMetric(m Metric) (compiledMetric, error) {

type compiledGauge struct {
compiledCommon
labelFromKey string
ValueFrom valuePath
NilIsZero bool
labelFromKey string
}

func (c *compiledGauge) Values(v interface{}) (result []eachValue, errs []error) {
Expand Down Expand Up @@ -376,9 +376,9 @@ func (c *compiledInfo) values(v interface{}) (result []eachValue, err []error) {

type compiledStateSet struct {
compiledCommon
LabelName string
ValueFrom valuePath
List []string
LabelName string
}

func (c *compiledStateSet) Values(v interface{}) (result []eachValue, errs []error) {
Expand Down Expand Up @@ -495,11 +495,11 @@ func (e eachValue) ToMetric() *metric.Metric {
}

type compiledFamily struct {
Name string
Help string
Each compiledEach
Labels map[string]string
LabelFromPath map[string]valuePath
Name string
Help string
ErrorLogV klog.Level
}

Expand Down Expand Up @@ -547,8 +547,8 @@ func addPathLabels(obj interface{}, labels map[string]valuePath, result map[stri
}

type pathOp struct {
part string
op func(interface{}) interface{}
part string
}

type valuePath []pathOp
Expand Down
4 changes: 2 additions & 2 deletions pkg/metric_generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ import (
// DeprecatedVersion is defined only if the metric for which this options applies is,
// in fact, deprecated.
type FamilyGenerator struct {
GenerateFunc func(obj interface{}) *metric.Family
Name string
Help string
Type metric.Type
OptIn bool
DeprecatedVersion string
StabilityLevel basemetrics.StabilityLevel
GenerateFunc func(obj interface{}) *metric.Family
OptIn bool
}

// NewFamilyGeneratorWithStability creates new FamilyGenerator instances with metric
Expand Down
11 changes: 6 additions & 5 deletions pkg/metrics_store/metrics_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,22 @@ import (
// interface. Instead of storing entire Kubernetes objects, it stores metrics
// generated based on those objects.
type MetricsStore struct {
// Protects metrics
mutex sync.RWMutex
// metrics is a map indexed by Kubernetes object id, containing a slice of
// metric families, containing a slice of metrics. We need to keep metrics
// grouped by metric families in order to zip families with their help text in
// MetricsStore.WriteAll().
metrics map[types.UID][][]byte

// generateMetricsFunc generates metrics based on a given Kubernetes object
// and returns them grouped by metric family.
generateMetricsFunc func(interface{}) []metric.FamilyInterface
// headers contains the header (TYPE and HELP) of each metric family. It is
// later on zipped with with their corresponding metric families in
// MetricStore.WriteAll().
headers []string

// generateMetricsFunc generates metrics based on a given Kubernetes object
// and returns them grouped by metric family.
generateMetricsFunc func(interface{}) []metric.FamilyInterface
// Protects metrics
mutex sync.RWMutex
}

// NewMetricsStore returns a new MetricsStore
Expand Down
16 changes: 8 additions & 8 deletions pkg/metricshandler/metrics_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,18 @@ import (
// MetricsHandler is a http.Handler that exposes the main kube-state-metrics
// /metrics endpoint. It allows concurrent reconfiguration at runtime.
type MetricsHandler struct {
opts *options.Options
kubeClient kubernetes.Interface
storeBuilder ksmtypes.BuilderInterface
enableGZIPEncoding bool
kubeClient kubernetes.Interface
storeBuilder ksmtypes.BuilderInterface
opts *options.Options

cancel func()

// mtx protects metricsWriters, curShard, and curTotalShards
mtx *sync.RWMutex
metricsWriters metricsstore.MetricsWriterList
curShard int32
curTotalShards int
mtx *sync.RWMutex
metricsWriters metricsstore.MetricsWriterList
curTotalShards int
curShard int32
enableGZIPEncoding bool
}

// New creates and returns a new MetricsHandler with the given options.
Expand Down
Loading

0 comments on commit 8e4a2ec

Please sign in to comment.