- 
                Notifications
    
You must be signed in to change notification settings  - Fork 8
 
feat(logging): add dynamic logging CLI and management API #173
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            bomanaps
  wants to merge
  11
  commits into
  storacha:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
bomanaps:feature/dynamic-logging
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from 3 commits
      Commits
    
    
            Show all changes
          
          
            11 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      42a6e46
              
                feat(logging): add dynamic logging CLI and management API
              
              
                bomanaps 1bf9045
              
                update to review comment and add unit test
              
              
                bomanaps 927c6bc
              
                feat: Restore cmd/cli/client and re-integrate client.Cmd
              
              
                bomanaps 5590b19
              
                move log cmd, cleanup and revert
              
              
                bomanaps 504ab43
              
                Merge remote-tracking branch 'origin/main' into feature/dynamic-logging
              
              
                bomanaps b396104
              
                Merge branch 'storacha:main' into feature/dynamic-logging
              
              
                bomanaps 389ec77
              
                add unit test for command logging
              
              
                bomanaps f94744e
              
                Merge branch 'main' into feature/dynamic-logging
              
              
                bomanaps f4efb6d
              
                consolidate logging endpoints
              
              
                bomanaps 3707f2a
              
                Merge branch 'storacha:main' into feature/dynamic-logging
              
              
                bomanaps 7402119
              
                Run go mod tidy to match CI expectations
              
              
                bomanaps File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package client | ||
| 
     | 
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| 
     | 
||
| "github.com/spf13/viper" | ||
| ) | ||
| 
     | 
||
| func SetLogLevel(ctx context.Context, subsystem, level string) error { | ||
| url := fmt.Sprintf("http://%s/log/level", viper.GetString("manage_api")) | ||
| jsonStr, err := json.Marshal(map[string]string{"subsystem": subsystem, "level": level}) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| 
     | 
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| req.Header.Set("Content-Type", "application/json") | ||
| 
     | 
||
| client := &http.Client{} | ||
| resp, err := client.Do(req) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer resp.Body.Close() | ||
| 
     | 
||
| if resp.StatusCode != http.StatusOK { | ||
| return fmt.Errorf("failed to set log level: %s", resp.Status) | ||
| } | ||
| 
     | 
||
| return nil | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| package cli | ||
| 
     | 
||
| import ( | ||
| "fmt" | ||
| 
     | 
||
| "github.com/spf13/cobra" | ||
| "github.com/storacha/piri/cmd/cliutil" | ||
| "github.com/storacha/piri/pkg/admin" | ||
| ) | ||
| 
     | 
||
| func NewLogCmd() *cobra.Command { | ||
| logCmd := &cobra.Command{ | ||
| Use: "log", | ||
| Short: "Manage logging subsystems and levels", | ||
| } | ||
| logCmd.PersistentFlags().String("manage-api", "127.0.0.1:8888", "Management API address") | ||
| 
     | 
||
| logListCmd := &cobra.Command{ | ||
| Use: "list", | ||
| Short: "List all logging subsystems and their levels", | ||
| Args: cobra.NoArgs, | ||
| RunE: func(cmd *cobra.Command, _ []string) error { | ||
| client := admin.NewClient(cliutil.MustGetManageAPI(cmd)) | ||
| resp, err := client.ListLogLevels(cmd.Context()) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| 
     | 
||
| for subsystem, level := range resp.Levels { | ||
| fmt.Printf("%-30s %s\n", subsystem, level) | ||
                
      
                  bomanaps marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| } | ||
| 
     | 
||
| return nil | ||
| }, | ||
| } | ||
| 
     | 
||
| logSetLevelCmd := &cobra.Command{ | ||
| Use: "set-level <level>", | ||
| Short: "Set log level for a subsystem or all subsystems", | ||
| Args: cobra.ExactArgs(1), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| level := args[0] | ||
| systems, err := cmd.Flags().GetStringSlice("system") | ||
| if err != nil { | ||
| return err | ||
| } | ||
| 
     | 
||
| client := admin.NewClient(cliutil.MustGetManageAPI(cmd)) | ||
| 
     | 
||
| if len(systems) == 0 { | ||
| // If no systems are specified, get all of them and set the level | ||
| resp, err := client.ListLogLevels(cmd.Context()) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| for subsystem := range resp.Levels { | ||
| if err := client.SetLogLevel(cmd.Context(), subsystem, level); err != nil { | ||
| return err | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
| 
     | 
||
| for _, system := range systems { | ||
| if err := client.SetLogLevel(cmd.Context(), system, level); err != nil { | ||
| return err | ||
| } | ||
| } | ||
| 
     | 
||
| return nil | ||
| }, | ||
| } | ||
| 
     | 
||
| logCmd.AddCommand(logListCmd) | ||
| logCmd.AddCommand(logSetLevelCmd) | ||
| logSetLevelCmd.Flags().StringSlice("system", []string{}, "Subsystem to target. Pass multiple times for multiple systems.") | ||
| 
     | 
||
| return logCmd | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| 
     | 
||
| package cli | ||
| 
     | 
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "strings" | ||
| "testing" | ||
| 
     | 
||
| "github.com/spf13/cobra" | ||
| "github.com/stretchr/testify/require" | ||
| "github.com/storacha/piri/pkg/admin" | ||
| ) | ||
| 
     | 
||
| func TestLogListCmd(t *testing.T) { | ||
| expected := map[string]string{ | ||
| "system1": "INFO", | ||
| "system2": "DEBUG", | ||
| } | ||
| 
     | 
||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| require.Equal(t, "/log/level", r.URL.Path) | ||
| require.Equal(t, http.MethodGet, r.Method) | ||
| 
     | 
||
| resp := admin.ListLogLevelsResponse{ | ||
| Levels: expected, | ||
| } | ||
| json.NewEncoder(w).Encode(resp) | ||
| })) | ||
| defer server.Close() | ||
| 
     | 
||
| // capture stdout | ||
| old := os.Stdout | ||
| r, w, _ := os.Pipe() | ||
| os.Stdout = w | ||
| 
     | 
||
| rootCmd.SetArgs([]string{"log", "list", "--manage-api", strings.TrimPrefix(server.URL, "http://")}) | ||
| require.NoError(t, rootCmd.Execute()) | ||
| 
     | 
||
| // restore stdout | ||
| w.Close() | ||
| os.Stdout = old | ||
| 
     | 
||
| var out bytes.Buffer | ||
| io.Copy(&out, r) | ||
| 
     | 
||
| for k, v := range expected { | ||
| require.Contains(t, out.String(), k) | ||
| require.Contains(t, out.String(), v) | ||
| } | ||
| } | ||
| 
     | 
