Skip to content

Commit

Permalink
feat: add GWClient
Browse files Browse the repository at this point in the history
  • Loading branch information
VladislavSenkevich committed Nov 29, 2021
1 parent 793a849 commit 57c225f
Showing 1 changed file with 34 additions and 86 deletions.
120 changes: 34 additions & 86 deletions plugins/outputs/groundwork/groundwork.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
package groundwork

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"

"github.com/gwos/tcg/sdk/clients"
"github.com/gwos/tcg/sdk/transit"
"github.com/hashicorp/go-uuid"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/outputs"
)

const (
defaultMonitoringRoute = "/api/monitoring?dynamic=true"
)

// Login and logout routes from Groundwork API
const (
loginURL = "/api/auth/login"
Expand Down Expand Up @@ -49,16 +44,15 @@ const (
)

type Groundwork struct {
Server string `toml:"url"`
AgentID string `toml:"agent_id"`
Username string `toml:"username"`
Password string `toml:"password"`
DefaultHost string `toml:"default_host"`
DefaultServiceState string `toml:"default_service_state"`
ResourceTag string `toml:"resource_tag"`
Log telegraf.Logger `toml:"-"`

authToken string
Server string `toml:"url"`
AgentID string `toml:"agent_id"`
Username string `toml:"username"`
Password string `toml:"password"`
DefaultHost string `toml:"default_host"`
DefaultServiceState string `toml:"default_service_state"`
ResourceTag string `toml:"resource_tag"`
Log telegraf.Logger `toml:"-"`
GWClient clients.GWClient `toml:"-"`
}

func (g *Groundwork) SampleConfig() string {
Expand Down Expand Up @@ -88,43 +82,45 @@ func (g *Groundwork) Init() error {
return errors.New("invalid 'default_service_state' provided")
}

g.GWClient = clients.GWClient{
AppName: "telegraf",
AppType: "TELEGRAF",
GWConnection: &clients.GWConnection{
HostName: g.Server,
UserName: g.Username,
Password: g.Password,
SendAllInventory: true,
IsDynamicInventory: true,
},
}
return nil
}

func (g *Groundwork) Connect() error {
byteToken, err := login(g.Server+loginURL, g.Username, g.Password)
err := g.GWClient.Connect()
if err != nil {
return fmt.Errorf("could not log in at %s: %v", g.Server+loginURL, err)
}

g.authToken = string(byteToken)

return nil
}

func (g *Groundwork) Close() error {
formValues := map[string]string{
"gwos-app-name": "telegraf",
"gwos-api-token": g.authToken,
}

headers := map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": internal.ProductToken(),
}

if _, _, err := clients.SendRequest(http.MethodPost, g.Server+logoutURL, headers, formValues, nil); err != nil {
err := g.GWClient.Disconnect()
if err != nil {
return fmt.Errorf("could not log out at %s: %v", g.Server+logoutURL, err)
}

return nil
}

func (g *Groundwork) Write(metrics []telegraf.Metric) error {
resourceToServicesMap := make(map[string][]transit.DynamicMonitoredService)
for _, metric := range metrics {
resource, service := g.parseMetric(metric)
resourceToServicesMap[resource] = append(resourceToServicesMap[resource], service)
resource, service, err := g.parseMetric(metric)
if err != nil {
g.Log.Errorf("%v", err)
continue
}
resourceToServicesMap[resource] = append(resourceToServicesMap[resource], *service)
}

var resources []transit.DynamicMonitoredResource
Expand Down Expand Up @@ -162,35 +158,11 @@ func (g *Groundwork) Write(metrics []telegraf.Metric) error {
return err
}

headers := map[string]string{
"GWOS-APP-NAME": "telegraf",
"GWOS-API-TOKEN": g.authToken,
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": internal.ProductToken(),
}

statusCode, body, err := clients.SendRequest(http.MethodPost, g.Server+defaultMonitoringRoute, headers, nil, requestJSON)
_, err = g.GWClient.SendResourcesWithMetrics(context.Background(), requestJSON)
if err != nil {
return fmt.Errorf("error while sending: %v", err)
}

/* Re-login mechanism */
if statusCode == 401 {
if err = g.Connect(); err != nil {
return fmt.Errorf("re-login failed: %v", err)
}
headers["GWOS-API-TOKEN"] = g.authToken
statusCode, body, err = clients.SendRequest(http.MethodPost, g.Server+defaultMonitoringRoute, headers, nil, requestJSON)
if err != nil {
return fmt.Errorf("error while sending: %v", err)
}
}

if statusCode != 200 {
return fmt.Errorf("HTTP request failed. [Status code]: %d, [Response]: %s", statusCode, string(body))
}

return nil
}

Expand All @@ -208,7 +180,7 @@ func init() {
})
}

func (g *Groundwork) parseMetric(metric telegraf.Metric) (string, transit.DynamicMonitoredService) {
func (g *Groundwork) parseMetric(metric telegraf.Metric) (string, *transit.DynamicMonitoredService, error) {
resource := g.DefaultHost
if value, present := metric.GetTag(g.ResourceTag); present {
resource = value
Expand Down Expand Up @@ -288,8 +260,7 @@ func (g *Groundwork) parseMetric(metric telegraf.Metric) (string, transit.Dynami
typedValue := new(transit.TypedValue)
err := typedValue.FromInterface(value.Value)
if err != nil {
typedValue = nil
g.Log.Errorf("%v", err)
return "", nil, err
}

serviceObject.Metrics = append(serviceObject.Metrics, transit.TimeSeries{
Expand All @@ -313,30 +284,7 @@ func (g *Groundwork) parseMetric(metric telegraf.Metric) (string, transit.Dynami
serviceObject.Status = serviceStatus
}

return resource, serviceObject
}

func login(url, username, password string) ([]byte, error) {
formValues := map[string]string{
"user": username,
"password": password,
"gwos-app-name": "telegraf",
}
headers := map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
"User-Agent": internal.ProductToken(),
}

statusCode, body, err := clients.SendRequest(http.MethodPost, url, headers, formValues, nil)
if err != nil {
return nil, err
}
if statusCode != 200 {
return nil, fmt.Errorf("request failed with status-code %d: %v", statusCode, string(body))
}

return body, nil
return resource, &serviceObject, nil
}

func validStatus(status string) bool {
Expand Down

0 comments on commit 57c225f

Please sign in to comment.