Skip to content

Commit

Permalink
Fix Generate Sample for Getting Started Tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
camilamacedo86 committed Apr 6, 2024
1 parent a7f6e03 commit 0b6b512
Show file tree
Hide file tree
Showing 14 changed files with 73 additions and 307 deletions.
1 change: 0 additions & 1 deletion docs/book/src/getting-started/testdata/project/PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# This file is used to track the info used to scaffold your project
# and allow the plugins properly work.
# More info: https://book.kubebuilder.io/reference/project-config.html
componentConfig: true
domain: example.com
layout:
- go.kubebuilder.io/v4
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package v1alpha1

import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
cfg "sigs.k8s.io/controller-runtime/pkg/config/v1alpha1"
)

// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
Expand Down Expand Up @@ -65,10 +64,6 @@ type Memcached struct {

Spec MemcachedSpec `json:"spec,omitempty"`
Status MemcachedStatus `json:"status,omitempty"`
// ControllerManagerConfigurationSpec returns the configurations for controllers
cfg.ControllerManagerConfigurationSpec `json:",inline"`

ClusterName string `json:"clusterName,omitempty"`
}

//+kubebuilder:object:root=true
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

73 changes: 58 additions & 15 deletions docs/book/src/getting-started/testdata/project/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package main

import (
"crypto/tls"
"flag"
"os"

Expand All @@ -30,6 +31,8 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"

cachev1alpha1 "example.com/memcached/api/v1alpha1"
"example.com/memcached/internal/controller"
Expand All @@ -49,11 +52,20 @@ func init() {
}

func main() {
var configFile string
flag.StringVar(&configFile, "config", "",
"The controller will load its initial configuration from this file. "+
"Omit this flag to use the default configuration values. "+
"Command-line flags override configuration from this file.")
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
var secureMetrics bool
var enableHTTP2 bool
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.BoolVar(&secureMetrics, "metrics-secure", false,
"If set the metrics endpoint is served securely")
flag.BoolVar(&enableHTTP2, "enable-http2", false,
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
opts := zap.Options{
Development: true,
}
Expand All @@ -62,18 +74,49 @@ func main() {

ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

var err error
ctrlConfig := cachev1alpha1.Memcached{}
options := ctrl.Options{Scheme: scheme}
if configFile != "" {
options, err = options.AndFrom(ctrl.ConfigFile().AtPath(configFile).OfKind(&ctrlConfig))
if err != nil {
setupLog.Error(err, "unable to load the config file")
os.Exit(1)
}
// if the enable-http2 flag is false (the default), http/2 should be disabled
// due to its vulnerabilities. More specifically, disabling http/2 will
// prevent from being vulnerable to the HTTP/2 Stream Cancellation and
// Rapid Reset CVEs. For more information see:
// - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
// - https://github.com/advisories/GHSA-4374-p667-p6c8
disableHTTP2 := func(c *tls.Config) {
setupLog.Info("disabling http/2")
c.NextProtos = []string{"http/1.1"}
}

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)
tlsOpts := []func(*tls.Config){}
if !enableHTTP2 {
tlsOpts = append(tlsOpts, disableHTTP2)
}

webhookServer := webhook.NewServer(webhook.Options{
TLSOpts: tlsOpts,
})

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{
BindAddress: metricsAddr,
SecureServing: secureMetrics,
TLSOpts: tlsOpts,
},
WebhookServer: webhookServer,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "4b13cc52.example.com",
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
// when the Manager ends. This requires the binary to immediately end when the
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
// speeds up voluntary leader transitions as the new leader don't have to wait
// LeaseDuration time first.
//
// In the default scaffold provided, the program ends immediately after
// the manager stops, so would be fine to enable this option. However,
// if you are doing or is intended to do any operation such as perform cleanups
// after the manager stops then its usage might be unsafe.
// LeaderElectionReleaseOnCancel: true,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,73 +26,6 @@ spec:
may reject unrecognized values.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
type: string
cacheNamespace:
description: |-
CacheNamespace if specified restricts the manager's cache to watch objects in
the desired namespace Defaults to all namespaces
Note: If a namespace is specified, controllers can still Watch for a
cluster-scoped resource (e.g Node). For namespaced resources the cache
will only hold objects from the desired namespace.
type: string
clusterName:
type: string
controller:
description: |-
Controller contains global configuration options for controllers
registered within this manager.
properties:
cacheSyncTimeout:
description: |-
CacheSyncTimeout refers to the time limit set to wait for syncing caches.
Defaults to 2 minutes if not set.
format: int64
type: integer
groupKindConcurrency:
additionalProperties:
type: integer
description: |-
GroupKindConcurrency is a map from a Kind to the number of concurrent reconciliation
allowed for that controller.
When a controller is registered within this manager using the builder utilities,
users have to specify the type the controller reconciles in the For(...) call.
If the object's kind passed matches one of the keys in this map, the concurrency
for that controller is set to the number specified.
The key is expected to be consistent in form with GroupKind.String(),
e.g. ReplicaSet in apps group (regardless of version) would be `ReplicaSet.apps`.
type: object
recoverPanic:
description: RecoverPanic indicates if panics should be recovered.
type: boolean
type: object
gracefulShutDown:
description: |-
GracefulShutdownTimeout is the duration given to runnable to stop before the manager actually returns on stop.
To disable graceful shutdown, set to time.Duration(0)
To use graceful shutdown without timeout, set to a negative duration, e.G. time.Duration(-1)
The graceful shutdown is skipped for safety reasons in case the leader election lease is lost.
type: string
health:
description: Health contains the controller health configuration
properties:
healthProbeBindAddress:
description: |-
HealthProbeBindAddress is the TCP address that the controller should bind to
for serving health probes
It can be set to "0" or "" to disable serving the health probe.
type: string
livenessEndpointName:
description: LivenessEndpointName, defaults to "healthz"
type: string
readinessEndpointName:
description: ReadinessEndpointName, defaults to "readyz"
type: string
type: object
kind:
description: |-
Kind is a string value representing the REST resource this object represents.
Expand All @@ -101,75 +34,8 @@ spec:
In CamelCase.
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
type: string
leaderElection:
description: |-
LeaderElection is the LeaderElection config to be used when configuring
the manager.Manager leader election
properties:
leaderElect:
description: |-
leaderElect enables a leader election client to gain leadership
before executing the main loop. Enable this when running replicated
components for high availability.
type: boolean
leaseDuration:
description: |-
leaseDuration is the duration that non-leader candidates will wait
after observing a leadership renewal until attempting to acquire
leadership of a led but unrenewed leader slot. This is effectively the
maximum duration that a leader can be stopped before it is replaced
by another candidate. This is only applicable if leader election is
enabled.
type: string
renewDeadline:
description: |-
renewDeadline is the interval between attempts by the acting master to
renew a leadership slot before it stops leading. This must be less
than or equal to the lease duration. This is only applicable if leader
election is enabled.
type: string
resourceLock:
description: |-
resourceLock indicates the resource object type that will be used to lock
during leader election cycles.
type: string
resourceName:
description: |-
resourceName indicates the name of resource object that will be used to lock
during leader election cycles.
type: string
resourceNamespace:
description: |-
resourceName indicates the namespace of resource object that will be used to lock
during leader election cycles.
type: string
retryPeriod:
description: |-
retryPeriod is the duration the clients should wait between attempting
acquisition and renewal of a leadership. This is only applicable if
leader election is enabled.
type: string
required:
- leaderElect
- leaseDuration
- renewDeadline
- resourceLock
- resourceName
- resourceNamespace
- retryPeriod
type: object
metadata:
type: object
metrics:
description: Metrics contains the controller metrics configuration
properties:
bindAddress:
description: |-
BindAddress is the TCP address that the controller should bind to
for serving prometheus metrics.
It can be set to "0" to disable the metrics serving.
type: string
type: object
spec:
description: MemcachedSpec defines the desired state of Memcached
properties:
Expand Down Expand Up @@ -261,36 +127,6 @@ spec:
type: object
type: array
type: object
syncPeriod:
description: |-
SyncPeriod determines the minimum frequency at which watched resources are
reconciled. A lower period will correct entropy more quickly, but reduce
responsiveness to change if there are many watched resources. Change this
value only if you know what you are doing. Defaults to 10 hours if unset.
there will a 10 percent jitter between the SyncPeriod of all controllers
so that all controllers will not send list requests simultaneously.
type: string
webhook:
description: Webhook contains the controllers webhook configuration
properties:
certDir:
description: |-
CertDir is the directory that contains the server key and certificate.
if not set, webhook server would look up the server key and certificate in
{TempDir}/k8s-webhook-server/serving-certs. The server key and certificate
must be named tls.key and tls.crt, respectively.
type: string
host:
description: |-
Host is the hostname that the webhook server binds to.
It is used to set webhook.Server.Host.
type: string
port:
description: |-
Port is the port that the webhook server serves at.
It is used to set webhook.Server.Port.
type: integer
type: object
type: object
served: true
storage: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@ patches:
# endpoint w/o any authn/z, please comment the following line.
- path: manager_auth_proxy_patch.yaml

# Mount the controller config file for loading manager configurations
# through a ComponentConfig type
- path: manager_config_patch.yaml

# [WEBHOOK] To enable webhook, uncomment all the sections with [WEBHOOK] prefix including the one in
# crd/kustomization.yaml
#- path: manager_webhook_patch.yaml
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,8 @@ spec:
requests:
cpu: 5m
memory: 64Mi
- name: manager
args:
- "--health-probe-bind-address=:8081"
- "--metrics-bind-address=127.0.0.1:8080"
- "--leader-elect"
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,3 @@ spec:
spec:
containers:
- name: manager
args:
- "--config=controller_manager_config.yaml"
volumeMounts:
- name: manager-config
mountPath: /controller_manager_config.yaml
subPath: controller_manager_config.yaml
volumes:
- name: manager-config
configMap:
name: manager-config

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,10 +1,2 @@
resources:
- manager.yaml

generatorOptions:
disableNameSuffixHash: true

configMapGenerator:
- name: manager-config
files:
- controller_manager_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ spec:
containers:
- command:
- /manager
args:
- --leader-elect
image: controller:latest
name: manager
env:
Expand Down
Loading

0 comments on commit 0b6b512

Please sign in to comment.