@@ -3,6 +3,7 @@ package advise
33import (
44 "context"
55 "fmt"
6+ "os"
67
78 "github.com/sourcegraph/sourcegraph/lib/errors"
89 "github.com/sourcegraph/src-cli/internal/scout"
@@ -24,6 +25,7 @@ func K8s(
2425 Namespace : "default" ,
2526 Pod : "" ,
2627 Container : "" ,
28+ Output : "" ,
2729 Spy : false ,
2830 Docker : false ,
2931 RestConfig : restConfig ,
@@ -64,6 +66,11 @@ func K8s(
6466 return nil
6567}
6668
69+ // Advise generates resource allocation advice for a Kubernetes pod.
70+ // The function fetches usage metrics for each container in the pod. It then
71+ // checks the usage percentages against thresholds to determine if more or less
72+ // of a resource is needed. Advice is generated and either printed to the console
73+ // or output to a file depending on the cfg.Output field.
6774func Advise (ctx context.Context , cfg * scout.Config , pod v1.Pod ) error {
6875 var advice []string
6976 usageMetrics , err := getUsageMetrics (ctx , cfg , pod )
@@ -83,15 +90,39 @@ func Advise(ctx context.Context, cfg *scout.Config, pod v1.Pod) error {
8390 advice = append (advice , storageAdvice )
8491 }
8592
86- fmt .Println (scout .EmojiFingerPointRight , pod .Name )
87- for _ , msg := range advice {
88- fmt .Println (msg )
93+ if cfg .Output != "" {
94+ outputToFile (ctx , cfg , pod , advice )
95+ } else {
96+ for _ , msg := range advice {
97+ fmt .Println (msg )
98+ }
8999 }
90100 }
91101
92102 return nil
93103}
94104
105+ // outputToFile writes resource allocation advice for a Kubernetes pod to a file.
106+ func outputToFile (ctx context.Context , cfg * scout.Config , pod v1.Pod , advice []string ) error {
107+ file , err := os .OpenFile (cfg .Output , os .O_APPEND | os .O_CREATE | os .O_WRONLY , 0644 )
108+ if err != nil {
109+ return errors .Wrap (err , "failed to open file" )
110+ }
111+ defer file .Close ()
112+
113+ if _ , err := file .WriteString (fmt .Sprintf ("- %s\n " , pod .Name )); err != nil {
114+ return errors .Wrap (err , "failed to write pod name to file" )
115+ }
116+
117+ for _ , msg := range advice {
118+ if _ , err := file .WriteString (fmt .Sprintf ("%s\n " , msg )); err != nil {
119+ return errors .Wrap (err , "failed to write container advice to file" )
120+ }
121+ }
122+ return nil
123+ }
124+
125+ // getUsageMetrics generates resource usage statistics for containers in a Kubernetes pod.
95126func getUsageMetrics (ctx context.Context , cfg * scout.Config , pod v1.Pod ) ([]scout.UsageStats , error ) {
96127 var usages []scout.UsageStats
97128 var usage scout.UsageStats
0 commit comments