Skip to content

Commit

Permalink
chore: new log library (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
azrod authored Oct 17, 2024
1 parent 6d72da4 commit 560a6fc
Show file tree
Hide file tree
Showing 25 changed files with 424 additions and 336 deletions.
20 changes: 0 additions & 20 deletions cmd/admission-controller/certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,11 @@ func generateTLS() (keyPair tls.Certificate, caPEM *bytes.Buffer, err error) {

caPEM, certPEM, certKeyPEM, err := generateCert([]string{webhookBase}, dnsNames, commonName)
if err != nil {
errorLogger.Printf("Failed to generate ca and certificate key pair: %v", err)
return
}

keyPair, err = tls.X509KeyPair(certPEM.Bytes(), certKeyPEM.Bytes())
if err != nil {
errorLogger.Printf("Failed to load certificate key pair: %v", err)
return
}
return
Expand All @@ -76,14 +74,12 @@ func generateCert(orgs, dnsNames []string, commonName string) (caPEM, newCertPEM
// generate private key for CA
caPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
errorLogger.Printf("Failed to generate private key for CA: %v", err)
return nil, nil, nil, err
}

// create the CA certificate
caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &caPrivateKey.PublicKey, caPrivateKey)
if err != nil {
errorLogger.Printf("Failed to create CA certificate: %v", err)
return nil, nil, nil, err
}

Expand All @@ -94,7 +90,6 @@ func generateCert(orgs, dnsNames []string, commonName string) (caPEM, newCertPEM
Bytes: caBytes,
})
if err != nil {
errorLogger.Printf("Failed to encode CA certificate: %v", err)
return nil, nil, nil, err
}

Expand All @@ -103,8 +98,6 @@ func generateCert(orgs, dnsNames []string, commonName string) (caPEM, newCertPEM
writeNewCA(caPEM, manifestWebhookPath)
time.Sleep(2 * time.Second)
applyManifest(manifestWebhookPath)

// debugLogger.Printf("CA certificate Encoded: %s", base64.StdEncoding.EncodeToString(caPEM.Bytes()))
}

// new certificate config
Expand All @@ -124,14 +117,12 @@ func generateCert(orgs, dnsNames []string, commonName string) (caPEM, newCertPEM
// generate new private key
newPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
errorLogger.Printf("Failed to generate private key for new certificate: %v", err)
return nil, nil, nil, err
}

// sign the new certificate
newCertBytes, err := x509.CreateCertificate(rand.Reader, newCert, ca, &newPrivateKey.PublicKey, caPrivateKey)
if err != nil {
errorLogger.Printf("Failed to create new certificate: %v", err)
return nil, nil, nil, err
}

Expand All @@ -142,7 +133,6 @@ func generateCert(orgs, dnsNames []string, commonName string) (caPEM, newCertPEM
Bytes: newCertBytes,
})
if err != nil {
errorLogger.Printf("Failed to encode new certificate: %v", err)
return nil, nil, nil, err
}

Expand All @@ -153,7 +143,6 @@ func generateCert(orgs, dnsNames []string, commonName string) (caPEM, newCertPEM
Bytes: x509.MarshalPKCS1PrivateKey(newPrivateKey),
})
if err != nil {
errorLogger.Printf("Failed to encode new private key: %v", err)
return nil, nil, nil, err
}

