SUSE/stratos

View on GitHub
src/jetstream/plugins/analysis/container/sonobuoy.go_

Summary

Maintainability
Test Coverage
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
    "os/exec"
    "path/filepath"
    "strings"
    "time"

    "github.com/cloudfoundry-incubator/stratos/src/jetstream/plugins/analysis/store"
    log "github.com/sirupsen/logrus"
)

func runSonobuoy(dbStore store.AnalysisStore, kubeconfig, folder string, report store.AnalysisRecord, body []byte) error {
    path := ""
    namespace := ""
    options := &popeyeConfig{}
    if err := json.Unmarshal(body, options); err == nil {
        namespace = options.Namespace
        path = namespace

        if len(options.App) > 0 {
            path = fmt.Sprintf("%s/%s", path, options.App)
        }
    }
    report.Name = "Sonobuoy cluster analysis"
    report.Type = "sonobuoy"
    report.Format = "junit"

    scriptPath := filepath.Join(getScriptFolder(), "sonobuoy-runner.sh")
    args := []string{scriptPath, kubeconfig, namespace}
    log.Error(scriptPath)

    report.Path = path
    parts := len(strings.Split(path, "/"))
    if parts == 2 {
        report.Name = fmt.Sprintf("Sonobuoy workload analysis: %s in %s", options.App, namespace)
    } else if parts == 1 && len(namespace) > 0 {
        report.Name = fmt.Sprintf("Sonobuoy namespace analysis: %s", namespace)
    }

    _, err := dbStore.Save(report)
    if err != nil {
        return err
    }

    go func() {
        // Use our custom script which is a wrapper around kubescore
        cmd := exec.Command("bash", args...)
        cmd.Dir = folder
        cmd.Env = make([]string, 0)
        cmd.Env = append(cmd.Env, fmt.Sprintf("KUBECONFIG=%s", kubeconfig))
        log.Info(kubeconfig)

        start := time.Now()
        out, err := cmd.Output()
        end := time.Now()

        // Remove the config file when we are done
        //os.Remove(kubeconfig)

        if err != nil {
            // There was an error
            // Remove the folder
            os.Remove(folder)
            log.Error(">>>>>>>>> ERROR <<<<<<<<<")
            log.Error(string(out))
            log.Error(err)
            report.Status = "error"
        } else {
            report.Status = "completed"

            // Parse the report
            // if summary, err := parsePopeyeReport(reportFile); err == nil {
            //     report.Result = serializePopeyeReport(summary)
            // }

            // Write stdout to log file
            reportFile := filepath.Join(folder, "report.log")
            ioutil.WriteFile(reportFile, out, os.ModePerm)
        }

        report.Duration = int(end.Sub(start).Seconds())

        dbStore.UpdateReport(report.UserID, &report)
    }()

    return nil
}