1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-16 11:09:33 +02:00
sap-jenkins-library/pkg/telemetry/telemetry.go

108 lines
2.3 KiB
Go
Raw Normal View History

2020-01-29 14:17:54 +02:00
package telemetry
import (
"crypto/sha1"
"fmt"
"os"
"time"
"net/http"
"net/url"
piperhttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/SAP/jenkins-library/pkg/log"
)
// eventType
const eventType = "library-os-ng"
// actionName
const actionName = "Piper Library OS"
// LibraryRepository that is passed into with -ldflags
var LibraryRepository string
// SiteID ...
var SiteID string
var disabled bool
var client piperhttp.Sender
// Initialize sets up the base telemetry data and is called in generated part of the steps
func Initialize(telemetryDisabled bool, stepName string) {
disabled = telemetryDisabled
// skip if telemetry is dieabled
if disabled {
log.Entry().Info("Telemetry reporting deactivated")
return
}
if client == nil {
client = &piperhttp.Client{}
}
client.SetOptions(piperhttp.ClientOptions{MaxRequestDuration: 5 * time.Second})
2020-01-29 14:17:54 +02:00
if len(LibraryRepository) == 0 {
LibraryRepository = "https://github.com/n/a"
}
if len(SiteID) == 0 {
SiteID = "827e8025-1e21-ae84-c3a3-3f62b70b0130"
}
baseData = BaseData{
URL: LibraryRepository,
ActionName: actionName,
EventType: eventType,
StepName: stepName,
SiteID: SiteID,
PipelineURLHash: getPipelineURLHash(), // http://server:port/jenkins/job/foo/
BuildURLHash: getBuildURLHash(), // http://server:port/jenkins/job/foo/15/
}
//ToDo: register Logrus Hook
}
func getPipelineURLHash() string {
return toSha1OrNA(os.Getenv("JOB_URL"))
}
func getBuildURLHash() string {
return toSha1OrNA(os.Getenv("BUILD_URL"))
}
func toSha1OrNA(input string) string {
if len(input) == 0 {
return "n/a"
}
return fmt.Sprintf("%x", sha1.Sum([]byte(input)))
}
// SWA baseURL
const baseURL = "https://webanalytics.cfapps.eu10.hana.ondemand.com"
// SWA endpoint
const endpoint = "/tracker/log"
// Send ...
func Send(customData *CustomData) {
data := Data{
BaseData: baseData,
BaseMetaData: baseMetaData,
CustomData: *customData,
}
// skip if telemetry is dieabled
if disabled {
return
}
request, _ := url.Parse(baseURL)
request.Path = endpoint
request.RawQuery = data.toPayloadString()
log.Entry().WithField("request", request.String()).Debug("Sending telemetry data")
client.SendRequest(http.MethodGet, request.String(), nil, nil, nil)
}