Skip to content

Commit 4d84c98

Browse files
committed
refactoring
Signed-off-by: Markus Blaschke <mblaschke82@gmail.com>
1 parent 04d02f3 commit 4d84c98

File tree

7 files changed

+104
-70
lines changed

7 files changed

+104
-70
lines changed

config/opts.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ type (
2020
}
2121

2222
Loganalytics struct {
23-
Workspace []string `long:"loganalytics.workspace" env:"LOGANALYTICS_WORKSPACE" env-delim:" " description:"Loganalytics workspace IDs" required:"true"`
23+
Workspace []string `long:"loganalytics.workspace" env:"LOGANALYTICS_WORKSPACE" env-delim:" " description:"Loganalytics workspace IDs"`
2424
Parallel int `long:"loganalytics.parallel" env:"LOGANALYTICS_PARALLEL" description:"Specifies how many workspaces should be queried in parallel" default:"5"`
2525
}
2626

global-metrics.go renamed to loganalytics/global-metrics.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package main
1+
package loganalytics
22

33
import "github.com/prometheus/client_golang/prometheus"
44

@@ -8,7 +8,7 @@ var (
88
prometheusQueryRequests *prometheus.CounterVec
99
)
1010

11-
func initGlobalMetrics() {
11+
func InitGlobalMetrics() {
1212
prometheusQueryTime = prometheus.NewSummaryVec(
1313
prometheus.SummaryOpts{
1414
Name: "azure_loganalytics_query_time",

misc.go renamed to loganalytics/misc.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
package main
1+
package loganalytics
22

33
import (
44
"fmt"
55
"net/url"
66
"strings"
77
)
88

9-
func paramsGetList(params url.Values, name string) (list []string, err error) {
9+
func ParamsGetList(params url.Values, name string) (list []string, err error) {
1010
for _, v := range params[name] {
1111
list = append(list, strings.Split(v, ",")...)
1212
}
1313
return
1414
}
1515

16-
func paramsGetListRequired(params url.Values, name string) (list []string, err error) {
17-
list, err = paramsGetList(params, name)
16+
func ParamsGetListRequired(params url.Values, name string) (list []string, err error) {
17+
list, err = ParamsGetList(params, name)
1818

1919
if len(list) == 0 {
2020
err = fmt.Errorf("parameter \"%v\" is missing", name)

loganalytics.go renamed to loganalytics/prober.go

Lines changed: 19 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,39 @@
1-
package main
1+
package loganalytics
22

33
import (
44
"context"
55
"encoding/json"
66
"fmt"
7-
operationalinsightsProfile "github.com/Azure/azure-sdk-for-go/profiles/latest/operationalinsights/mgmt/operationalinsights"
87
"github.com/Azure/azure-sdk-for-go/services/operationalinsights/v1/operationalinsights"
98
"github.com/Azure/go-autorest/autorest"
9+
"github.com/Azure/go-autorest/autorest/azure"
1010
"github.com/Azure/go-autorest/autorest/to"
1111
"github.com/patrickmn/go-cache"
1212
"github.com/prometheus/client_golang/prometheus"
1313
"github.com/remeh/sizedwaitgroup"
1414
log "github.com/sirupsen/logrus"
15+
"github.com/webdevops/azure-loganalytics-exporter/config"
1516
"github.com/webdevops/azure-resourcegraph-exporter/kusto"
1617
"net/http"
1718
"strconv"
1819
"time"
1920
)
2021

2122
const (
22-
OPINSIGHTS_URL_SUFFIX = "/v1"
23+
OperationInsightsWorkspaceUrlSuffix = "/v1"
2324
)
2425

2526
type (
2627
LogAnalyticsProber struct {
28+
QueryConfig kusto.Config
29+
Conf config.Opts
30+
31+
Azure struct {
32+
Environment azure.Environment
33+
OpInsightsAuthorizer autorest.Authorizer
34+
AzureAuthorizer autorest.Authorizer
35+
}
36+
2737
workspaceList []string
2838

2939
request *http.Request
@@ -48,11 +58,6 @@ type (
4858
ServiceDiscovery LogAnalyticsServiceDiscovery
4959
}
5060

51-
LogAnalyticsServiceDiscovery struct {
52-
enabled bool
53-
prober *LogAnalyticsProber
54-
}
55-
5661
LogAnalyticsProbeResult struct {
5762
Name string
5863
Metrics []kusto.MetricRow
@@ -126,8 +131,8 @@ func (p *LogAnalyticsProber) AddWorkspaces(workspace ...string) {
126131

127132
func (p *LogAnalyticsProber) LogAnalyticsQueryClient() operationalinsights.QueryClient {
128133
// Create and authorize a operationalinsights client
129-
client := operationalinsights.NewQueryClientWithBaseURI(AzureEnvironment.ResourceIdentifiers.OperationalInsights + OPINSIGHTS_URL_SUFFIX)
130-
client.Authorizer = OpInsightsAuthorizer
134+
client := operationalinsights.NewQueryClientWithBaseURI(p.Azure.Environment.ResourceIdentifiers.OperationalInsights + OperationInsightsWorkspaceUrlSuffix)
135+
client.Authorizer = p.Azure.OpInsightsAuthorizer
131136
client.ResponseInspector = p.respondDecorator(nil)
132137
return client
133138
}
@@ -138,7 +143,7 @@ func (p *LogAnalyticsProber) Run() {
138143
// check if value is cached
139144
executeQuery := true
140145
if p.cache != nil && p.config.cacheEnabled {
141-
if v, ok := metricCache.Get(*p.config.cacheKey); ok {
146+
if v, ok := p.cache.Get(*p.config.cacheKey); ok {
142147
if cacheData, ok := v.([]byte); ok {
143148
if err := json.Unmarshal(cacheData, &p.metricList); err == nil {
144149
p.logger.Debug("fetched from cache")
@@ -165,7 +170,7 @@ func (p *LogAnalyticsProber) Run() {
165170
p.logger.Debug("saving metrics to cache")
166171
if cacheData, err := json.Marshal(p.metricList); err == nil {
167172
p.response.Header().Add("X-metrics-cached-until", time.Now().Add(*p.config.cacheDuration).Format(time.RFC3339))
168-
metricCache.Set(*p.config.cacheKey, cacheData, *p.config.cacheDuration)
173+
p.cache.Set(*p.config.cacheKey, cacheData, *p.config.cacheDuration)
169174
p.logger.Debugf("saved metric to cache for %s", p.config.cacheDuration.String())
170175
}
171176
}
@@ -197,7 +202,7 @@ func (p *LogAnalyticsProber) Run() {
197202
func (p *LogAnalyticsProber) executeQueries() {
198203
queryClient := p.LogAnalyticsQueryClient()
199204

200-
for _, queryRow := range Config.Queries {
205+
for _, queryRow := range p.QueryConfig.Queries {
201206
queryConfig := queryRow
202207

203208
// check if query matches module name
@@ -342,7 +347,7 @@ func (p *LogAnalyticsProber) parseCacheTime(r *http.Request) (time.Duration, err
342347
}
343348

344349
func (p *LogAnalyticsProber) NewSizedWaitGroup() sizedwaitgroup.SizedWaitGroup {
345-
size := opts.Loganalytics.Parallel
350+
size := p.Conf.Loganalytics.Parallel
346351

347352
parallelString := p.request.URL.Query().Get("parallel")
348353
if parallelString != "" {
@@ -353,46 +358,3 @@ func (p *LogAnalyticsProber) NewSizedWaitGroup() sizedwaitgroup.SizedWaitGroup {
353358

354359
return sizedwaitgroup.New(size)
355360
}
356-
357-
func (sd *LogAnalyticsServiceDiscovery) ResourcesClient(subscriptionId string) *operationalinsightsProfile.WorkspacesClient {
358-
client := operationalinsightsProfile.NewWorkspacesClientWithBaseURI(AzureEnvironment.ResourceManagerEndpoint, subscriptionId)
359-
client.Authorizer = AzureAuthorizer
360-
client.ResponseInspector = sd.prober.respondDecorator(&subscriptionId)
361-
362-
return &client
363-
}
364-
365-
func (sd *LogAnalyticsServiceDiscovery) Use() {
366-
sd.enabled = true
367-
}
368-
func (sd *LogAnalyticsServiceDiscovery) Find() {
369-
contextLogger := sd.prober.logger.WithFields(log.Fields{
370-
"type": "servicediscovery",
371-
})
372-
373-
contextLogger.Debug("requesting list for workspaces via Azure API")
374-
375-
params := sd.prober.request.URL.Query()
376-
377-
subscriptionList, _ := paramsGetList(params, "subscription")
378-
for _, subscriptionId := range subscriptionList {
379-
subscriptionLogger := contextLogger.WithFields(log.Fields{
380-
"subscription": subscriptionId,
381-
})
382-
383-
list, err := sd.ResourcesClient(subscriptionId).List(sd.prober.ctx)
384-
if err != nil {
385-
subscriptionLogger.Error(err)
386-
panic(LogAnalyticsPanicStop{Message: err.Error()})
387-
}
388-
389-
for _, val := range *list.Value {
390-
if val.CustomerID != nil {
391-
sd.prober.workspaceList = append(
392-
sd.prober.workspaceList,
393-
to.String(val.CustomerID),
394-
)
395-
}
396-
}
397-
}
398-
}

loganalytics/servicediscovery.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package loganalytics
2+
3+
import (
4+
operationalinsightsProfile "github.com/Azure/azure-sdk-for-go/profiles/latest/operationalinsights/mgmt/operationalinsights"
5+
"github.com/Azure/go-autorest/autorest/to"
6+
log "github.com/sirupsen/logrus"
7+
)
8+
9+
type (
10+
LogAnalyticsServiceDiscovery struct {
11+
enabled bool
12+
prober *LogAnalyticsProber
13+
}
14+
)
15+
16+
func (sd *LogAnalyticsServiceDiscovery) ResourcesClient(subscriptionId string) *operationalinsightsProfile.WorkspacesClient {
17+
client := operationalinsightsProfile.NewWorkspacesClientWithBaseURI(sd.prober.Azure.Environment.ResourceManagerEndpoint, subscriptionId)
18+
client.Authorizer = sd.prober.Azure.AzureAuthorizer
19+
client.ResponseInspector = sd.prober.respondDecorator(&subscriptionId)
20+
21+
return &client
22+
}
23+
24+
func (sd *LogAnalyticsServiceDiscovery) Use() {
25+
sd.enabled = true
26+
}
27+
28+
func (sd *LogAnalyticsServiceDiscovery) Find() {
29+
contextLogger := sd.prober.logger
30+
31+
contextLogger.Debug("requesting list for workspaces via Azure API")
32+
33+
params := sd.prober.request.URL.Query()
34+
35+
subscriptionList, err := ParamsGetListRequired(params, "subscription")
36+
if err != nil {
37+
contextLogger.Error(err)
38+
panic(LogAnalyticsPanicStop{Message: err.Error()})
39+
}
40+
41+
for _, subscriptionId := range subscriptionList {
42+
subscriptionLogger := contextLogger.WithFields(log.Fields{
43+
"subscription": subscriptionId,
44+
})
45+
46+
list, err := sd.ResourcesClient(subscriptionId).List(sd.prober.ctx)
47+
if err != nil {
48+
subscriptionLogger.Error(err)
49+
panic(LogAnalyticsPanicStop{Message: err.Error()})
50+
}
51+
52+
for _, val := range *list.Value {
53+
if val.CustomerID != nil {
54+
sd.prober.workspaceList = append(
55+
sd.prober.workspaceList,
56+
to.String(val.CustomerID),
57+
)
58+
}
59+
}
60+
}
61+
}

main.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"github.com/prometheus/client_golang/prometheus/promhttp"
1111
log "github.com/sirupsen/logrus"
1212
"github.com/webdevops/azure-loganalytics-exporter/config"
13+
"github.com/webdevops/azure-loganalytics-exporter/loganalytics"
1314
"github.com/webdevops/azure-resourcegraph-exporter/kusto"
1415
"net/http"
1516
"os"
@@ -45,7 +46,7 @@ func main() {
4546

4647
log.Infof("starting azure-loganalytics-exporter v%s (%s; %s; by %v)", gitTag, gitCommit, runtime.Version(), Author)
4748
log.Info(string(opts.GetJson()))
48-
initGlobalMetrics()
49+
loganalytics.InitGlobalMetrics()
4950

5051
metricCache = cache.New(120*time.Second, 60*time.Second)
5152

probe.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@ import (
44
"fmt"
55
"github.com/prometheus/client_golang/prometheus/promhttp"
66
log "github.com/sirupsen/logrus"
7+
"github.com/webdevops/azure-loganalytics-exporter/loganalytics"
78
"net/http"
89
)
910

1011
func handleProbePanic(w http.ResponseWriter, r *http.Request) {
1112
if err := recover(); err != nil {
1213
switch v := err.(type) {
13-
case LogAnalyticsPanicStop:
14+
case loganalytics.LogAnalyticsPanicStop:
1415
// log entry already sent
1516
msg := fmt.Sprintf("ERROR: %v", v.Message)
1617
http.Error(w, msg, http.StatusBadRequest)
@@ -37,7 +38,6 @@ func handleProbeRequest(w http.ResponseWriter, r *http.Request) {
3738

3839
prober := NewLogAnalyticsProber(w, r)
3940
prober.AddWorkspaces(opts.Loganalytics.Workspace...)
40-
prober.EnableCache(metricCache)
4141
prober.Run()
4242

4343
h := promhttp.HandlerFor(prober.GetPrometheusRegistry(), promhttp.HandlerOpts{})
@@ -47,14 +47,13 @@ func handleProbeRequest(w http.ResponseWriter, r *http.Request) {
4747
func handleProbeWorkspace(w http.ResponseWriter, r *http.Request) {
4848
defer handleProbePanic(w, r)
4949

50-
workspaceList, err := paramsGetListRequired(r.URL.Query(), "workspace")
50+
workspaceList, err := loganalytics.ParamsGetListRequired(r.URL.Query(), "workspace")
5151
if err != nil {
5252
panic("no workspaces defined")
5353
}
5454

5555
prober := NewLogAnalyticsProber(w, r)
5656
prober.AddWorkspaces(workspaceList...)
57-
prober.EnableCache(metricCache)
5857
prober.Run()
5958

6059
h := promhttp.HandlerFor(prober.GetPrometheusRegistry(), promhttp.HandlerOpts{})
@@ -66,9 +65,20 @@ func handleProbeSubscriptionRequest(w http.ResponseWriter, r *http.Request) {
6665

6766
prober := NewLogAnalyticsProber(w, r)
6867
prober.ServiceDiscovery.Use()
69-
prober.EnableCache(metricCache)
7068
prober.Run()
7169

7270
h := promhttp.HandlerFor(prober.GetPrometheusRegistry(), promhttp.HandlerOpts{})
7371
h.ServeHTTP(w, r)
7472
}
73+
74+
func NewLogAnalyticsProber(w http.ResponseWriter, r *http.Request) *loganalytics.LogAnalyticsProber {
75+
prober := loganalytics.NewLogAnalyticsProber(w, r)
76+
prober.QueryConfig = Config
77+
prober.Conf = opts
78+
prober.Azure.AzureAuthorizer = AzureAuthorizer
79+
prober.Azure.OpInsightsAuthorizer = OpInsightsAuthorizer
80+
prober.Azure.Environment = AzureEnvironment
81+
prober.EnableCache(metricCache)
82+
83+
return prober
84+
}

0 commit comments

Comments
 (0)