Skip to content
Merged
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
8 changes: 5 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Build the manager binary
FROM docker.io/library/golang:1.25.4 as builder
FROM docker.io/library/golang:1.26.4 as builder

WORKDIR /workspace
# Copy the Go Modules manifests
Expand All @@ -11,13 +11,15 @@ RUN go mod download

# Copy the go source
COPY main.go main.go
COPY pprof.go pprof.go
COPY pprof_disabled.go pprof_disabled.go
COPY api/ api/
COPY controllers/ controllers/
COPY pkg/ pkg/
COPY internal/ internal/

# Build
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o manager main.go
ARG GO_TAGS=""
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "${GO_TAGS}" -a -o manager .

# Use distroless as minimal base image to package the manager binary
# Refer to https://github.com/GoogleContainerTools/distroless for more details
Expand Down
15 changes: 13 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -108,18 +108,29 @@ prime-test-cluster: mkcert

##@ Build

PPROF_GO_TAGS ?= pprof
PPROF_IMAGE_TAG_SUFFIX ?= -debug

.PHONY: build
build: generate fmt vet ## Build manager binary.
go build -o bin/manager main.go
go build -o bin/manager .

.PHONY: build-debug
build-debug: generate fmt vet ## Build manager binary with pprof enabled.
go build -tags=$(PPROF_GO_TAGS) -o bin/manager .

.PHONY: run
run: manifests generate fmt vet ## Run a controller from your host.
go run ./main.go
go run .

.PHONY: docker-build
docker-build: ## Build docker image with the manager.
docker build -t ${IMG}:${TAG} .

.PHONY: docker-build-debug
docker-build-debug: ## Build docker image with pprof enabled.
docker build --build-arg GO_TAGS=$(PPROF_GO_TAGS) -t ${IMG}:${TAG}$(PPROF_IMAGE_TAG_SUFFIX) .

.PHONY: docker-push
docker-push: ## Push docker image with the manager.
docker push ${IMG}:${TAG}
Expand Down
4 changes: 4 additions & 0 deletions controllers/componentversion_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
kuberecorder "k8s.io/client-go/tools/record"
"ocm.software/ocm/api/datacontext"
"ocm.software/ocm/api/ocm"
ocmdesc "ocm.software/ocm/api/ocm/compdesc"
compdesc "ocm.software/ocm/api/ocm/compdesc/versions/ocm.software/v3alpha1"
Expand Down Expand Up @@ -166,6 +167,9 @@ func (r *ComponentVersionReconciler) Reconcile(ctx context.Context, req ctrl.Req

return ctrl.Result{}, nil
}
defer func() {
_ = datacontext.Close(octx)
}()

