diff --git a/cmd/cert-manager/cert-manager.go b/cmd/cert-manager/cert-manager.go index bbdc883..f1314a5 100644 --- a/cmd/cert-manager/cert-manager.go +++ b/cmd/cert-manager/cert-manager.go @@ -40,8 +40,7 @@ func NewCertManager(checker *cmd.Checker) (*CertManager, error) { t := time.Now() namespace := fmt.Sprintf("cert-manager-test-%d%02d%02d-%s", t.Year(), t.Month(), t.Day(), util.GenerateRandomString(5)) - checker.Logger().Infof("cert-manager check application namespace: %s", namespace) - checker.Chatwork.AddMessage(fmt.Sprintf("cert-manager check application namespace: %s\n", namespace)) + location, _ := time.LoadLocation("Asia/Tokyo") resourceName := "sample" @@ -49,9 +48,15 @@ func NewCertManager(checker *cmd.Checker) (*CertManager, error) { resourceName = v } + checker.Chatwork.AddMessage(fmt.Sprintf("Start in %s at %s\n", checker.ClusterName, time.Now().In(location).Format("2006-01-02 15:04:05"))) + + checker.Logger().Infof("cert-manager check application Namespace: %s", namespace) + checker.Chatwork.AddMessage(fmt.Sprintf("cert-manager check application Namespace: %s\n", namespace)) + k8sclientset, err := config.NewK8sClientset() + if err != nil { - checker.Logger().Fatal("Error NewK8sClientset: ", err) + return nil, fmt.Errorf("error NewK8sClientset: %s", err) } scheme := runtime.NewScheme() @@ -59,8 +64,7 @@ func NewCertManager(checker *cmd.Checker) (*CertManager, error) { k8sclient, err := config.NewK8sClient(client.Options{Scheme: scheme}) if err != nil { - checker.Logger().Errorf("NewK8sClient: %s", err) - return nil, err + return nil, fmt.Errorf("error NewK8sClient: %s", err) } return &CertManager{ @@ -100,8 +104,8 @@ func (c *CertManager) createResources(cert certificates) error { ObjectMeta: metav1.ObjectMeta{ Name: c.Namespace, }}); err != nil { - c.Logger().Error("Error create namespace:", err) - c.Chatwork.AddMessage(fmt.Sprint("Error create namespace:", err)) + c.Logger().Error("Error create Namespace:", err) + c.Chatwork.AddMessage(fmt.Sprint("Error create Namespace:", err)) return err } @@ -125,23 +129,23 @@ func (c *CertManager) cleanUpResources(cert certificates) error { var result *multierror.Error var err error - c.Logger().Error("Delete Certificate:", cert.certificate.ObjectMeta.Name) + c.Logger().Infof("Delete Certificate: %s", cert.certificate.ObjectMeta.Name) if err := c.Client.Delete(context.Background(), cert.certificate); err != nil { c.Chatwork.AddMessage(fmt.Sprintf("Error Delete Certificate: %s\n", err)) - c.Logger().Error("Error Delete Certificate:", err) + c.Logger().Errorf("Error Delete Certificate: %s", err) result = multierror.Append(result, err) } - c.Logger().Error("Delete Issuer:", cert.certificate.ObjectMeta.Name) + c.Logger().Infof("Delete Issuer: %s", cert.certificate.ObjectMeta.Name) if err := c.Client.Delete(context.Background(), cert.issuer); err != nil { c.Chatwork.AddMessage(fmt.Sprintf("Error Delete Issuer: %s\n", err)) - c.Logger().Error("Error Delete Issuer:", err) + c.Logger().Errorf("Error Delete Issuer: %s", err) result = multierror.Append(result, err) } - c.Logger().Error("Delete RootCA:", cert.certificate.ObjectMeta.Name) + c.Logger().Infof("Delete RootCA: %s", cert.certificate.ObjectMeta.Name) if err := c.Client.Delete(context.Background(), cert.rootCA); err != nil { - c.Logger().Error("Error Delete RootCA:", err) + c.Logger().Errorf("Error Delete RootCA: %s", err) c.Chatwork.AddMessage(fmt.Sprintf("Error Delete RootCA: %s\n", err)) result = multierror.Append(result, err) } @@ -221,7 +225,7 @@ func (c *CertManager) createCertificateObject() certificates { // CRなので、client-goではなく、client-runtimeを使う // ここでしか作らないリソースなので、utilのほうには入れない func (c *CertManager) createCert(cert certificates) error { - c.Logger().Infoln("Create RootCA:", cert.rootCA.ObjectMeta.Name) + c.Logger().Infof("Create RootCA: %s", cert.rootCA.ObjectMeta.Name) c.Chatwork.AddMessage(fmt.Sprintf("Create RootCA: %s\n", cert.rootCA.ObjectMeta.Name)) err := c.Client.Create(c.Ctx, cert.rootCA) if err != nil { @@ -233,10 +237,10 @@ func (c *CertManager) createCert(cert certificates) error { err = wait.PollUntilContextTimeout(c.Ctx, 5*time.Second, c.Timeout, true, func(ctx context.Context) (bool, error) { secret, err := secretClient.Get(ctx, cert.rootCA.Spec.SecretName, metav1.GetOptions{}) if err != nil { - c.Logger().WithError(err).Errorf("Waiting for secret %s to be ready", cert.rootCA.Spec.SecretName) + c.Logger().WithError(err).Infof("Waiting for Secret %s to be ready", cert.rootCA.Spec.SecretName) return false, nil } - c.Logger().Infof("Created secret:%s at %s", secret.Name, secret.CreationTimestamp) + c.Logger().Infof("Created Secret:%s at %s", secret.Name, secret.CreationTimestamp) return true, nil }) @@ -245,14 +249,14 @@ func (c *CertManager) createCert(cert certificates) error { } //Create Issuer - c.Logger().Infoln("Create Issuer:", cert.issuer.ObjectMeta.Name) + c.Logger().Infof("Create Issuer: %s", cert.issuer.ObjectMeta.Name) c.Chatwork.AddMessage(fmt.Sprintf("Create Issuer: %s\n", cert.issuer.ObjectMeta.Name)) err = c.Client.Create(c.Ctx, cert.issuer) if err != nil { return err } - c.Logger().Infoln("Create Certificate:", cert.certificate.ObjectMeta.Name) + c.Logger().Infof("Create Certificate: %s", cert.certificate.ObjectMeta.Name) c.Chatwork.AddMessage(fmt.Sprintf("Create Certificate: %s\n", cert.certificate.ObjectMeta.Name)) err = c.Client.Create(c.Ctx, cert.certificate) @@ -263,15 +267,15 @@ func (c *CertManager) createCert(cert certificates) error { err = wait.PollUntilContextTimeout(c.Ctx, 5*time.Second, c.Timeout, true, func(ctx context.Context) (bool, error) { secret, err := secretClient.Get(ctx, cert.certificate.Spec.SecretName, metav1.GetOptions{}) if err != nil { - c.Logger().WithError(err).Errorf("Waiting for secret %s to be ready", cert.certificate.Spec.SecretName) + c.Logger().WithError(err).Infof("Waiting for Secret %s to be ready", cert.certificate.Spec.SecretName) return false, nil } - c.Logger().Infof("Created secret:%s at %s", secret.Name, secret.CreationTimestamp) + c.Logger().Infof("Created Secret:%s at %s", secret.Name, secret.CreationTimestamp) return true, nil }) if err != nil { - return fmt.Errorf("waiting for Certificate secret to be ready: %w", err) + return fmt.Errorf("waiting for Certificate Secret to be ready: %w", err) } return nil diff --git a/cmd/cert-manager/cert-manager_test.go b/cmd/cert-manager/cert-manager_test.go index 8d68969..c51d542 100644 --- a/cmd/cert-manager/cert-manager_test.go +++ b/cmd/cert-manager/cert-manager_test.go @@ -24,7 +24,7 @@ func TestNewCertManager(t *testing.T) { return logrus.NewEntry(logrus.New()) } chatwork := ¬ify.Chatwork{} - checker := cmd.NewChecker(context.Background(), false, logger, chatwork, 3*time.Minute) + checker := cmd.NewChecker(context.Background(), false, logger, chatwork, "test", 3*time.Minute) ingress, err := NewCertManager(checker) if err != nil { t.Fatalf("NewCertManager: %s", err) @@ -59,7 +59,7 @@ func TestCheck(t *testing.T) { now := time.Now() namespace := fmt.Sprintf("cert-manager-test-%d%02d%02d-%s", now.Year(), now.Month(), now.Day(), util.GenerateRandomString(5)) cm := &CertManager{ - Checker: cmd.NewChecker(context.Background(), true, logger, chatwork, 3*time.Minute), + Checker: cmd.NewChecker(context.Background(), true, logger, chatwork, "test", 3*time.Minute), Namespace: namespace, ResourceName: "sample", Clientset: k8sclientset, diff --git a/cmd/checker.go b/cmd/checker.go index 4631630..d3070d4 100644 --- a/cmd/checker.go +++ b/cmd/checker.go @@ -9,21 +9,23 @@ import ( ) type Checker struct { - Ctx context.Context - Debug bool - Logger func() *logrus.Entry - Chatwork *notify.Chatwork - Timeout time.Duration + Ctx context.Context + Debug bool + Logger func() *logrus.Entry + Chatwork *notify.Chatwork + ClusterName string + Timeout time.Duration } -func NewChecker(ctx context.Context, debug bool, logger func() *logrus.Entry, chatwork *notify.Chatwork, timeout time.Duration) *Checker { +func NewChecker(ctx context.Context, debug bool, logger func() *logrus.Entry, chatwork *notify.Chatwork, clusterName string, timeout time.Duration) *Checker { logger().Info("Checker timeout: ", timeout) return &Checker{ - Ctx: ctx, - Debug: debug, - Logger: logger, - Chatwork: chatwork, - Timeout: timeout, + Ctx: ctx, + Debug: debug, + Logger: logger, + Chatwork: chatwork, + ClusterName: clusterName, + Timeout: timeout, } } diff --git a/cmd/cluster-autoscaler/clusterAutoscaler.go b/cmd/cluster-autoscaler/clusterAutoscaler.go index 73d16a7..77e0b00 100644 --- a/cmd/cluster-autoscaler/clusterAutoscaler.go +++ b/cmd/cluster-autoscaler/clusterAutoscaler.go @@ -32,8 +32,10 @@ func NewClusterAutoscaler(checker *cmd.Checker) (*ClusterAutoscaler, error) { namespace := fmt.Sprintf("cluster-autoscaler-test-%d%02d%02d-%s", t.Year(), t.Month(), t.Day(), util.GenerateRandomString(5)) - checker.Logger().Infof("cluster-autoscaler check application namespace: %s", namespace) - checker.Chatwork.AddMessage(fmt.Sprintf("cluster-autoscaler check application namespace: %s\n", namespace)) + location, _ := time.LoadLocation("Asia/Tokyo") + checker.Chatwork.AddMessage(fmt.Sprintf("Start in %s at %s\n", checker.ClusterName, time.Now().In(location).Format("2006-01-02 15:04:05"))) + checker.Logger().Infof("cluster-autoscaler check application Namespace: %s", namespace) + checker.Chatwork.AddMessage(fmt.Sprintf("cluster-autoscaler check application Namespace: %s\n", namespace)) resourceName := "sample-for-scale" nodeLabelKey := "eks.amazonaws.com/capacityType" @@ -53,7 +55,7 @@ func NewClusterAutoscaler(checker *cmd.Checker) (*ClusterAutoscaler, error) { k8sclientset, err := config.NewK8sClientset() if err != nil { - checker.Logger().Fatal("Error NewK8sClientset: ", err) + return nil, fmt.Errorf("error NewK8sClientset: %s", err) } return &ClusterAutoscaler{ diff --git a/cmd/datadog-agent/datadog-agent.go b/cmd/datadog-agent/datadog-agent.go index 52d520e..6246c10 100644 --- a/cmd/datadog-agent/datadog-agent.go +++ b/cmd/datadog-agent/datadog-agent.go @@ -37,11 +37,14 @@ func NewDatadogAgent(checker *cmd.Checker) (*DatadogAgent, error) { appKey = v } - queryMetrics = "avg:kubernetes.cpu.user.total" + queryMetrics = "avg:kubernetes.cpu.user.total{*}" if v := os.Getenv("QUERY_METRICS"); v != "" { queryMetrics = v } + location, _ := time.LoadLocation("Asia/Tokyo") + checker.Chatwork.AddMessage(fmt.Sprintf("Start in %s at %s\n", checker.ClusterName, time.Now().In(location).Format("2006-01-02 15:04:05"))) + return &DatadogAgent{ Checker: checker, ApiKey: apiKey, @@ -104,18 +107,18 @@ func (d *DatadogAgent) checkMetrics() error { } else if r != nil && r.StatusCode == 401 { return true, errors.New("401 Unauthorized") } - d.Logger().Errorf("Error when querying metrics: %v", err) + d.Logger().Warnf("Error when querying metrics: %v", err) return false, err } if len(resp.GetSeries()) == 0 { - d.Logger().Infof("No results found") + d.Logger().Info("No results found") return false, nil } else if len(resp.GetSeries()) > 0 { - d.Logger().Infof("Response from `MetricsApi.QueryMetrics`") + d.Logger().Info("Response from `MetricsApi.QueryMetrics`") d.Chatwork.AddMessage("Response from `MetricsApi.QueryMetrics`\n") responseContent, _ := json.MarshalIndent(resp, "", " ") - d.Logger().Debugf("Response:%s", responseContent) + d.Logger().Debugf("Response: %s", responseContent) return true, nil } diff --git a/cmd/datadog-agent/datadog-agent_test.go b/cmd/datadog-agent/datadog-agent_test.go index f32fcb8..3076b13 100644 --- a/cmd/datadog-agent/datadog-agent_test.go +++ b/cmd/datadog-agent/datadog-agent_test.go @@ -17,7 +17,7 @@ func TestNewDatadogAgent(t *testing.T) { return logrus.NewEntry(logrus.New()) } chatwork := ¬ify.Chatwork{} - checker := cmd.NewChecker(context.Background(), false, logger, chatwork, 3*time.Minute) + checker := cmd.NewChecker(context.Background(), false, logger, chatwork, "test", 3*time.Minute) datadogAgent, err := NewDatadogAgent(checker) if err != nil { t.Fatalf("NewDatadogAgent: %s", err) @@ -36,7 +36,7 @@ func TestCheck(t *testing.T) { chatwork := ¬ify.Chatwork{ApiToken: "token", RoomId: "test", Logger: logger} datadogAgent := &DatadogAgent{ - Checker: cmd.NewChecker(context.Background(), false, logger, chatwork, 1*time.Minute), + Checker: cmd.NewChecker(context.Background(), false, logger, chatwork, "test", 1*time.Minute), ApiKey: "", AppKey: "", QueryMetrics: "", @@ -54,7 +54,7 @@ func TestCheck(t *testing.T) { } datadogAgent = &DatadogAgent{ - Checker: cmd.NewChecker(context.Background(), false, logger, chatwork, 3*time.Minute), + Checker: cmd.NewChecker(context.Background(), false, logger, chatwork, "test", 3*time.Minute), ApiKey: "test", AppKey: "test", QueryMetrics: "avg:kubernetes.cpu.user.total", diff --git a/cmd/fluent/fluent.go b/cmd/fluent/fluent.go index f7de247..e637a1f 100644 --- a/cmd/fluent/fluent.go +++ b/cmd/fluent/fluent.go @@ -38,8 +38,12 @@ func NewFluent(checker *cmd.Checker) (*Fluent, error) { t := time.Now() namespace := fmt.Sprintf("fluent-test-%d%02d%02d-%s", t.Year(), t.Month(), t.Day(), util.GenerateRandomString(5)) - checker.Logger().Infof("fluent check application namespace: %s", namespace) - checker.Chatwork.AddMessage(fmt.Sprintf("fluent check application namespace: %s\n", namespace)) + + location, _ := time.LoadLocation("Asia/Tokyo") + checker.Chatwork.AddMessage(fmt.Sprintf("Start in %s at %s\n", checker.ClusterName, time.Now().In(location).Format("2006-01-02 15:04:05"))) + + checker.Logger().Infof("fluent check application Namespace: %s", namespace) + checker.Chatwork.AddMessage(fmt.Sprintf("fluent check application Namespace: %s\n", namespace)) resourceName := "burst-log-generator" @@ -68,8 +72,12 @@ func NewFluent(checker *cmd.Checker) (*Fluent, error) { k8sclient, err := config.NewK8sClientset() if err != nil { - checker.Logger().Errorf("NewK8sClientset: %s", err) - return nil, err + return nil, fmt.Errorf("NewK8sClientset: %s", err) + } + + awsConfig, err := config.NewAwsConfig(checker.Ctx) + if err != nil { + return nil, fmt.Errorf("NewAwsConfig: %s", err) } return &Fluent{ @@ -79,7 +87,7 @@ func NewFluent(checker *cmd.Checker) (*Fluent, error) { ResourceName: resourceName, LogBucketName: logBucketName, LogPath: logPath, - Awscfg: config.NewAwsConfig(checker.Ctx), + Awscfg: awsConfig, }, nil } @@ -179,7 +187,7 @@ func (f *Fluent) checkS3Object() error { result, err := client.ListObjectsV2(ctx, input) if err != nil { - f.Logger().Error("Got an error retrieving items:", err) + f.Logger().Warnf("Got an error retrieving items: %s", err) return false, nil } @@ -187,10 +195,10 @@ func (f *Fluent) checkS3Object() error { for _, item := range result.Contents { if item.LastModified.After(t) { f.Chatwork.AddMessage(fmt.Sprintf("fluentd output to s3://%s/%s/%s\n", targetBucket, targetPrefix, *item.Key)) - f.Logger().Println("Name: ", *item.Key) - f.Logger().Println("Last modified: ", *item.LastModified) - f.Logger().Println("Size: ", item.Size) - f.Logger().Println("Storage class: ", item.StorageClass) + f.Logger().Infof("Name: %s ", *item.Key) + f.Logger().Infof("Last modified: %s", *item.LastModified) + f.Logger().Infof("Size: %d", item.Size) + f.Logger().Infof("Storage class: %s", item.StorageClass) return true, nil } } @@ -203,7 +211,7 @@ func (f *Fluent) checkS3Object() error { return fmt.Errorf("error waiting for S3 objects to be ready: %w", err) } - f.Logger().Infoln("All S3 Objects are available.") + f.Logger().Info("All S3 Objects are available.") return nil } diff --git a/cmd/fluent/fluent_test.go b/cmd/fluent/fluent_test.go index 316d5e8..b2108a6 100644 --- a/cmd/fluent/fluent_test.go +++ b/cmd/fluent/fluent_test.go @@ -16,7 +16,7 @@ func TestNewFluent(t *testing.T) { return logrus.NewEntry(logrus.New()) } chatwork := ¬ify.Chatwork{} - checker := cmd.NewChecker(context.Background(), false, logger, chatwork, 3*time.Minute) + checker := cmd.NewChecker(context.Background(), false, logger, chatwork, "test", 3*time.Minute) fluent, err := NewFluent(checker) if err != nil { t.Fatalf("NewFluent: %s", err) diff --git a/cmd/ingress/ingress.go b/cmd/ingress/ingress.go index 93f7632..16f39c1 100644 --- a/cmd/ingress/ingress.go +++ b/cmd/ingress/ingress.go @@ -33,15 +33,20 @@ type Ingress struct { ExternalHostname string } -func NewIngress(checker *cmd.Checker, noDnsCheck bool, ingressClassName string) (*Ingress, error) { +func NewIngress(checker *cmd.Checker, noDnsCheck bool) (*Ingress, error) { t := time.Now() namespace := fmt.Sprintf("ingress-test-%d%02d%02d-%s", t.Year(), t.Month(), t.Day(), util.GenerateRandomString(5)) - checker.Logger().Infof("ingress check application namespace: %s", namespace) - checker.Chatwork.AddMessage(fmt.Sprintf("ingress check application namespace: %s\n", namespace)) + + location, _ := time.LoadLocation("Asia/Tokyo") + checker.Chatwork.AddMessage(fmt.Sprintf("Start in %s at %s\n", checker.ClusterName, time.Now().In(location).Format("2006-01-02 15:04:05"))) + + checker.Logger().Infof("Ingress check application Namespace: %s", namespace) + checker.Chatwork.AddMessage(fmt.Sprintf("Ingress check application Namespace: %s\n", namespace)) resourceName := "sample" externalHostName := "sample-skmt.cwtest.info" + ingressClassName := "alb" if v := os.Getenv("RESOURCE_NAME"); v != "" { resourceName = v @@ -50,10 +55,13 @@ func NewIngress(checker *cmd.Checker, noDnsCheck bool, ingressClassName string) externalHostName = v } + if v := os.Getenv("INGRESS_CLASS_NAME"); v != "" { + ingressClassName = v + } + k8sclient, err := config.NewK8sClientset() if err != nil { - checker.Logger().Errorf("NewK8sClientset: %s", err) - return nil, err + return nil, fmt.Errorf("error NewK8sClientset: %s", err) } return &Ingress{ @@ -68,7 +76,7 @@ func NewIngress(checker *cmd.Checker, noDnsCheck bool, ingressClassName string) } func (i *Ingress) Check() error { - i.Chatwork.AddMessage("ingress check start\n") + i.Chatwork.AddMessage("Ingress check start\n") defer i.Chatwork.Send() defer func() { @@ -90,7 +98,7 @@ func (i *Ingress) Check() error { } } - i.Chatwork.AddMessage("ingress check finished\n") + i.Chatwork.AddMessage("Ingress check finished\n") return nil } @@ -103,19 +111,19 @@ func (i *Ingress) createResources() error { ObjectMeta: metav1.ObjectMeta{ Name: i.Namespace, }}); err != nil { - i.Chatwork.AddMessage(fmt.Sprintf("Error Create Namespace: %s", err)) + i.Chatwork.AddMessage(fmt.Sprintf("Error Create Namespace: %s\n", err)) return err } if err := k.CreateDeployment(i.Ctx, i.createDeploymentObject(), i.Timeout); err != nil { - i.Chatwork.AddMessage(fmt.Sprintf("Error Create Deployment: %s", err)) + i.Chatwork.AddMessage(fmt.Sprintf("Error Create Deployment: %s\n", err)) return err } if err := k.CreateService(i.Ctx, i.createServiceObject()); err != nil { - i.Chatwork.AddMessage(fmt.Sprintf("Error Create Service: %s", err)) + i.Chatwork.AddMessage(fmt.Sprintf("Error Create Service: %s\n", err)) return err } if err := k.CreateIngress(i.Ctx, i.createIngressObject(), i.Timeout); err != nil { - i.Chatwork.AddMessage(fmt.Sprintf("Error Create Ingress: %s", err)) + i.Chatwork.AddMessage(fmt.Sprintf("Error Create Ingress: %s\n", err)) return err } return nil @@ -267,25 +275,24 @@ func (i *Ingress) checkDNSRecord() error { c := new(dns.Client) m := new(dns.Msg) - i.Chatwork.AddMessage("ingress create finished\n") - i.Logger().Println("Check DNS Record for: ", i.ExternalHostname) + i.Logger().Infof("Check DNS Record for: %s", i.ExternalHostname) err := wait.PollUntilContextTimeout(i.Ctx, 30*time.Second, i.Timeout, false, func(ctx context.Context) (bool, error) { m.SetQuestion(dns.Fqdn(i.ExternalHostname), dns.TypeA) r, _, err := c.Exchange(m, "8.8.8.8:53") if err != nil { - i.Logger().Println(err) + i.Logger().Warn(err) return false, nil } if len(r.Answer) == 0 { - i.Logger().Println("No record.") + i.Logger().Info("No record.") return false, nil } for _, ans := range r.Answer { if a, ok := ans.(*dns.A); ok { - i.Logger().Println("Record is available:", a.A) + i.Logger().Infof("Record is available: %s", a.A) i.Chatwork.AddMessage(fmt.Sprintf("Record is available: %s\n", a.A)) return true, nil } diff --git a/cmd/ingress/ingress_test.go b/cmd/ingress/ingress_test.go index 27a40aa..2c8250f 100644 --- a/cmd/ingress/ingress_test.go +++ b/cmd/ingress/ingress_test.go @@ -20,8 +20,8 @@ func TestNewIngress(t *testing.T) { return logrus.NewEntry(logrus.New()) } chatwork := ¬ify.Chatwork{} - checker := cmd.NewChecker(context.Background(), false, logger, chatwork, 3*time.Minute) - ingress, err := NewIngress(checker, false, "alb") + checker := cmd.NewChecker(context.Background(), false, logger, chatwork, "test", 3*time.Minute) + ingress, err := NewIngress(checker, false) if err != nil { t.Fatalf("NewIngress: %s", err) } @@ -51,7 +51,7 @@ func TestCheck(t *testing.T) { // kindとingress-nginxがある前提 // レコードは作れないのでNoDnsCheckをtrueにする ingress := &Ingress{ - Checker: cmd.NewChecker(context.Background(), true, logger, chatwork, 1*time.Minute), + Checker: cmd.NewChecker(context.Background(), true, logger, chatwork, "test", 1*time.Minute), Namespace: namespace, Clientset: k8sclient, NoDnsCheck: true, @@ -81,7 +81,7 @@ func TestCheckDNSRecord(t *testing.T) { // kindとingress-nginxがある前提 // レコードは作れないのでNoDnsCheckをtrueにする ingress := &Ingress{ - Checker: cmd.NewChecker(context.Background(), false, logger, chatwork, 1*time.Minute), + Checker: cmd.NewChecker(context.Background(), false, logger, chatwork, "test", 1*time.Minute), Namespace: "ingress-test", Clientset: k8sclient, NoDnsCheck: true, diff --git a/config/config.go b/config/config.go index 593d123..e2fea11 100644 --- a/config/config.go +++ b/config/config.go @@ -2,21 +2,22 @@ package config import ( "context" - "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "k8s.io/client-go/kubernetes" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" ) -func NewAwsConfig(ctx context.Context) aws.Config { +func NewAwsConfig(ctx context.Context) (aws.Config, error) { cfg, err := config.LoadDefaultConfig(ctx) if err != nil { - log.Printf("unable to load SDK config: %v", err) + return aws.Config{}, err } - return cfg + return cfg, nil } func NewK8sClientset() (*kubernetes.Clientset, error) { @@ -27,18 +28,19 @@ func NewK8sClientset() (*kubernetes.Clientset, error) { clientset, err := kubernetes.NewForConfig(config) if err != nil { - log.Printf("error kubernetes NewForConfig: %v", err) return nil, err } return clientset, nil } func NewK8sClient(options client.Options) (client.Client, error) { + // https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/log/log.go#L58 + log.SetLogger(zap.New(zap.UseDevMode(true))) + config := ctrl.GetConfigOrDie() c, err := client.New(config, options) if err != nil { - log.Printf("error kubernetes client: %v", err) return nil, err } return c, nil diff --git a/go.mod b/go.mod index 1a86412..d492466 100644 --- a/go.mod +++ b/go.mod @@ -42,6 +42,7 @@ require ( github.com/evanphx/json-patch/v5 v5.6.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-logr/logr v1.2.4 // indirect + github.com/go-logr/zapr v1.2.4 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.22.3 // indirect @@ -69,6 +70,8 @@ require ( github.com/prometheus/common v0.44.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect github.com/spf13/pflag v1.0.5 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.25.0 // indirect golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect golang.org/x/mod v0.12.0 // indirect golang.org/x/net v0.17.0 // indirect diff --git a/go.sum b/go.sum index d1a6841..8ae2673 100644 --- a/go.sum +++ b/go.sum @@ -38,6 +38,9 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.25.4 h1:yEvZ4neOQ/KpUqyR+X0ycUTW/kVR github.com/aws/aws-sdk-go-v2/service/sts v1.25.4/go.mod h1:feTnm2Tk/pJxdX+eooEsxvlvTWBvDm6CasRZ+JOs2IY= github.com/aws/smithy-go v1.17.0 h1:wWJD7LX6PBV6etBUwO0zElG0nWN9rUhp0WdYeHSHAaI= github.com/aws/smithy-go v1.17.0/go.mod h1:NukqUGpCZIILqqiV0NIjeFh24kd/FAa4beRb6nbIUPE= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= +github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cert-manager/cert-manager v1.13.2 h1:LG8+OLvxtc49CSyfjW7zHSyvlt7JVaHgRGyhfdvPpkk= @@ -110,6 +113,7 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -169,10 +173,15 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= go.uber.org/zap v1.25.0 h1:4Hvk6GtkucQ790dqmj7l1eEnRdKm3k3ZUrUMS2d5+5c= go.uber.org/zap v1.25.0/go.mod h1:JIAUzQIH94IC4fOJQm7gMmBJP5k7wQfdcnYdPoEXJYk= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -180,15 +189,19 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/oauth2 v0.12.0 h1:smVPGxink+n1ZI5pkQa8y6fZT0RW0MgCO5bFpepy4B4= @@ -197,15 +210,20 @@ golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ= golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -216,9 +234,11 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -234,6 +254,7 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= diff --git a/main.go b/main.go index c6dd704..1d79f34 100644 --- a/main.go +++ b/main.go @@ -19,7 +19,6 @@ package main import ( "context" - "fmt" "os" "os/signal" "runtime" @@ -50,9 +49,10 @@ func main() { var ctx context.Context - var ingressClassName string var noDnsCheck bool + clusterName := os.Getenv("CLUSTER_NAME") + var rootCmd = &cobra.Command{ Use: "kibertas", SilenceUsage: true, @@ -73,7 +73,7 @@ func main() { Short: "test cluster-autoscaler", Long: "test cluster-autoscaler", RunE: func(cobra_cmd *cobra.Command, args []string) error { - checker = cmd.NewChecker(ctx, debug, logger, chatwork, time.Duration(timeout)*time.Minute) + checker = cmd.NewChecker(ctx, debug, logger, chatwork, clusterName, time.Duration(timeout)*time.Minute) ca, err := clusterautoscaler.NewClusterAutoscaler(checker) if err != nil { return err @@ -87,8 +87,8 @@ func main() { Short: "test ingress", Long: "test ingress(ingress-controller, external-dns)", RunE: func(cobra_cmd *cobra.Command, args []string) error { - checker = cmd.NewChecker(ctx, debug, logger, chatwork, time.Duration(timeout)*time.Minute) - i, err := ingress.NewIngress(checker, noDnsCheck, ingressClassName) + checker = cmd.NewChecker(ctx, debug, logger, chatwork, clusterName, time.Duration(timeout)*time.Minute) + i, err := ingress.NewIngress(checker, noDnsCheck) if err != nil { return err } @@ -101,7 +101,7 @@ func main() { Short: "test fluent(fluent-bit, fluentd)", Long: "test fluent(fluent-bit, fluentd)", RunE: func(cobra_cmd *cobra.Command, args []string) error { - checker = cmd.NewChecker(ctx, debug, logger, chatwork, time.Duration(timeout)*time.Minute) + checker = cmd.NewChecker(ctx, debug, logger, chatwork, clusterName, time.Duration(timeout)*time.Minute) f, err := fluent.NewFluent(checker) if err != nil { return err @@ -115,7 +115,7 @@ func main() { Short: "test datadog-agent", Long: "test datadog-agent", RunE: func(cobra_cmd *cobra.Command, args []string) error { - checker = cmd.NewChecker(ctx, debug, logger, chatwork, time.Duration(timeout)*time.Minute) + checker = cmd.NewChecker(ctx, debug, logger, chatwork, clusterName, time.Duration(timeout)*time.Minute) da, err := datadogagent.NewDatadogAgent(checker) if err != nil { return err @@ -129,7 +129,7 @@ func main() { Short: "test cert-manager", Long: "test cert-manager", RunE: func(cobra_cmd *cobra.Command, args []string) error { - checker = cmd.NewChecker(ctx, debug, logger, chatwork, time.Duration(timeout)*time.Minute) + checker = cmd.NewChecker(ctx, debug, logger, chatwork, clusterName, time.Duration(timeout)*time.Minute) cm, err := certmanager.NewCertManager(checker) if err != nil { return err @@ -138,56 +138,59 @@ func main() { }, } - /* - var cmdAll = &cobra.Command{ - Use: "all", - Short: "test all application", - Long: "test all application", - RunE: func(cmd *cobra.Command, args []string) error { - logger().Info("test all application") - i, err := ingress.NewIngress(debug, logger, chatwork, noDnsCheck, ingressClassName) - if err != nil { - return err - } - - err = i.Check() - if err != nil { - return err - } - - ca, err := clusterautoscaler.NewClusterAutoscaler(debug, logger, chatwork) - if err != nil { - return err - } - - err = ca.Check() - if err != nil { - return err - } - - cm, err := certmanager.NewCertManager(debug, logger, chatwork) - if err != nil { - return err - } - - err = cm.Check() - if err != nil { - return err - } - - f, err := fluent.NewFluent(debug, logger, chatwork) - if err != nil { - return err - } - - err = f.Check() - if err != nil { - return err - } - return nil - }, - } - */ + var cmdAll = &cobra.Command{ + Use: "all", + Short: "test all application", + Long: "test all application", + RunE: func(cobra_cmd *cobra.Command, args []string) error { + logger().Info("test all application") + checker = cmd.NewChecker(ctx, debug, logger, chatwork, clusterName, time.Duration(timeout)*time.Minute) + ca, err := clusterautoscaler.NewClusterAutoscaler(checker) + if err != nil { + return err + } + if err := ca.Check(); err != nil { + return err + } + + //checker.Chatwork = initChatwork(logger) + i, err := ingress.NewIngress(checker, false) + if err != nil { + return err + } + if err := i.Check(); err != nil { + return err + } + + //checker.Chatwork = initChatwork(logger) + f, err := fluent.NewFluent(checker) + if err != nil { + return err + } + if err := f.Check(); err != nil { + return err + } + + //checker.Chatwork = initChatwork(logger) + da, err := datadogagent.NewDatadogAgent(checker) + if err != nil { + return err + } + if err := da.Check(); err != nil { + return err + } + + //checker.Chatwork = initChatwork(logger) + cm, err := certmanager.NewCertManager(checker) + if err != nil { + return err + } + if err := cm.Check(); err != nil { + return err + } + return nil + }, + } rootCmd.AddCommand(cmdTest) rootCmd.PersistentFlags().IntVar(&timeout, "timeout", 15, "Check timeout. If you want to change the timeout, please specify the number of minutes.") @@ -203,12 +206,12 @@ func main() { logger().Debug("log level: ", logLevel) chatwork = initChatwork(logger) + ctx = newSignalContext(logger, chatwork) cmdIngress.Flags().BoolVar(&noDnsCheck, "no-dns-check", false, "This is a flag for the dns check. If you want to skip the dns check, please specify false.(default: false)") - cmdIngress.Flags().StringVar(&ingressClassName, "ingress-class-name", "alb", "This is a flag for the ingress class name. If you want to change the ingress class name, please specify the name.(default: alb)") - //cmdTest.AddCommand(cmdAll) + cmdTest.AddCommand(cmdAll) cmdTest.AddCommand(cmdFluent) cmdTest.AddCommand(cmdClusterAutoscaler) cmdTest.AddCommand(cmdIngress) @@ -216,6 +219,8 @@ func main() { cmdTest.AddCommand(cmdDatadogAgent) if err := rootCmd.Execute(); err != nil { + chatwork.AddMessage("Error: " + err.Error() + "\n") + chatwork.Send() logger().Fatal("Error: ", err) } } @@ -239,11 +244,8 @@ func newSignalContext(logger func() *logrus.Entry, chatwork *notify.Chatwork) co func initChatwork(logger func() *logrus.Entry) *notify.Chatwork { apiToken := os.Getenv("CHATWORK_API_TOKEN") roomId := os.Getenv("CHATWORK_ROOM_ID") - clusterName := os.Getenv("CLUSTER_NAME") chatwork := notify.NewChatwork(apiToken, roomId, logger) - location, _ := time.LoadLocation("Asia/Tokyo") - chatwork.AddMessage(fmt.Sprintf("kibertas start in %s at %s\n", clusterName, time.Now().In(location).Format("2006-01-02 15:04:05"))) return chatwork } diff --git a/util/k8s/resources.go b/util/k8s/resources.go index b3c18d3..51bdb3f 100644 --- a/util/k8s/resources.go +++ b/util/k8s/resources.go @@ -34,18 +34,18 @@ func (k *K8s) CreateNamespace(ctx context.Context, ns *apiv1.Namespace) error { _, err := k.clientset.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{}) k.logger().Infof("Creating Namespace: %s", ns.Name) if err != nil && kerrors.IsAlreadyExists(err) { - k.logger().Infof("Namespace %s already exists", ns.Name) + k.logger().Warnf("Namespace %s already exists", ns.Name) _, err = k.clientset.CoreV1().Namespaces().Update(context.TODO(), ns, metav1.UpdateOptions{}) if err != nil { - k.logger().Infof("Error updating namespace %s", ns.Name) + k.logger().Errorf("Error updating namespace %s", ns.Name) return err } return nil } else if err != nil { - k.logger().Infoln("Error creating namespace") + k.logger().Info("Error creating namespace") return err } - k.logger().Infoln("Namespace created") + k.logger().Info("Namespace created") return nil } @@ -66,10 +66,10 @@ func (k *K8s) CreateDeployment(ctx context.Context, deployment *appsv1.Deploymen k.logger().Infof("Creating Deployment: %s", deployment.Name) result, err := deploymentsClient.Create(ctx, deployment, metav1.CreateOptions{}) if err != nil && kerrors.IsAlreadyExists(err) { - k.logger().Infof("Already exists, updating deployment: %s", deployment.Name) + k.logger().Warnf("Already exists, updating deployment: %s", deployment.Name) _, err = deploymentsClient.Update(ctx, deployment, metav1.UpdateOptions{}) if err != nil { - k.logger().Error("Error Updating Deployment:", err) + k.logger().Errorf("Error Updating Deployment: %s", err) return err } } else if err != nil { @@ -86,7 +86,7 @@ func (k *K8s) CreateDeployment(ctx context.Context, deployment *appsv1.Deploymen if deployment.Status.ReadyReplicas == *deployment.Spec.Replicas { return true, nil } else { - k.logger().Infof("Waiting for pods to be ready, current: %d, desired: %d", deployment.Status.ReadyReplicas, *deployment.Spec.Replicas) + k.logger().Infof("Waiting for Pods to be ready, current: %d, desired: %d", deployment.Status.ReadyReplicas, *deployment.Spec.Replicas) return false, nil } }) @@ -95,7 +95,7 @@ func (k *K8s) CreateDeployment(ctx context.Context, deployment *appsv1.Deploymen return fmt.Errorf("waiting for Pods to be ready: %w", err) } - k.logger().Infoln("All Pods are ready") + k.logger().Info("All Pods are ready") return nil } @@ -107,30 +107,30 @@ func (k *K8s) DeleteDeployment(deploymentName string) error { if err := deploymentsClient.Delete(context.TODO(), deploymentName, metav1.DeleteOptions{ PropagationPolicy: &deletePolicy, }); err != nil { - k.logger().Error("Error Deleting Deployment: ", err) + k.logger().Errorf("Error Deleting Deployment: %s", err) return err } - k.logger().Infoln("Deleted Deployment.") + k.logger().Info("Deleted Deployment.") return nil } func (k *K8s) CreateService(ctx context.Context, service *apiv1.Service) error { serviceClient := k.clientset.CoreV1().Services(k.namespace) - k.logger().Infof("Create service: %s", service.Name) + k.logger().Infof("Create Service: %s", service.Name) _, err := serviceClient.Create(ctx, service, metav1.CreateOptions{}) if err != nil && kerrors.IsAlreadyExists(err) { - k.logger().Infof("Already exists, updating service: %s", service.Name) + k.logger().Warnf("Already exists, updating Service: %s", service.Name) _, err = serviceClient.Update(ctx, service, metav1.UpdateOptions{}) if err != nil { - k.logger().Error("Error updating service:", err) + k.logger().Errorf("Error updating Service: %s", err) return err } } else if err != nil { - k.logger().Errorf("Error creating service: %s", err) + k.logger().Errorf("Error creating Service: %s", err) return err } - k.logger().Infoln("Created service.") + k.logger().Info("Created Service.") return nil } @@ -138,31 +138,31 @@ func (k *K8s) DeleteService(serviceName string) error { serviceClient := k.clientset.CoreV1().Services(k.namespace) deletePolicy := metav1.DeletePropagationForeground - k.logger().Infof("Deleting service: %s", serviceName) + k.logger().Infof("Deleting Service: %s", serviceName) if err := serviceClient.Delete(context.TODO(), serviceName, metav1.DeleteOptions{ PropagationPolicy: &deletePolicy, }); err != nil { - k.logger().Error("Error deleting service:", err) + k.logger().Errorf("Error deleting Service: %s", err) return err } - k.logger().Infoln("Deleted service.") + k.logger().Info("Deleted Service.") return nil } func (k *K8s) CreateIngress(ctx context.Context, ingress *networkingv1.Ingress, timeout time.Duration) error { ingressClient := k.clientset.NetworkingV1().Ingresses(k.namespace) - k.logger().Infof("Creating ingress: %s", ingress.Name) + k.logger().Infof("Creating Ingress: %s", ingress.Name) _, err := ingressClient.Create(ctx, ingress, metav1.CreateOptions{}) if err != nil && kerrors.IsAlreadyExists(err) { - k.logger().Infof("Already exists, updating ingress: %s", ingress.Name) + k.logger().Warnf("Already exists, updating Ingress: %s", ingress.Name) _, err = ingressClient.Update(ctx, ingress, metav1.UpdateOptions{}) if err != nil { - k.logger().Error("Error updating ingress:", err) + k.logger().Errorf("Error updating Ingress: %s", err) return err } } else if err != nil { - k.logger().Error("Error creating ingress:", err) + k.logger().Errorf("Error creating Ingress: %s", err) return err } @@ -179,7 +179,7 @@ func (k *K8s) CreateIngress(ctx context.Context, ingress *networkingv1.Ingress, return true, nil } } - k.logger().Infoln("Ingress is not yet available, retrying...") + k.logger().Info("Ingress is not yet available, retrying...") return false, nil }) @@ -194,13 +194,13 @@ func (k *K8s) DeleteIngress(ingressName string) error { ingressClient := k.clientset.NetworkingV1().Ingresses(k.namespace) deletePolicy := metav1.DeletePropagationForeground - k.logger().Infof("Deleting ingress: %s", ingressName) + k.logger().Infof("Deleting Ingress: %s", ingressName) if err := ingressClient.Delete(context.TODO(), ingressName, metav1.DeleteOptions{ PropagationPolicy: &deletePolicy, }); err != nil { - k.logger().Error("Error deleting ingress:", err) + k.logger().Errorf("Error deleting Ingress: %s", err) return err } - k.logger().Infof("Deleted ingress: %s", ingressName) + k.logger().Infof("Deleted Ingress: %s", ingressName) return nil } diff --git a/util/notify/chatwork.go b/util/notify/chatwork.go index fbbc84a..a057633 100644 --- a/util/notify/chatwork.go +++ b/util/notify/chatwork.go @@ -43,6 +43,7 @@ func (c *Chatwork) AddMessage(message string) { // https://developer.chatwork.com/ja/endpoint_rooms.html#POST-rooms-room_id-messages // エラーが起きても問題ないので、エラーはログに出力するだけ func (c *Chatwork) Send() { + defer c.Messages.Reset() // APIのURLを作成 apiUrl := fmt.Sprintf("https://api.chatwork.com/v2/rooms/%s/messages", c.RoomId)