harness-drone/metric/handler.go

54 lines
1.4 KiB
Go
Raw Normal View History

2019-02-19 23:56:41 +00:00
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package metric
import (
"errors"
"net/http"
"github.com/drone/drone/core"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// errInvalidToken is returned when the prometheus token is invalid.
var errInvalidToken = errors.New("Invalid or missing prometheus token")
// errAccessDenied is returned when the authorized user does not
// have access to the metrics endpoint.
var errAccessDenied = errors.New("Access denied")
// Server is an http Metrics server.
type Server struct {
2019-04-24 22:22:55 +00:00
metrics http.Handler
session core.Session
anonymous bool
2019-02-19 23:56:41 +00:00
}
// NewServer returns a new metrics server.
2019-04-24 22:22:55 +00:00
func NewServer(session core.Session, anonymous bool) *Server {
2019-02-19 23:56:41 +00:00
return &Server{
2019-04-24 22:22:55 +00:00
metrics: promhttp.Handler(),
session: session,
anonymous: anonymous,
2019-02-19 23:56:41 +00:00
}
}
// ServeHTTP responds to an http.Request and writes system
// metrics to the response body in plain text format.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
user, _ := s.session.Get(r)
switch {
2019-04-24 22:22:55 +00:00
case !s.anonymous && user == nil:
2019-02-19 23:56:41 +00:00
http.Error(w, errInvalidToken.Error(), 401)
2019-04-24 22:22:55 +00:00
case !s.anonymous && !user.Admin && !user.Machine:
2019-02-19 23:56:41 +00:00
http.Error(w, errAccessDenied.Error(), 403)
default:
s.metrics.ServeHTTP(w, r)
}
}