Expand All @@ -166,7 +155,6 @@ func writeNewCA(caPEM *bytes.Buffer, filePath string) {
// Lire le fichier
file, err := os.Open(filePath)
if err != nil {
warningLogger.Printf("Failed to open file: %v\n", err)
return
}
defer file.Close()
Expand All @@ -182,14 +170,12 @@ func writeNewCA(caPEM *bytes.Buffer, filePath string) {
}

if err := scanner.Err(); err != nil {
warningLogger.Printf("Failed to read file: %v\n", err)
return
}

// Écrire les modifications dans le fichier
file, err = os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC, 0o644)
if err != nil {
warningLogger.Printf("Failed to open file: %v\n", err)
return
}
defer file.Close()
Expand All @@ -198,7 +184,6 @@ func writeNewCA(caPEM *bytes.Buffer, filePath string) {
for _, line := range lines {
_, err := writer.WriteString(line + "\n")
if err != nil {
warningLogger.Printf("Failed to write to file: %v\n", err)
return
}
}
Expand All @@ -209,7 +194,6 @@ func applyManifest(file string) {
// read the manifest file
manifestBytes, err := os.ReadFile(file)
if err != nil {
warningLogger.Printf("Failed to read manifest: %v\n", err)
return
}

Expand All @@ -218,14 +202,12 @@ func applyManifest(file string) {
obj := &unstructured.Unstructured{}
_, _, err = decoder.Decode(manifestBytes, nil, obj)
if err != nil {
warningLogger.Printf("Failed to decode manifest: %v\n", err)
return
}

// convert the unstructured object to typed object
mutatingWebhookConfiguration, err := kubeclient.DecodeUnstructured[v1.MutatingWebhookConfigurationApplyConfiguration](obj)
if err != nil {
warningLogger.Printf("Failed to decode manifest: %v\n", err)
return
}

Expand All @@ -235,8 +217,6 @@ func applyManifest(file string) {
&mutatingWebhookConfiguration,
metav1.ApplyOptions{Force: true, FieldManager: "kumi-webhook"},
); err != nil {
warningLogger.Printf("Failed to apply manifest: %v\n", err)
return
}
infoLogger.Printf("Successfully applied manifest: %s", file)
}
27 changes: 11 additions & 16 deletions cmd/admission-controller/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,25 @@ import (
"context"
"crypto/tls"
"flag"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"

"github.com/orange-cloudavenue/kube-image-updater/internal/httpserver"
client "github.com/orange-cloudavenue/kube-image-updater/internal/kubeclient"
"github.com/orange-cloudavenue/kube-image-updater/internal/log"
"github.com/orange-cloudavenue/kube-image-updater/internal/metrics"
)

var (
insideCluster bool = true // running inside k8s cluster
debugLogger *log.Logger
infoLogger *log.Logger
warningLogger *log.Logger
errorLogger *log.Logger

webhookNamespace string = "example.com"
webhookServiceName string = "your"
Expand All @@ -49,12 +46,6 @@ var (
)

func init() {
// init loggers
debugLogger = log.New(os.Stderr, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile)
infoLogger = log.New(os.Stderr, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
warningLogger = log.New(os.Stderr, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)
errorLogger = log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)

// webhook server running namespace (default to "default")
if os.Getenv("POD_NAMESPACE") != "" {
webhookNamespace = os.Getenv("POD_NAMESPACE")
Expand Down Expand Up @@ -82,14 +73,14 @@ func main() {
// kubernetes golang library provide flag "kubeconfig" to specify the path to the kubeconfig file
kubeClient, err = client.New(flag.Lookup("kubeconfig").Value.String())
if err != nil {
log.Panicf("Error creating kubeclient: %v", err)
log.WithError(err).Panicf("Error creating kubeclient")
}

// * Webhook server
// generate cert for webhook
pair, caPEM, err := generateTLS()
if err != nil {
errorLogger.Fatalf("Failed to generate TLS pair: %v", err)
log.WithError(err).Fatal("Failed to generate TLS")
}
tlsC := &tls.Config{
Certificates: []tls.Certificate{pair},
Expand All @@ -100,7 +91,7 @@ func main() {
// create or update the mutatingwebhookconfiguration
err = createOrUpdateMutatingWebhookConfiguration(caPEM, webhookServiceName, webhookNamespace, kubeClient)
if err != nil {
errorLogger.Printf("Failed to create or update the mutating webhook configuration: %v", err)
log.WithError(err).Error("Failed to create or update the mutating webhook configuration")
signalChan <- os.Interrupt
}

Expand All @@ -116,11 +107,15 @@ func main() {

s, err := a.Add("webhook", httpserver.WithTLS(tlsC), httpserver.WithAddr(webhookPort))
if err != nil {
errorLogger.Fatalf("Failed to create the server: %v", err)
log.
WithError(err).
WithFields(logrus.Fields{
"address": webhookPort,
}).Fatal("Failed to create the server")
}
s.Config.Post(webhookPathMutate, ServeHandler)
if err := a.Run(); err != nil {
errorLogger.Fatalf("Failed to start HTTP servers: %v", err)
log.WithError(err).Fatal("Failed to start HTTP servers")
}

// !-- OS signal handling --! //
Expand Down
12 changes: 2 additions & 10 deletions cmd/admission-controller/webhook-configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

client "github.com/orange-cloudavenue/kube-image-updater/internal/kubeclient"
"github.com/orange-cloudavenue/kube-image-updater/internal/log"
)

// createOrUpdateMutatingWebhookConfiguration creates or updates the mutating webhook configuration
// for the webhook service. The CA is generated and used for the webhook.
// This function create the request to the Kubernetes API server to create or update the mutating webhook configuration.
func createOrUpdateMutatingWebhookConfiguration(caPEM *bytes.Buffer, webhookService, webhookNamespace string, k client.Interface) error {
infoLogger.Println("Initializing the kube client...")

mutatingWebhookConfigV1Client := k.AdmissionregistrationV1()

var clientConfig admissionregistrationv1.WebhookClientConfig
Expand All @@ -42,8 +41,7 @@ func createOrUpdateMutatingWebhookConfiguration(caPEM *bytes.Buffer, webhookServ
URL: &url,
}
}

infoLogger.Printf("Creating or updating the mutatingwebhookconfiguration: %s", webhookConfigName)
log.Debug("Creating or updating the mutatingwebhookconfiguration")
fail := admissionregistrationv1.Fail
sideEffect := admissionregistrationv1.SideEffectClassNone
mutatingWebhookConfig := &admissionregistrationv1.MutatingWebhookConfiguration{
Expand Down Expand Up @@ -77,12 +75,9 @@ func createOrUpdateMutatingWebhookConfiguration(caPEM *bytes.Buffer, webhookServ
switch {
case err != nil && apierrors.IsNotFound(err):
if _, err := mutatingWebhookConfigV1Client.MutatingWebhookConfigurations().Create(context.TODO(), mutatingWebhookConfig, metav1.CreateOptions{}); err != nil {
warningLogger.Printf("Failed to update the mutatingwebhookconfiguration: %s", webhookConfigName)
return err
}
infoLogger.Printf("Created mutatingwebhookconfiguration: %s", webhookConfigName)
case err != nil:
warningLogger.Printf("Failed to check the mutatingwebhookconfiguration: %s", webhookConfigName)
return err
default:
// there is an existing mutatingWebhookConfiguration
Expand All @@ -98,12 +93,9 @@ func createOrUpdateMutatingWebhookConfiguration(caPEM *bytes.Buffer, webhookServ
reflect.DeepEqual(foundWebhookConfig.Webhooks[0].ClientConfig.URL, mutatingWebhookConfig.Webhooks[0].ClientConfig.URL)) {
mutatingWebhookConfig.ObjectMeta.ResourceVersion = foundWebhookConfig.ObjectMeta.ResourceVersion
if _, err := mutatingWebhookConfigV1Client.MutatingWebhookConfigurations().Update(context.TODO(), mutatingWebhookConfig, metav1.UpdateOptions{}); err != nil {
warningLogger.Printf("Failed to update the mutatingwebhookconfiguration: %s", webhookConfigName)
return err
}
infoLogger.Printf("Updated the mutatingwebhookconfiguration: %s", webhookConfigName)
}
infoLogger.Printf("The mutatingwebhookconfiguration: %s already exists and has no change", webhookConfigName)
}

return nil
Expand Down
Loading

0 comments on commit 560a6fc

Please sign in to comment.