||
| func TestLogSetLevelCmd(t *testing.T) { | ||
| t.Run("sets level for a single system", func(t *testing.T) { | ||
| rootCmd := newRootCmd() | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| require.Equal(t, "/log/level", r.URL.Path) | ||
| require.Equal(t, http.MethodPost, r.Method) | ||
| 
     | 
||
| var req admin.SetLogLevelRequest | ||
| json.NewDecoder(r.Body).Decode(&req) | ||
| 
     | 
||
| require.Equal(t, "system1", req.Subsystem) | ||
| require.Equal(t, "DEBUG", req.Level) | ||
| })) | ||
| defer server.Close() | ||
| 
     | 
||
| rootCmd.SetArgs([]string{"log", "set-level", "--system", "system1", "DEBUG", "--manage-api", strings.TrimPrefix(server.URL, "http://")}) | ||
| require.NoError(t, rootCmd.Execute()) | ||
| }) | ||
| 
     | 
||
| t.Run("sets level for multiple systems", func(t *testing.T) { | ||
| rootCmd := newRootCmd() | ||
| requests := 0 | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| requests++ | ||
| require.Equal(t, "/log/level", r.URL.Path) | ||
| require.Equal(t, http.MethodPost, r.Method) | ||
| 
     | 
||
| var req admin.SetLogLevelRequest | ||
| json.NewDecoder(r.Body).Decode(&req) | ||
| 
     | 
||
| require.Contains(t, []string{"system1", "system2"}, req.Subsystem) | ||
| require.Equal(t, "WARN", req.Level) | ||
| })) | ||
| defer server.Close() | ||
| 
     | 
||
| rootCmd.SetArgs([]string{"log", "set-level", "--system", "system1", "--system", "system2", "WARN", "--manage-api", strings.TrimPrefix(server.URL, "http://")}) | ||
| require.NoError(t, rootCmd.Execute()) | ||
| require.Equal(t, 2, requests) | ||
| }) | ||
| 
     | 
||
| t.Run("sets level for all systems", func(t *testing.T) { | ||
| rootCmd := newRootCmd() | ||
| postRequests := 0 | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| require.Equal(t, "/log/level", r.URL.Path) | ||
| 
     | 
||
| if r.Method == http.MethodGet { | ||
| resp := admin.ListLogLevelsResponse{ | ||
| Levels: map[string]string{"system1": "INFO", "system2": "INFO"}, | ||
| } | ||
| json.NewEncoder(w).Encode(resp) | ||
| return | ||
| } | ||
| 
     | 
||
| postRequests++ | ||
| require.Equal(t, http.MethodPost, r.Method) | ||
| 
     | 
||
| var req admin.SetLogLevelRequest | ||
| json.NewDecoder(r.Body).Decode(&req) | ||
| 
     | 
||
| require.Contains(t, []string{"system1", "system2"}, req.Subsystem) | ||
| require.Equal(t, "FATAL", req.Level) | ||
| })) | ||
| defer server.Close() | ||
| 
     | 
||
| rootCmd.SetArgs([]string{"log", "set-level", "FATAL", "--manage-api", strings.TrimPrefix(server.URL, "http://")}) | ||
| require.NoError(t, rootCmd.Execute()) | ||
| require.Equal(t, 2, postRequests) | ||
| }) | ||
| } | ||
| 
     | 
||
| func newRootCmd() *cobra.Command { | ||
| root := &cobra.Command{ | ||
| Use: "piri", | ||
| Short: "Piri is the software run by all storage providers on the Storacha network", | ||
| } | ||
| root.AddCommand(NewLogCmd()) | ||
| return root | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| 
          
            
          
           | 
    @@ -62,12 +62,16 @@ func init() { | |
| cobra.CheckErr(rootCmd.MarkPersistentFlagFilename("key-file", "pem")) | ||
| cobra.CheckErr(viper.BindPFlag("key_file", rootCmd.PersistentFlags().Lookup("key-file"))) | ||
| 
     | 
||
| rootCmd.PersistentFlags().String("manage-api", "127.0.0.1:8888", "Management API address") | ||
| cobra.CheckErr(viper.BindPFlag("manage_api", rootCmd.PersistentFlags().Lookup("manage-api"))) | ||
| 
     | 
||
                
       | 
||
| // register all commands and their subcommands | ||
| rootCmd.AddCommand(serve.Cmd) | ||
| rootCmd.AddCommand(wallet.Cmd) | ||
| rootCmd.AddCommand(identity.Cmd) | ||
| rootCmd.AddCommand(delegate.Cmd) | ||
| rootCmd.AddCommand(delegate.Cmd) | ||
| rootCmd.AddCommand(client.Cmd) | ||
| rootCmd.AddCommand(NewLogCmd()) | ||
                
      
                  bomanaps marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| } | ||
| 
     | 
||
| 
          
            
          
           | 
    ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.