Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Note: this is not an officially supported Google product.
* [[Boost resources] fixed target](#boost-resources-fixed-target)
* [[Boost duration] fixed time](#boost-duration-fixed-time)
* [[Boost duration] POD condition](#boost-duration-pod-condition)
* [[Boost resources] pattern matching for containers](#boost-resources-pattern-matching-for-containers)
* [Configuration](#configuration)
* [Metrics](#metrics)
* [License](#license)
Expand Down Expand Up @@ -201,6 +202,82 @@ Define the POD condition, the resource boost effect will last until the conditio
status: "True"
```

### [Boost resources] pattern matching for containers

You can define `containerPolicies` that apply to one or more containers by using pattern matching on the container name. This allows for flexible and powerful policy definitions.

The operator supports three types of patterns:

#### **1. Exact Match**
Matches a specific container name exactly. This pattern has the **highest precedence**.
```yaml
containerPolicies:
- containerName: my-app-container
percentageIncrease:
value: 50
```

#### **2. Glob Patterns**
Use wildcard patterns familiar from shell commands. Glob patterns have a higher precedence than Regex patterns and the universal wildcard (`*`). More specific globs (e.g., `app-*-db`) are prioritized over less specific ones (e.g., `*-db`).

Supported wildcards:
- `*`: matches any sequence of characters.
- `?`: matches any single character.
- `[]`: matches any character within the brackets. Can be negated with `!`.
```yaml
containerPolicies:
# Matches istio-sidecar, envoy-sidecar, etc.
- containerName: '*-sidecar'
percentageIncrease:
value: 30
# Matches app-v1, app-v2, etc.
- containerName: 'app-v?'
percentageIncrease:
value: 25
```

#### **3. Regular Expressions**
For complex patterns, use regular expressions. The pattern must start with `^` and/or end with `$`. Regex patterns have a lower precedence than Exact and Glob patterns but higher than the universal wildcard (`*`).
```yaml
containerPolicies:
# Matches containers starting with app or api
- containerName: '^(app|api).*$'
percentageIncrease:
value: 40
```

#### **Precedence and Evaluation**
When multiple `containerPolicies` are defined, they are evaluated based on pattern specificity, not the order in the YAML file. The first policy that matches a container's name, based on the precedence order below, will be applied.

The precedence order is:
1. **Exact Match** (e.g., `app-frontend`)
2. **Glob Pattern** (e.g., `*-db`, `app-*`)
3. **Regular Expression** (e.g., `^app-.*$`)
4. **Universal Wildcard** (`*`)

**Example: Mixed Policies**

Given the following policies, the `app-frontend` container will get the `200%` increase (exact match), `api-backend` will get the `150%` increase (regex match), `cache-db` will get the `100%` increase (glob match), and any other container will get the `50%` increase (wildcard).

```yaml
spec:
resourcePolicy:
containerPolicies:
# Order does not matter; policies are sorted by precedence.
- containerName: '*' # 4th (Wildcard)
percentageIncrease:
value: 50
- containerName: '^(api)-.*$' # 3rd (Regex)
percentageIncrease:
value: 150
- containerName: '*-db' # 2nd (Glob)
percentageIncrease:
value: 100
- containerName: 'app-frontend' # 1st (Exact)
percentageIncrease:
value: 200
```

## Configuration

Kube Startup CPU Boost operator can be configured with environmental variables.
Expand Down
105 changes: 105 additions & 0 deletions examples/pattern-matching-examples.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
---
# Examples demonstrating container name pattern matching.
#
# The operator applies container policies based on a specific precedence order,
# not the order they appear in the YAML file.
#
# Precedence Order:
# 1. Exact Match (e.g., "my-app")
# 2. Glob Pattern (e.g., "*-sidecar")
# 3. Regular Expression (e.g., "^(app|api).*$")
# 4. Universal Wildcard ("*")
#
---
apiVersion: autoscaling.x-k8s.io/v1alpha1
kind: StartupCPUBoost
metadata:
name: pattern-precedence-example
namespace: default
spec:
selector:
matchLabels:
app: my-microservices-app
resourcePolicy:
containerPolicies:
# The order here is intentionally mixed to demonstrate that precedence,
# not file order, determines which policy is applied.

# 4. Universal Wildcard (lowest precedence)
# Matches any container not matched by a more specific pattern.
- containerName: '*'
percentageIncrease:
value: 25

# 3. Regular Expression
# Matches containers like 'auth-service', 'payment-service'.
- containerName: '^(auth|payment)-.*$'
percentageIncrease:
value: 200

# 2. Glob Pattern
# Matches containers like 'envoy-sidecar', 'istio-proxy-sidecar'.
- containerName: '*-sidecar'
percentageIncrease:
value: 75

# 1. Exact Match (highest precedence)
# Matches only the container named 'api-gateway'.
- containerName: 'api-gateway'
fixedResources:
requests: "2"
limits: "4"

durationPolicy:
podCondition:
type: Ready
status: "True"
---
apiVersion: autoscaling.x-k8s.io/v1alpha1
kind: StartupCPUBoost
metadata:
name: advanced-glob-example
namespace: default
spec:
selector:
matchLabels:
app: web-services
resourcePolicy:
containerPolicies:
# A more specific glob takes precedence over a less specific one.
# 'web-app-v2' is more specific than 'web-*' because it's longer.
- containerName: 'web-app-v2'
percentageIncrease:
value: 150
- containerName: 'web-*'
percentageIncrease:
value: 100

# Question mark matches a single character. Matches 'db-1', 'db-2', etc.
- containerName: 'db-?'
fixedResources:
requests: "0.5"
limits: "1"

# Character class matches a range. Matches 'cache-0', 'cache-1', etc.
- containerName: 'cache-[0-9]'
fixedResources:
requests: "0.3"
limits: "0.8"
durationPolicy:
fixedDuration:
unit: Seconds
value: 90
199 changes: 199 additions & 0 deletions internal/boost/pattern/matcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pattern

import (
"fmt"
"regexp"
"strings"
)

// Matcher matches container names against patterns (glob, regex, or exact)
type Matcher struct {
pattern string
regex *regexp.Regexp
isRegex bool
isGlob bool
isExact bool
}

// NewMatcher creates a new pattern matcher from a container name pattern
func NewMatcher(pattern string) (*Matcher, error) {
m := &Matcher{
pattern: pattern,
}

// Check if pattern is a regex (starts with ^ and/or ends with $)
if strings.HasPrefix(pattern, "^") || strings.HasSuffix(pattern, "$") {
m.isRegex = true
regex, err := regexp.Compile(pattern)
if err != nil {
return nil, fmt.Errorf("invalid regex pattern %q: %w", pattern, err)
}
m.regex = regex
return m, nil
}

// Check if pattern contains glob wildcards
if strings.Contains(pattern, "*") || strings.Contains(pattern, "?") || strings.Contains(pattern, "[") {
m.isGlob = true
return m, nil
}

// Exact match
m.isExact = true
return m, nil
}

// Matches returns true if the container name matches the pattern
func (m *Matcher) Matches(containerName string) bool {
if m.isRegex {
return m.regex.MatchString(containerName)
}

if m.isGlob {
return matchGlob(m.pattern, containerName)
}

// Exact match
return m.pattern == containerName
}

// matchGlob implements simple glob pattern matching
// Supports: *, ?, [abc], [a-z], [!abc]
func matchGlob(pattern, name string) bool {
return globMatch(pattern, name, 0, 0)
}

func globMatch(pattern, name string, pi, ni int) bool {
for pi < len(pattern) {
switch pattern[pi] {
case '*':
// Handle multiple consecutive asterisks
for pi < len(pattern) && pattern[pi] == '*' {
pi++
}

// If asterisk is at the end, it matches everything
if pi == len(pattern) {
return true
}

// Try to match the rest of the pattern with all suffixes of name
for ni <= len(name) {
if globMatch(pattern, name, pi, ni) {
return true
}
ni++
}
return false

case '?':
// ? matches any single character except empty
if ni >= len(name) {
return false
}
pi++
ni++

case '[':
// Character class [abc], [a-z], [!abc]
if ni >= len(name) {
return false
}

nextClose := strings.IndexByte(pattern[pi:], ']')
if nextClose == -1 {
return false // Invalid pattern: unclosed [
}

charClass := pattern[pi+1 : pi+nextClose]
negate := false
if len(charClass) > 0 && charClass[0] == '!' {
negate = true
charClass = charClass[1:]
}

matched := matchCharClass(charClass, name[ni])
if negate {
matched = !matched
}
if !matched {
return false
}

pi += nextClose + 1
ni++

case '\\':
// Escape next character
if pi+1 >= len(pattern) {
return false
}
pi++
if ni >= len(name) || pattern[pi] != name[ni] {
return false
}
pi++
ni++

default:
// Regular character must match exactly
if ni >= len(name) || pattern[pi] != name[ni] {
return false
}
pi++
ni++
}
}

return ni == len(name)
}

func matchCharClass(charClass string, char byte) bool {
i := 0
for i < len(charClass) {
// Check for range (e.g., a-z)
if i+2 < len(charClass) && charClass[i+1] == '-' {
if char >= charClass[i] && char <= charClass[i+2] {
return true
}
i += 3
continue
}

if char == charClass[i] {
return true
}
i++
}
return false
}

func (m *Matcher) IsExact() bool {
return m.isExact
}

func (m *Matcher) IsRegex() bool {
return m.isRegex
}

func (m *Matcher) IsGlob() bool {
return m.isGlob
}

func (m *Matcher) Pattern() string {
return m.pattern
}
Loading