Skip to content

Commit

Permalink
Merge cc9566e into 870c3a2
Browse files Browse the repository at this point in the history
  • Loading branch information
kamaev committed Jun 19, 2019
2 parents 870c3a2 + cc9566e commit a33bf05
Show file tree
Hide file tree
Showing 11 changed files with 123 additions and 100 deletions.
1 change: 0 additions & 1 deletion Dockerfile.api
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ FROM alpine
RUN apk add --no-cache ca-certificates && update-ca-certificates

COPY pkg/api/api.yml /etc/moira/api.yml
COPY pkg/api/web.json /etc/moira/web.json

COPY --from=builder /go/src/github.com/moira-alert/moira/build/api /usr/bin/api
COPY --from=builder /usr/local/go/lib/time/zoneinfo.zip /usr/local/go/lib/time/
Expand Down
16 changes: 16 additions & 0 deletions api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,19 @@ type Config struct {
EnableCORS bool
Listen string
}

// WebConfig is container for web ui configuration parameters
type WebConfig struct {
SupportEmail string `json:"supportEmail,omitempty"`
RemoteAllowed bool `json:"remoteAllowed"`
Contacts []WebContact `json:"contacts"`
}

// WebContact is container for web ui contact validation
type WebContact struct {
ContactType string `json:"type"`
ContactLabel string `json:"label"`
ValidationRegex string `json:"validation,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Help string `json:"help,omitempty"`
}
18 changes: 4 additions & 14 deletions api/handler/handler.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"fmt"
"net/http"

"github.com/go-chi/chi"
Expand All @@ -22,7 +21,7 @@ const contactKey moiramiddle.ContextKey = "contact"
const subscriptionKey moiramiddle.ContextKey = "subscription"

// NewHandler creates new api handler request uris based on github.com/go-chi/chi
func NewHandler(db moira.Database, log moira.Logger, index moira.Searcher, config *api.Config, metricSourceProvider *metricSource.SourceProvider, configFile []byte) http.Handler {
func NewHandler(db moira.Database, log moira.Logger, index moira.Searcher, config *api.Config, metricSourceProvider *metricSource.SourceProvider, webConfig *api.WebConfig) http.Handler {
database = db
searchIndex = index
router := chi.NewRouter()
Expand All @@ -36,7 +35,9 @@ func NewHandler(db moira.Database, log moira.Logger, index moira.Searcher, confi

router.Route("/api", func(router chi.Router) {
router.Use(moiramiddle.DatabaseContext(database))
router.Get("/config", webConfig(configFile))
router.Get("/web", web(webConfig))
// TODO: remove '/config'
router.Get("/config", web(webConfig))
router.Route("/user", user)
router.Route("/trigger", triggers(metricSourceProvider, searchIndex))
router.Route("/tag", tag)
Expand All @@ -53,17 +54,6 @@ func NewHandler(db moira.Database, log moira.Logger, index moira.Searcher, confi
return router
}

func webConfig(content []byte) http.HandlerFunc {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
if content == nil {
render.Render(writer, request, api.ErrorInternalServer(fmt.Errorf("web config file was not loaded")))
return
}
writer.Header().Set("Content-Type", "application/json")
writer.Write(content)
})
}

func notFoundHandler(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("X-Content-Type-Options", "nosniff")
writer.Header().Set("Content-Type", "application/json")
Expand Down
21 changes: 21 additions & 0 deletions api/handler/web.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package handler

import (
"encoding/json"
"net/http"

"github.com/go-chi/render"
"github.com/moira-alert/moira/api"
)

func web(сonfig *api.WebConfig) http.HandlerFunc {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
configContent, err := json.Marshal(&сonfig)
if err != nil {
render.Render(writer, request, api.ErrorInternalServer(err))
return
}
writer.Header().Set("Content-Type", "application/json")
writer.Write(configContent)
})
}
55 changes: 49 additions & 6 deletions cmd/api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,39 @@ type config struct {
Graphite cmd.GraphiteConfig `yaml:"graphite"`
Logger cmd.LoggerConfig `yaml:"log"`
API apiConfig `yaml:"api"`
Web webConfig `yaml:"web"`
Pprof cmd.ProfilerConfig `yaml:"pprof"`
Remote cmd.RemoteConfig `yaml:"remote"`
}

type apiConfig struct {
// Api local network address. Default is ':8081' so api will be available at http://moira.company.com:8081/api
// Api local network address. Default is ':8081' so api will be available at http://moira.company.com:8081/api.
Listen string `yaml:"listen"`
// If true, CORS for cross-domain requests will be enabled. This option can be used only for debugging purposes.
EnableCORS bool `yaml:"enable_cors"`
// Web_UI config file path. If file not found, api will return 404 in response to "api/config"
WebConfigPath string `yaml:"web_config_path"`
}

type webConfig struct {
// Moira administrator email address.
SupportEmail string `yaml:"supportEmail"`
// If true, users will be able to choose Graphite as trigger metrics data source
RemoteAllowed bool
// List of enabled contact types
Contacts []webContact `yaml:"contacts"`
}

type webContact struct {
// Contact type. Use sender name for script and webhook senders, in other cases use sender type.
// See senders section of notifier config for more details: https://moira.readthedocs.io/en/latest/installation/configuration.html#notifier
ContactType string `yaml:"type"`
// Contact type label that will be shown in web ui
ContactLabel string `yaml:"label"`
// Regular expression to match valid contact values
ValidationRegex string `yaml:"validation"`
// Short description/example of valid contact value
Placeholder string `yaml:"placeholder"`
// More detailed contact description
Help string `yaml:"help"`
}

func (config *apiConfig) getSettings() *api.Config {
Expand All @@ -30,6 +52,25 @@ func (config *apiConfig) getSettings() *api.Config {
}
}

func (config *webConfig) getSettings(isRemoteEnabled bool) *api.WebConfig {
webContacts := make([]api.WebContact, 0, len(config.Contacts))
for _, configContact := range config.Contacts {
contact := api.WebContact{
ContactType: configContact.ContactType,
ContactLabel: configContact.ContactLabel,
ValidationRegex: configContact.ValidationRegex,
Placeholder: configContact.Placeholder,
Help: configContact.Help,
}
webContacts = append(webContacts, contact)
}
return &api.WebConfig{
SupportEmail: config.SupportEmail,
RemoteAllowed: isRemoteEnabled,
Contacts: webContacts,
}
}

func getDefault() config {
return config{
Redis: cmd.RedisConfig{
Expand All @@ -42,9 +83,11 @@ func getDefault() config {
LogLevel: "info",
},
API: apiConfig{
Listen: ":8081",
WebConfigPath: "/etc/moira/web.json",
EnableCORS: false,
Listen: ":8081",
EnableCORS: false,
},
Web: webConfig{
RemoteAllowed: false,
},
Graphite: cmd.GraphiteConfig{
RuntimeStats: false,
Expand Down
19 changes: 3 additions & 16 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
Expand Down Expand Up @@ -70,11 +69,6 @@ func main() {
}
logger.Infof("Moira API stopped. Version: %s", MoiraVersion)

configFile, err := getWebConfigBytes(config.API.WebConfigPath)
if err != nil {
logger.Warningf("Failed to read web config file by path '%s', method 'api/config' will be return 404, error: %s'", config.API.WebConfigPath, err.Error())
}

if config.Pprof.Listen != "" {
logger.Infof("Starting pprof server at: [%s]", config.Pprof.Listen)
cmd.StartProfiling(logger, config.Pprof)
Expand Down Expand Up @@ -117,7 +111,9 @@ func main() {
remoteSource := remote.Create(remoteConfig)
metricSourceProvider := metricSource.CreateMetricSourceProvider(localSource, remoteSource)

httpHandler := handler.NewHandler(database, logger, searchIndex, apiConfig, metricSourceProvider, configFile)
webConfig := config.Web.getSettings(remoteConfig.Enabled)

httpHandler := handler.NewHandler(database, logger, searchIndex, apiConfig, metricSourceProvider, webConfig)
server := &http.Server{
Handler: httpHandler,
}
Expand All @@ -134,15 +130,6 @@ func main() {
logger.Infof("Moira API shutting down.")
}

func getWebConfigBytes(path string) ([]byte, error) {
webConfigFile, err := os.Open(path)
if err != nil {
return nil, err
}
defer webConfigFile.Close()
return ioutil.ReadAll(webConfigFile)
}

// Stop Moira API HTTP server
func Stop(logger moira.Logger, server *http.Server) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
Expand Down
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ services:
dockerfile: Dockerfile.api
volumes:
- ./local/api.yml:/etc/moira/api.yml
- ./local/web.json:/etc/moira/web.json
depends_on:
- redis
- checker
Expand Down
16 changes: 15 additions & 1 deletion local/api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,21 @@ remote:
api:
listen: ":8081"
enable_cors: false
web_config_path: "/etc/moira/web.json"
web:
contacts:
- type: mail
label: E-mail
- type: pushover
label: Pushover
- type: slack
label: Slack
- type: telegram
label: Telegram
help: required to grant @MoiraBot admin privileges
- type: twilio sms
label: Twilio SMS
- type: twilio voice
label: Twilio voice
log:
log_file: stdout
log_level: debug
30 changes: 0 additions & 30 deletions local/web.json

This file was deleted.

16 changes: 15 additions & 1 deletion pkg/api/api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,21 @@ remote:
api:
listen: ":8081"
enable_cors: false
web_config_path: "/etc/moira/web.json"
web:
contacts:
- type: mail
label: E-mail
- type: pushover
label: Pushover
- type: slack
label: Slack
- type: telegram
label: Telegram
help: required to grant @MoiraBot admin privileges
- type: twilio sms
label: Twilio SMS
- type: twilio voice
label: Twilio voice
log:
log_file: stdout
log_level: info
30 changes: 0 additions & 30 deletions pkg/api/web.json

This file was deleted.

0 comments on commit a33bf05

Please sign in to comment.