Skip to content

Commit

Permalink
Merge pull request #16 from WanderaOrg/logging
Browse files Browse the repository at this point in the history
Logging improvements
  • Loading branch information
coufalja authored Jul 25, 2018
2 parents 9114ed2 + 0bbe658 commit e8b6f2e
Show file tree
Hide file tree
Showing 15 changed files with 79 additions and 53 deletions.
23 changes: 22 additions & 1 deletion Gopkg.lock

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

22 changes: 8 additions & 14 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"fmt"
"github.com/WanderaOrg/scccmd/pkg/client"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"io/ioutil"
)
Expand Down Expand Up @@ -55,18 +56,15 @@ func ExecuteGetValues(args []string) error {
}

if gp.destination != "" {
if Verbose {
fmt.Println("Config server response:")
fmt.Println(resp)
}
log.Debug("Config server response:")
log.Debug(resp)

if err = ioutil.WriteFile(gp.destination, []byte(resp), 0644); err != nil {
return err
}

if Verbose {
fmt.Println("Response written to: ", gp.destination)
}
log.Debug("Response written to: ", gp.destination)

} else {
fmt.Print(resp)
}
Expand All @@ -85,18 +83,14 @@ func ExecuteGetFiles(args []string) error {
return err
}

if Verbose {
fmt.Println("Config server response:")
fmt.Println(string(resp))
}
log.Debug("Config server response:")
log.Debug(string(resp))

if err = ioutil.WriteFile(mapping.destination, resp, 0644); err != nil {
return err
}

if Verbose {
fmt.Println("Response written to: ", mapping.destination)
}
log.Debug("Response written to: ", mapping.destination)
}
return nil
}
Expand Down
17 changes: 14 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,33 @@
package cmd

import (
"fmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

//Verbose verbose logging turned on
var Verbose bool
var loglevel string

var rootCmd = &cobra.Command{
Use: "scccmd",
DisableAutoGenTag: true,
Short: "Spring Cloud Config management tool",
Long: `Commandline tool used for managing configuration from Spring Cloud Config Server.
Tool currently provides functionality t get (download) config file from server.`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
lvl, err := log.ParseLevel(loglevel)
if err != nil {
return err
}

log.SetLevel(lvl)
return nil
},
}

