Skip to content

Commit

Permalink
feat: unified cmd and api
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Schuetz <thomas.schuetz@t-sc.eu>
  • Loading branch information
thschue committed Apr 13, 2023
1 parent adae2ef commit 9157d4d
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 115 deletions.
55 changes: 2 additions & 53 deletions cmd/analyze/analyze.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
package analyze

import (
"context"
"fmt"
"os"

"github.com/fatih/color"
"github.com/k8sgpt-ai/k8sgpt/pkg/ai"
"github.com/k8sgpt-ai/k8sgpt/pkg/analysis"
"github.com/k8sgpt-ai/k8sgpt/pkg/kubernetes"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
Expand All @@ -33,60 +29,13 @@ var AnalyzeCmd = &cobra.Command{
provide you with a list of issues that need to be resolved`,
Run: func(cmd *cobra.Command, args []string) {

// get ai configuration
var configAI ai.AIConfiguration
err := viper.UnmarshalKey("ai", &configAI)
// AnalysisResult configuration
config, err := analysis.NewAnalysis(backend, language, filters, namespace, nocache, explain)
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
}

if len(configAI.Providers) == 0 {
color.Red("Error: AI provider not specified in configuration. Please run k8sgpt auth")
os.Exit(1)
}

var aiProvider ai.AIProvider
for _, provider := range configAI.Providers {
if backend == provider.Name {
aiProvider = provider
break
}
}

if aiProvider.Name == "" {
color.Red("Error: AI provider %s not specified in configuration. Please run k8sgpt auth", backend)
os.Exit(1)
}

aiClient := ai.NewClient(aiProvider.Name)
if err := aiClient.Configure(aiProvider.Password, aiProvider.Model, language); err != nil {
color.Red("Error: %v", err)
os.Exit(1)
}

ctx := context.Background()
// Get kubernetes client from viper

kubecontext := viper.GetString("kubecontext")
kubeconfig := viper.GetString("kubeconfig")
client, err := kubernetes.NewClient(kubecontext, kubeconfig)
if err != nil {
color.Red("Error initialising kubernetes client: %v", err)
os.Exit(1)
}

// AnalysisResult configuration
config := &analysis.Analysis{
Namespace: namespace,
NoCache: nocache,
Filters: filters,
Explain: explain,
AIClient: aiClient,
Client: client,
Context: ctx,
}

err = config.RunAnalysis()
if err != nil {
color.Red("Error: %v", err)
Expand Down
2 changes: 0 additions & 2 deletions cmd/serve/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ var ServeCmd = &cobra.Command{
Token: token,
}

fmt.Println(server)

err := server.Serve()
if err != nil {
color.Red("Error: %v", err)
Expand Down
6 changes: 4 additions & 2 deletions pkg/ai/noopai.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/base64"
"fmt"
"github.com/fatih/color"
"github.com/k8sgpt-ai/k8sgpt/pkg/util"
"github.com/spf13/viper"
"strings"
)
Expand Down Expand Up @@ -33,15 +34,16 @@ func (a *NoOpAIClient) Parse(ctx context.Context, prompt []string, nocache bool)
inputKey := strings.Join(prompt, " ")
// Check for cached data
sEnc := base64.StdEncoding.EncodeToString([]byte(inputKey))
cacheKey := util.GetCacheKey(a.GetName(), sEnc)

response, err := a.GetCompletion(ctx, inputKey)
if err != nil {
color.Red("error getting completion: %v", err)
return "", err
}

if !viper.IsSet(sEnc) {
viper.Set(sEnc, base64.StdEncoding.EncodeToString([]byte(response)))
if !viper.IsSet(cacheKey) {
viper.Set(cacheKey, base64.StdEncoding.EncodeToString([]byte(response)))
if err := viper.WriteConfig(); err != nil {
color.Red("error writing config: %v", err)
return "", nil
Expand Down
10 changes: 6 additions & 4 deletions pkg/ai/openai.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/base64"
"errors"
"fmt"
"github.com/k8sgpt-ai/k8sgpt/pkg/util"
"strings"

"github.com/fatih/color"
Expand Down Expand Up @@ -58,10 +59,11 @@ func (a *OpenAIClient) Parse(ctx context.Context, prompt []string, nocache bool)
inputKey := strings.Join(prompt, " ")
// Check for cached data
sEnc := base64.StdEncoding.EncodeToString([]byte(inputKey))
cacheKey := util.GetCacheKey(a.GetName(), sEnc)
// find in viper cache
if viper.IsSet(sEnc) && !nocache {
if viper.IsSet(cacheKey) && !nocache {
// retrieve data from cache
response := viper.GetString(sEnc)
response := viper.GetString(cacheKey)
if response == "" {
color.Red("error retrieving cached data")
return "", nil
Expand All @@ -79,8 +81,8 @@ func (a *OpenAIClient) Parse(ctx context.Context, prompt []string, nocache bool)
return "", err
}

if !viper.IsSet(sEnc) {
viper.Set(sEnc, base64.StdEncoding.EncodeToString([]byte(response)))
if !viper.IsSet(cacheKey) || nocache {
viper.Set(cacheKey, base64.StdEncoding.EncodeToString([]byte(response)))
if err := viper.WriteConfig(); err != nil {
color.Red("error writing config: %v", err)
return "", nil
Expand Down
56 changes: 55 additions & 1 deletion pkg/analysis/analysis.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"

"github.com/fatih/color"
Expand Down Expand Up @@ -41,8 +42,61 @@ type JsonOutput struct {
Results []common.Result `json:"results"`
}

func (a *Analysis) RunAnalysis() error {
func NewAnalysis(backend string, language string, filters []string, namespace string, noCache bool, explain bool) (*Analysis, error) {
var configAI ai.AIConfiguration
err := viper.UnmarshalKey("ai", &configAI)
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
}

if len(configAI.Providers) == 0 {
color.Red("Error: AI provider not specified in configuration. Please run k8sgpt auth")
os.Exit(1)
}

var aiProvider ai.AIProvider
for _, provider := range configAI.Providers {
if backend == provider.Name {
aiProvider = provider
break
}
}

if aiProvider.Name == "" {
color.Red("Error: AI provider %s not specified in configuration. Please run k8sgpt auth", backend)
return nil, errors.New("AI provider not specified in configuration")
}

aiClient := ai.NewClient(aiProvider.Name)
if err := aiClient.Configure(aiProvider.Password, aiProvider.Model, language); err != nil {
color.Red("Error: %v", err)
return nil, err
}

ctx := context.Background()
// Get kubernetes client from viper

kubecontext := viper.GetString("kubecontext")
kubeconfig := viper.GetString("kubeconfig")
client, err := kubernetes.NewClient(kubecontext, kubeconfig)
if err != nil {
color.Red("Error initialising kubernetes client: %v", err)
return nil, err
}

return &Analysis{
Context: ctx,
Filters: filters,
Client: client,
AIClient: aiClient,
Namespace: namespace,
NoCache: noCache,
Explain: explain,
}, nil
}

func (a *Analysis) RunAnalysis() error {
activeFilters := viper.GetStringSlice("active_filters")

analyzerMap := analyzer.GetAnalyzerMap()
Expand Down
56 changes: 3 additions & 53 deletions pkg/server/main.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
package server

import (
"context"
"fmt"
"github.com/fatih/color"
"github.com/k8sgpt-ai/k8sgpt/pkg/ai"
"github.com/k8sgpt-ai/k8sgpt/pkg/analysis"
"github.com/k8sgpt-ai/k8sgpt/pkg/kubernetes"
"github.com/spf13/viper"
"net/http"
"os"
)
Expand All @@ -31,56 +27,9 @@ func (s *K8sGPTServer) analyzeHandler(w http.ResponseWriter, r *http.Request) {
nocache := getBoolParam(r.URL.Query().Get("nocache"))
language := r.URL.Query().Get("language")

// get ai configuration
var configAI ai.AIConfiguration
err := viper.UnmarshalKey("ai", &configAI)
config, err := analysis.NewAnalysis(s.Backend, language, []string{}, namespace, nocache, explain)
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
}

if len(configAI.Providers) == 0 {
color.Red("Error: AI provider not specified in configuration. Please run k8sgpt auth")
os.Exit(1)
}

var aiProvider ai.AIProvider
for _, provider := range configAI.Providers {
if s.Backend == provider.Name {
aiProvider = provider
break
}
}

if aiProvider.Name == "" {
color.Red("Error: AI provider %s not specified in configuration. Please run k8sgpt auth", s.Backend)
os.Exit(1)
}

aiClient := ai.NewClient(aiProvider.Name)
if err := aiClient.Configure(aiProvider.Password, aiProvider.Model, language); err != nil {
color.Red("Error: %v", err)
os.Exit(1)
}

ctx := context.Background()
// Get kubernetes client from viper

kubecontext := viper.GetString("kubecontext")
kubeconfig := viper.GetString("kubeconfig")
client, err := kubernetes.NewClient(kubecontext, kubeconfig)
if err != nil {
color.Red("Error initialising kubernetes client: %v", err)
os.Exit(1)
}

config := &analysis.Analysis{
Namespace: namespace,
Explain: explain,
AIClient: aiClient,
Client: client,
Context: ctx,
NoCache: nocache,
fmt.Fprintf(w, err.Error())
}

err = config.RunAnalysis()
Expand Down Expand Up @@ -108,6 +57,7 @@ func (s *K8sGPTServer) analyzeHandler(w http.ResponseWriter, r *http.Request) {

func (s *K8sGPTServer) Serve() error {
http.HandleFunc("/analyze", s.analyzeHandler)
color.Green("Starting server on port " + s.Port)
err := http.ListenAndServe(":"+s.Port, nil)
if err != nil {
fmt.Printf("error starting server: %s\n", err)
Expand Down
4 changes: 4 additions & 0 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,7 @@ func ReplaceIfMatch(text string, pattern string, replacement string) string {
}
return text
}

func GetCacheKey(provider string, sEnc string) string {
return fmt.Sprintf("%s-%s", provider, sEnc)
}

0 comments on commit 9157d4d

Please sign in to comment.