grafana/pkg/services/ngalert/image/upload.go
George Robinson bad4f7fec5
Alerting: Change screenshots to use components (#55156)
* Alerting: Change screenshots to use components

This commit changes screenshots to use a number of components instead of a set of functional wrappers.

It moves the uploading of screenshots from the screenshot package to the image package so we can re-use the same code for both uploading screenshots and server-side images; SingleFlight from the screenshot package to the image package so we can use it for both taking and uploading the screenshot, where as before it was used just for taking the screenshot; and it also removes the use of a cache because we know that screenshots can be taken at most once per tick of the scheduler.
2022-09-21 10:25:07 +01:00

48 lines
1.3 KiB
Go

package image
import (
"context"
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/grafana/grafana/pkg/components/imguploader"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
)
type UploadingService struct {
uploader imguploader.ImageUploader
failures prometheus.Counter
successes prometheus.Counter
}
func NewUploadingService(uploader imguploader.ImageUploader, r prometheus.Registerer) *UploadingService {
return &UploadingService{
uploader: uploader,
failures: promauto.With(r).NewCounter(prometheus.CounterOpts{
Name: "image_upload_failures_total",
Namespace: "grafana",
Subsystem: "alerting",
}),
successes: promauto.With(r).NewCounter(prometheus.CounterOpts{
Name: "image_upload_successes_total",
Namespace: "grafana",
Subsystem: "alerting",
}),
}
}
// Upload uploads an image and returns a new image with the unmodified path and a URL.
// It returns the unmodified image on error.
func (s *UploadingService) Upload(ctx context.Context, image ngmodels.Image) (ngmodels.Image, error) {
url, err := s.uploader.Upload(ctx, image.Path)
if err != nil {
defer s.failures.Inc()
return image, fmt.Errorf("failed to upload screenshot: %w", err)
}
image.URL = url
defer s.successes.Inc()
return image, nil
}