func init() {
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
rootCmd.PersistentFlags().StringVar(&loglevel, "log-level", "info", fmt.Sprintf("command log level (options: %s)", log.AllLevels))

rootCmd.AddCommand(getCmd)
rootCmd.AddCommand(genDocCmd)
rootCmd.AddCommand(encryptCmd)
Expand Down
6 changes: 3 additions & 3 deletions cmd/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package cmd

import (
"github.com/WanderaOrg/scccmd/pkg/inject"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"log"
"os"
"os/signal"
"syscall"
Expand Down Expand Up @@ -41,9 +41,9 @@ func executeWebhook(args []string) error {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

log.Println("Config webhook started")
log.Info("Config webhook started")
<-signalChan
log.Println("Shutdown signal received, exiting...")
log.Info("Shutdown signal received, exiting...")
close(stop)

return nil
Expand Down
4 changes: 2 additions & 2 deletions docs/scccmd.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ Tool currently provides functionality t get (download) config file from server.
### Options

```
-h, --help help for scccmd
-v, --verbose verbose output
-h, --help help for scccmd
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
```

### SEE ALSO
Expand Down
2 changes: 1 addition & 1 deletion docs/scccmd_decrypt.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ scccmd decrypt [flags]
### Options inherited from parent commands

```
-v, --verbose verbose output
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
```

### SEE ALSO
Expand Down
2 changes: 1 addition & 1 deletion docs/scccmd_encrypt.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ scccmd encrypt [flags]
### Options inherited from parent commands

```
-v, --verbose verbose output
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
```

### SEE ALSO
Expand Down
2 changes: 1 addition & 1 deletion docs/scccmd_gendoc.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ scccmd gendoc [flags]
### Options inherited from parent commands

```
-v, --verbose verbose output
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
```

### SEE ALSO
Expand Down
2 changes: 1 addition & 1 deletion docs/scccmd_get.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Get the config from the given config server
### Options inherited from parent commands

```
-v, --verbose verbose output
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
```

### SEE ALSO
Expand Down
2 changes: 1 addition & 1 deletion docs/scccmd_get_files.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ scccmd get files [flags]
```
-a, --application string name of the application to get the config for
-l, --label string configuration label (default "master")
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
-p, --profile string configuration profile (default "default")
-s, --source string address of the config server
-v, --verbose verbose output
```

### SEE ALSO
Expand Down
2 changes: 1 addition & 1 deletion docs/scccmd_get_values.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ scccmd get values [flags]
```
-a, --application string name of the application to get the config for
-l, --label string configuration label (default "master")
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
-p, --profile string configuration profile (default "default")
-s, --source string address of the config server
-v, --verbose verbose output
```

### SEE ALSO
Expand Down
2 changes: 1 addition & 1 deletion docs/scccmd_webhook.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ scccmd webhook [flags]
### Options inherited from parent commands

```
-v, --verbose verbose output
--log-level string command log level (options: [panic fatal error warning info debug]) (default "info")
```

### SEE ALSO
Expand Down
36 changes: 18 additions & 18 deletions pkg/inject/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"github.com/dimiro1/health"
"github.com/howeyc/fsnotify"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"io/ioutil"
"k8s.io/api/admission/v1beta1"
Expand All @@ -15,7 +16,6 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"log"
"net/http"
"path/filepath"
"sync"
Expand Down Expand Up @@ -182,7 +182,7 @@ func NewWebhook(p WebhookParameters) (*Webhook, error) {
func (wh *Webhook) Run(stop <-chan struct{}) {
go func() {
if err := wh.server.ListenAndServeTLS("", ""); err != nil {
log.Printf("ListenAndServeTLS for admission webhook returned error: %v", err)
log.Errorf("ListenAndServeTLS for admission webhook returned error: %v", err)
}
}()
defer wh.watcher.Close() // nolint: errcheck
Expand All @@ -201,13 +201,13 @@ func (wh *Webhook) Run(stop <-chan struct{}) {
case <-timerC:
config, err := loadConfig(wh.configFile)
if err != nil {
log.Printf("update error: %v", err)
log.Errorf("update error: %v", err)
break
}

pair, err := tls.LoadX509KeyPair(wh.certFile, wh.keyFile)
if err != nil {
log.Printf("reload cert error: %v", err)
log.Errorf("reload cert error: %v", err)
break
}
wh.mu.Lock()
Expand All @@ -220,11 +220,11 @@ func (wh *Webhook) Run(stop <-chan struct{}) {
timerC = time.After(watchDebounceDelay)
}
case err := <-wh.watcher.Error:
log.Printf("Watcher error: %v", err)
log.Errorf("Watcher error: %v", err)
case <-healthC:
content := []byte(`ok`)
if err := ioutil.WriteFile(wh.healthCheckFile, content, 0644); err != nil {
log.Printf("Health check update of %q failed: %v", wh.healthCheckFile, err)
log.Errorf("Health check update of %q failed: %v", wh.healthCheckFile, err)
}
case <-stop:
return
Expand All @@ -240,23 +240,23 @@ func (wh *Webhook) serveInject(w http.ResponseWriter, r *http.Request) {
}
}
if len(body) == 0 {
log.Println("no body found")
log.Errorf("no body found")
http.Error(w, "no body found", http.StatusBadRequest)
return
}

// verify the content type is accurate
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
log.Printf("contentType=%s, expect application/json \n", contentType)
log.Errorf("contentType=%s, expect application/json \n", contentType)
http.Error(w, "invalid Content-Type, want `application/json`", http.StatusUnsupportedMediaType)
return
}

var reviewResponse *v1beta1.AdmissionResponse
ar := v1beta1.AdmissionReview{}
if _, _, err := deserializer.Decode(body, nil, &ar); err != nil {
log.Printf("Could not decode body: %v", err)
log.Errorf("Could not decode body: %v", err)
reviewResponse = toAdmissionResponse(err)
} else {
reviewResponse = wh.inject(&ar)
Expand All @@ -272,11 +272,11 @@ func (wh *Webhook) serveInject(w http.ResponseWriter, r *http.Request) {

resp, err := json.Marshal(response)
if err != nil {
log.Printf("Could not encode response: %v", err)
log.Errorf("Could not encode response: %v", err)
http.Error(w, fmt.Sprintf("could encode response: %v", err), http.StatusInternalServerError)
}
if _, err := w.Write(resp); err != nil {
log.Printf("Could not write response: %v", err)
log.Errorf("Could not write response: %v", err)
http.Error(w, fmt.Sprintf("could not write response: %v", err), http.StatusInternalServerError)
}
}
Expand Down Expand Up @@ -310,17 +310,17 @@ func (wh *Webhook) inject(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionRespons
req := ar.Request
var pod corev1.Pod
if err := json.Unmarshal(req.Object.Raw, &pod); err != nil {
log.Printf("Could not unmarshal raw object: %v", err)
log.Errorf("Could not unmarshal raw object: %v", err)
return toAdmissionResponse(err)
}

log.Printf("AdmissionReview for Kind=%v Namespace=%v Name=%v (%v) UID=%v Rfc6902PatchOperation=%v UserInfo=%v",
log.Infof("AdmissionReview for Kind=%v Namespace=%v Name=%v (%v) UID=%v Rfc6902PatchOperation=%v UserInfo=%v",
req.Kind, req.Namespace, req.Name, pod.Name, req.UID, req.Operation, req.UserInfo)
log.Printf("Object: %v", string(req.Object.Raw))
log.Printf("OldObject: %v", string(req.OldObject.Raw))
log.Debugf("Object: %v", string(req.Object.Raw))
log.Debugf("OldObject: %v", string(req.OldObject.Raw))

if !injectRequired(ignoredNamespaces, wh.config.Policy, &pod.ObjectMeta, injectKey, statusKey) {
log.Printf("Skipping %s/%s due to policy check", pod.Namespace, pod.Name)
log.Infof("Skipping %s/%s due to policy check", pod.Namespace, pod.Name)
return &v1beta1.AdmissionResponse{
Allowed: true,
}
Expand All @@ -338,7 +338,7 @@ func (wh *Webhook) inject(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionRespons
return toAdmissionResponse(err)
}

log.Printf("AdmissionResponse: patch=%v\n", string(patchBytes))
log.Debugf("AdmissionResponse: patch=%v\n", string(patchBytes))

reviewResponse := v1beta1.AdmissionResponse{
Allowed: true,
Expand Down Expand Up @@ -367,7 +367,7 @@ func loadConfig(injectFile string) (*WebhookConfig, error) {
return nil, err
}

log.Printf("New configuration: sha256sum %x", sha256.Sum256(data))
log.Infof("New configuration: sha256sum %x", sha256.Sum256(data))

return &c, nil
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/inject/hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -424,13 +424,13 @@ func TestRunAndServe(t *testing.T) {
var gotPatch bytes.Buffer
if len(gotReview.Response.Patch) > 0 {
if err := json.Compact(&gotPatch, gotReview.Response.Patch); err != nil {
t.Fatalf(err.Error())
t.Fatal(err.Error())
}
}
var wantPatch bytes.Buffer
if len(c.wantPatch) > 0 {
if err := json.Compact(&wantPatch, c.wantPatch); err != nil {
t.Fatalf(err.Error())
t.Fatal(err.Error())
}
}
testutil.AssertString(t, "got bad patch", string(wantPatch.Bytes()), string(gotPatch.Bytes()))
Expand Down
Loading

0 comments on commit e8b6f2e

Please sign in to comment.