RIC:1060: Change in PTL
[ric-plt/xapp-frame.git] / pkg / xapp / restapi.go
index 00f8aba..2cdee59 100755 (executable)
@@ -20,6 +20,7 @@
 package xapp
 
 import (
+       "bytes"
        "encoding/json"
        "fmt"
        "io/ioutil"
@@ -27,11 +28,13 @@ import (
        "os"
        "path"
        "strings"
+       "time"
 
+       "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/models"
        "github.com/gorilla/mux"
+       "github.com/prometheus/client_golang/prometheus"
+       "github.com/prometheus/common/expfmt"
        "github.com/spf13/viper"
-
-       "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/models"
 )
 
 const (
@@ -137,19 +140,32 @@ func (r *Router) CollectDefaultSymptomData(fileName string, data interface{}) st
        }
 
        //
-       if metrics, err := r.GetLocalMetrics(GetPortData("http").Port); err == nil {
+       // Collect some general information into one file
+       //
+       var lines []string
+
+       // uptime
+       d := XappUpTime()
+       h := d / time.Hour
+       d -= h * time.Hour
+       m := d / time.Minute
+       d -= m * time.Minute
+       s := d / time.Second
+       lines = append(lines, fmt.Sprintf("uptime: %02d:%02d:%02d", h, m, s))
+
+       Util.WriteToFile(baseDir+"information.txt", strings.Join(lines, "\n"))
+
+       //
+       // Collect metrics
+       //
+       if metrics, err := r.GetLocalMetrics(); err == nil {
                if err := Util.WriteToFile(baseDir+"metrics.json", metrics); err != nil {
                        Logger.Error("writeToFile failed for metrics.json: %v", err)
                }
        }
 
        //
-       if data != nil {
-               if b, err := json.MarshalIndent(data, "", "  "); err == nil {
-                       Util.WriteToFile(baseDir+fileName, string(b))
-               }
-       }
-
+       // Collect currently used config file
        //
        cfile := viper.ConfigFileUsed()
        input, err := ioutil.ReadFile(cfile)
@@ -160,8 +176,12 @@ func (r *Router) CollectDefaultSymptomData(fileName string, data interface{}) st
        }
 
        //
-       Util.WriteToFile(baseDir+"environment", strings.Join(os.Environ(), "\n"))
+       // Collect environment
+       //
+       Util.WriteToFile(baseDir+"environment.txt", strings.Join(os.Environ(), "\n"))
 
+       //
+       // Collect RMR rt table
        //
        rtPath := os.Getenv("RMR_STASH_RT")
        if rtPath != "" {
@@ -173,6 +193,15 @@ func (r *Router) CollectDefaultSymptomData(fileName string, data interface{}) st
                }
        }
 
+       //
+       // Put data that was provided as argument
+       //
+       if data != nil {
+               if b, err := json.MarshalIndent(data, "", "  "); err == nil {
+                       Util.WriteToFile(baseDir+fileName, string(b))
+               }
+       }
+
        return baseDir
 }
 
@@ -206,23 +235,30 @@ func (r *Router) SendSymptomDataError(w http.ResponseWriter, req *http.Request,
        http.Error(w, message, http.StatusInternalServerError)
 }
 
-func (r *Router) GetLocalMetrics(port int) (string, error) {
-       resp, err := http.Get(fmt.Sprintf("http://localhost:%d/ric/v1/metrics", port))
+func (r *Router) GetLocalMetrics() (string, error) {
+       buf := &bytes.Buffer{}
+       enc := expfmt.NewEncoder(buf, expfmt.FmtText)
+       vals, err := prometheus.DefaultGatherer.Gather()
        if err != nil {
-               Logger.Error("GetLocalMetrics: http.Get failed: %v", err)
-               return "", err
+               return fmt.Sprintf("#metrics get error: %s\n", err.Error()), fmt.Errorf("Could get local metrics %w", err)
        }
-       defer resp.Body.Close()
-
-       metrics, err := ioutil.ReadAll(resp.Body)
-       if err != nil {
-               Logger.Error("GetLocalMetrics: ioutil.ReadAll failed: %v", err)
-               return "", err
+       for _, val := range vals {
+               err = enc.Encode(val)
+               if err != nil {
+                       buf.WriteString(fmt.Sprintf("#metrics enc err:%s\n", err.Error()))
+               }
        }
-
-       return string(metrics), nil
+       return string(buf.Bytes()), nil
 }
 
+//Resource.InjectRoute(url, metricsHandler, "GET")
+//func metricsHandler(w http.ResponseWriter, r *http.Request) {
+//     w.Header().Set("Content-Type", "text/plain")
+//     w.WriteHeader(http.StatusOK)
+//     metrics, _ := Resource.GetLocalMetrics()
+//     w.Write([]byte(metrics))
+//}
+
 func IsHealthProbeReady() bool {
        return healthReady
 }
@@ -280,15 +316,25 @@ func appconfigHandler(w http.ResponseWriter, r *http.Request) {
        metadata.XappName = &name
        metadata.ConfigType = &configtype
 
-       configFile, err := os.Open("/opt/ric/config/config-file.json")
-       if err != nil {
-               Logger.Error("Cannot open config file: %v", err)
+       // Read config-files
+       cfiles := []string{viper.ConfigFileUsed(), "/opt/ric/config/config-file.json"}
+
+       var err error
+       var configFile *os.File
+       for _, cfile := range cfiles {
+               configFile, err = os.Open(cfile)
+               if err != nil {
+                       configFile = nil
+                       Logger.Error("Cannot open config file: %s err: %v", cfile, err)
+               }
+       }
+       if err != nil || configFile == nil {
+               Logger.Error("Cannot open any of listed config files: %v", cfiles)
                respondWithJSON(w, http.StatusInternalServerError, nil)
-               // return nil,errors.New("Could Not parse the config file")
+               return
        }
 
        body, err := ioutil.ReadAll(configFile)
-
        defer configFile.Close()
 
        xappconfig.Metadata = &metadata
@@ -297,6 +343,4 @@ func appconfigHandler(w http.ResponseWriter, r *http.Request) {
        appconfig = append(appconfig, &xappconfig)
 
        respondWithJSON(w, http.StatusOK, appconfig)
-
-       //return appconfig,nil
 }