// reconcile the version before calling reconcile func
update, version, err := r.checkVersion(ctx, octx, obj)
Expand Down
4 changes: 4 additions & 0 deletions controllers/configuration_strat_merge_patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ func (m *MutationReconcileLooper) strategicMergePatch(
gzipSnapshot := &bytes.Buffer{}
gz := gzip.NewWriter(gzipSnapshot)
if _, err := gz.Write(resource); err != nil {
gz.Close()

return "", err
}

Expand Down Expand Up @@ -89,6 +91,8 @@ func (m *MutationReconcileLooper) strategicMergePatch(
}

if _, err := patched.Write(contents); err != nil {
patched.Close()

return "", err
}

Expand Down
8 changes: 8 additions & 0 deletions controllers/mutation_reconcile_looper.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"ocm.software/ocm/api/datacontext"
ocmcore "ocm.software/ocm/api/ocm"
"ocm.software/ocm/api/ocm/resourcerefs"
"ocm.software/ocm/api/utils/tarutils"
Expand Down Expand Up @@ -307,6 +308,9 @@ func (m *MutationReconcileLooper) fetchDataFromComponentVersion(ctx context.Cont
if err != nil {
return nil, fmt.Errorf("failed to create authenticated client: %w", err)
}
defer func() {
_ = datacontext.Close(octx)
}()

if obj.ResourceRef == nil {
return nil, fmt.Errorf("no resource ref found for %s", key)
Expand Down Expand Up @@ -344,6 +348,7 @@ func (m *MutationReconcileLooper) getSnapshotBytes(ctx context.Context, snapshot
if err != nil {
return nil, fmt.Errorf("failed to fetch data: %w", err)
}
defer reader.Close()

if uncompress {
uncompressed, _, err := compression.AutoDecompress(reader)
Expand Down Expand Up @@ -375,6 +380,9 @@ func (m *MutationReconcileLooper) createSubstitutionRulesForLocalization(
if err != nil {
return nil, fmt.Errorf("failed to create authenticated client: %w", err)
}
defer func() {
_ = datacontext.Close(octx)
}()

compvers, err := m.OCMClient.GetComponentVersion(ctx, octx, cv.GetRepositoryURL(), cv.Spec.Component, cv.Status.ReconciledVersion)
if err != nil {
Expand Down
4 changes: 4 additions & 0 deletions controllers/resource_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
kuberecorder "k8s.io/client-go/tools/record"
"ocm.software/ocm/api/datacontext"
ocmmetav1 "ocm.software/ocm/api/ocm/compdesc/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
Expand Down Expand Up @@ -195,6 +196,9 @@ func (r *ResourceReconciler) reconcile(

return ctrl.Result{}, nil
}
defer func() {
_ = datacontext.Close(octx)
}()

reader, digest, size, err := r.OCMClient.GetResource(ctx, octx, componentVersion, obj.Spec.SourceRef.ResourceRef)
if err != nil {
Expand Down
13 changes: 12 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func main() {
eventsAddr string
enableLeaderElection bool
probeAddr string
pprofAddr string
ociRegistryAddr string
ociRegistryCertSecretName string
ociRegistryInsecureSkipVerify bool
Expand All @@ -79,6 +80,12 @@ func main() {
":8081",
"The address the probe endpoint binds to.",
)
flag.StringVar(
&pprofAddr,
"pprof-bind-address",
":6060",
"The address the pprof endpoint binds to (only used in builds with the pprof tag).",
)
Comment thread
frewilhelm marked this conversation as resolved.
flag.StringVar(
&ociRegistryAddr,
"oci-registry-addr",
Expand Down Expand Up @@ -166,6 +173,11 @@ func main() {
ociRegistryAddr = v
}

if pprofEnabled {
setupLog.Info("starting pprof server", "address", pprofAddr)
startPprof(pprofAddr)
}

setupManagers(ociRegistryAddr, mgr, ociRegistryNamespace, ociRegistryCertSecretName, ociRegistryInsecureSkipVerify, restConfig, eventsAddr)

//+kubebuilder:scaffold:builder
Expand All @@ -180,7 +192,6 @@ func main() {
}

ctx := ctrl.SetupSignalHandler()

setupLog.Info("starting manager")
if err := mgr.Start(ctx); err != nil {
setupLog.Error(err, "problem running manager")
Expand Down
51 changes: 32 additions & 19 deletions pkg/oci/repository.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package oci

import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
Expand All @@ -10,6 +11,7 @@ import (
"io"
"net/http"
"strings"
"sync"

ociname "github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
Expand Down Expand Up @@ -87,9 +89,11 @@ type Client struct {
Namespace string
CertSecretName string

certPem []byte
keyPem []byte
ca []byte
mu sync.Mutex
certPem []byte
keyPem []byte
ca []byte
transport *http.Transport
}

// WithTransport sets up insecure TLS so the library is forced to use HTTPS.
Expand All @@ -99,49 +103,57 @@ func (c *Client) WithTransport(ctx context.Context) Option {
return nil
}

// always refresh certificates to handle cert-manager rotation
if err := c.setupCertificates(ctx); err != nil {
return fmt.Errorf("failed to set up certificates for transport: %w", err)
t, err := c.getOrRefreshTransport(ctx)
if err != nil {
return fmt.Errorf("failed to set up transport: %w", err)
}

o.remoteOpts = append(o.remoteOpts, remote.WithTransport(c.constructTLSRoundTripper()))
o.remoteOpts = append(o.remoteOpts, remote.WithTransport(t))

return nil
}
}

func (c *Client) setupCertificates(ctx context.Context) error {
func (c *Client) getOrRefreshTransport(ctx context.Context) (http.RoundTripper, error) {
c.mu.Lock()
defer c.mu.Unlock()

if c.Client == nil {
return fmt.Errorf("client must not be nil if certificate is requested, please set WithClient when creating the oci cache")
return nil, fmt.Errorf("client must not be nil if certificate is requested, please set WithClient when creating the oci cache")
}

registryCerts := &corev1.Secret{}
if err := c.Client.Get(ctx, apitypes.NamespacedName{Name: c.CertSecretName, Namespace: c.Namespace}, registryCerts); err != nil {
return fmt.Errorf("unable to find the secret containing the registry certificates: %w", err)
return nil, fmt.Errorf("unable to find the secret containing the registry certificates: %w", err)
}

certFile, ok := registryCerts.Data["tls.crt"]
if !ok {
return fmt.Errorf("tls.crt data not found in registry certificate secret")
return nil, fmt.Errorf("tls.crt data not found in registry certificate secret")
}

keyFile, ok := registryCerts.Data["tls.key"]
if !ok {
return fmt.Errorf("tls.key data not found in registry certificate secret")
return nil, fmt.Errorf("tls.key data not found in registry certificate secret")
}

caFile, ok := registryCerts.Data["ca.crt"]
if !ok {
return fmt.Errorf("ca.crt data not found in registry certificate secret")
return nil, fmt.Errorf("ca.crt data not found in registry certificate secret")
}

if c.transport != nil && bytes.Equal(c.certPem, certFile) && bytes.Equal(c.keyPem, keyFile) && bytes.Equal(c.ca, caFile) {
return c.transport, nil
}

if c.transport != nil {
c.transport.CloseIdleConnections()
}

c.certPem = certFile
c.keyPem = keyFile
c.ca = caFile

return nil
}

func (c *Client) constructTLSRoundTripper() http.RoundTripper {
tlsConfig := &tls.Config{}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(c.ca)
Expand All @@ -156,10 +168,11 @@ func (c *Client) constructTLSRoundTripper() http.RoundTripper {
tlsConfig.RootCAs = caCertPool
tlsConfig.InsecureSkipVerify = c.InsecureSkipVerify

// Create a new HTTP transport with the TLS configuration
return &http.Transport{
c.transport = &http.Transport{
TLSClientConfig: tlsConfig,
}

return c.transport, nil
}

// NewClient creates a new OCI Client.
Expand Down
5 changes: 5 additions & 0 deletions pkg/ocm/ocm.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,11 @@ func (c *Client) GetResource(
if err != nil {
return nil, "", -1, fmt.Errorf("failed to autodecompress content: %w", err)
}
defer func() {
if cerr := decompressedReader.Close(); cerr != nil {
err = errors.Join(err, cerr)
}
}()

// We need to push the media type... And construct the right layers I guess.
digest, size, err := c.cache.PushData(ctx, decompressedReader, mediaType, name, version)
Expand Down
8 changes: 3 additions & 5 deletions pkg/snapshot/tar.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,15 @@ func buildTar(artifactPath, sourceDir string) error {
}
f, err := os.Open(p) //nolint:gosec // path is validated by filepath.Walk which skips symlinks
if err != nil {
f.Close()

return err
}
if _, err := io.Copy(tw, f); err != nil {
f.Close()
defer f.Close()

if _, err := io.Copy(tw, f); err != nil {
return err
}

return f.Close()
return nil
}); err != nil {
tw.Close()
tf.Close()
Expand Down
32 changes: 32 additions & 0 deletions pprof.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//go:build pprof

package main

import (
"net/http"
"net/http/pprof"
"time"
)

const pprofEnabled = true

func startPprof(addr string) {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)

server := &http.Server{
Addr: addr,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}

go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
}
7 changes: 7 additions & 0 deletions pprof_disabled.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//go:build !pprof

package main

const pprofEnabled = false

func startPprof(_ string) {}
Loading