Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor the way the config is used #179

Merged
merged 5 commits into from
Jul 1, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions cmd/promql-langserver/promql-langserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"os"

kitlog "github.com/go-kit/kit/log"
"github.com/prometheus-community/promql-langserver/config"
promClient "github.com/prometheus-community/promql-langserver/prometheus"

"github.com/prometheus-community/promql-langserver/langserver"
Expand All @@ -33,27 +34,27 @@ func main() {

flag.Parse()

config, err := langserver.ReadConfig(*configFilePath)
conf, err := config.ReadConfig(*configFilePath)
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading config file:", err.Error())
os.Exit(1)
}
if config.RESTAPIPort != 0 {
fmt.Fprintln(os.Stderr, "REST API: Listening on port ", config.RESTAPIPort)
prometheusClient, err := promClient.NewClient(config.PrometheusURL)
if conf.RESTAPIPort != 0 {
fmt.Fprintln(os.Stderr, "REST API: Listening on port ", conf.RESTAPIPort)
prometheusClient, err := promClient.NewClient(conf.PrometheusURL)
if err != nil {
log.Fatal(err)
}

var logger kitlog.Logger

switch config.LogFormat {
case langserver.JSONFormat:
switch conf.LogFormat {
case config.JSONFormat:
logger = kitlog.NewJSONLogger(os.Stderr)
case langserver.TextFormat:
case config.TextFormat:
logger = kitlog.NewLogfmtLogger(os.Stderr)
default:
log.Fatalf(`invalid log format: "%s"`, config.LogFormat)
log.Fatalf(`invalid log format: "%s"`, conf.LogFormat)
}

logger = kitlog.NewSyncLogger(logger)
Expand All @@ -63,12 +64,12 @@ func main() {
log.Fatal(err)
}

err = http.ListenAndServe(fmt.Sprint(":", config.RESTAPIPort), handler)
err = http.ListenAndServe(fmt.Sprint(":", conf.RESTAPIPort), handler)
if err != nil {
log.Fatal(err)
}
} else {
_, s := langserver.StdioServer(context.Background(), config)
_, s := langserver.StdioServer(context.Background(), conf)
if err := s.Run(); err != nil {
log.Fatal(err)
}
Expand Down
133 changes: 133 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright 2020 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config

import (
"fmt"
"io/ioutil"
"net/url"
"os"
"strconv"

"github.com/kelseyhightower/envconfig"
"gopkg.in/yaml.v3"
)

// ReadConfig gets the GlobalConfig from a configFile (that is a path to the file).
func ReadConfig(configFile string) (*Config, error) {
if len(configFile) == 0 {
fmt.Fprintln(os.Stderr, "No config file provided, configuration is reading from System environment")
return readConfigFromENV()
}
fmt.Fprintln(os.Stderr, "Configuration is reading from configuration file")
return readConfigFromYAML(configFile)
}

func readConfigFromYAML(configFile string) (*Config, error) {
b, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, err
}
res := new(Config)
err = yaml.Unmarshal(b, res)
return res, err
}

func readConfigFromENV() (*Config, error) {
res := new(Config)
err := res.unmarshalENV()
return res, err
}

// LogFormat is the type used for describing the format of logs.
type LogFormat string

const (
// JSONFormat is used for JSON logs.
JSONFormat LogFormat = "json"
// TextFormat is used of structured text logs.
TextFormat LogFormat = "text"
)

var mapLogFormat = map[LogFormat]bool{ // nolint: gochecknoglobals
JSONFormat: true,
TextFormat: true,
}

// Config contains the configuration for a server.
type Config struct {
ActivateRPCLog bool `yaml:"activate_rpc_log"`
LogFormat LogFormat `yaml:"log_format"`
PrometheusURL string `yaml:"prometheus_url"`
RESTAPIPort uint64 `yaml:"rest_api_port"`
}

// UnmarshalYAML overrides a function used internally by the yaml.v3 lib.
func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
tmp := &Config{}
type plain Config
if err := unmarshal((*plain)(tmp)); err != nil {
return err
}
if err := tmp.Validate(); err != nil {
return err
}
*c = *tmp
return nil
}

func (c *Config) unmarshalENV() error {
prefix := "LANGSERVER"
conf := &struct {
ActivateRPCLog bool
LogFormat string
PrometheusURL string
// the envconfig lib is not able to convert an empty string to the value 0
// so we have to convert it manually
RESTAPIPort string
}{}
if err := envconfig.Process(prefix, conf); err != nil {
return err
}
if len(conf.RESTAPIPort) > 0 {
var parseError error
c.RESTAPIPort, parseError = strconv.ParseUint(conf.RESTAPIPort, 10, 64)
if parseError != nil {
return parseError
}
}
c.ActivateRPCLog = conf.ActivateRPCLog
c.PrometheusURL = conf.PrometheusURL
c.LogFormat = LogFormat(conf.LogFormat)
return c.Validate()
}

// Validate returns an error if the config is not valid.
func (c *Config) Validate() error {
if len(c.PrometheusURL) > 0 {
if _, err := url.Parse(c.PrometheusURL); err != nil {
return err
}
}

if len(c.LogFormat) > 0 {
if !mapLogFormat[c.LogFormat] {
return fmt.Errorf(`invalid value for logFormat. "%s" Valid values are "%s" or "%s"`, c.LogFormat, TextFormat, JSONFormat)
}
} else {
// default value
c.LogFormat = TextFormat
}

return nil
}
23 changes: 12 additions & 11 deletions langserver/config_test.go → config/config_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2019 The Prometheus Authors
// Copyright 2020 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Expand All @@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package langserver
package config

import (
"os"
Expand All @@ -30,22 +30,23 @@ func TestUnmarshalENV(t *testing.T) {
title: "empty config",
variables: map[string]string{},
expected: &Config{
LogFormat: TextFormat,
ActivateRPCLog: false,
LogFormat: TextFormat,
},
},
{
title: "full config",
variables: map[string]string{
"LANGSERVER_RPCTRACE": "text",
"LANGSERVER_PROMETHEUSURL": "http://localhost:9090",
"LANGSERVER_RESTAPIPORT": "8080",
"LANGSERVER_LOGFORMAT": "json",
"LANGSERVER_ACTIVATERPCLOG": "true",
"LANGSERVER_PROMETHEUSURL": "http://localhost:9090",
"LANGSERVER_RESTAPIPORT": "8080",
"LANGSERVER_LOGFORMAT": "json",
},
expected: &Config{
RPCTrace: "text",
PrometheusURL: "http://localhost:9090",
RESTAPIPort: 8080,
LogFormat: JSONFormat,
ActivateRPCLog: true,
PrometheusURL: "http://localhost:9090",
RESTAPIPort: 8080,
LogFormat: JSONFormat,
},
},
}
Expand Down
127 changes: 12 additions & 115 deletions langserver/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,125 +16,10 @@ package langserver
import (
"context"
"fmt"
"io/ioutil"
"net/url"
"os"
"strconv"

"github.com/kelseyhightower/envconfig"
"github.com/prometheus-community/promql-langserver/internal/vendored/go-tools/lsp/protocol"
"gopkg.in/yaml.v3"
)

// Config contains the configuration for a server.
type Config struct {
RPCTrace string `yaml:"rpc_trace"`
LogFormat LogFormat `yaml:"log_format"`
PrometheusURL string `yaml:"prometheus_url"`
RESTAPIPort uint64 `yaml:"rest_api_port"`
}

// LogFormat is the type used for describing the format of logs.
type LogFormat string

const (
// JSONFormat is used for JSON logs.
JSONFormat LogFormat = "json"
// TextFormat is used of structured text logs.
TextFormat LogFormat = "text"
)

var mapLogFormat = map[LogFormat]bool{ // nolint: gochecknoglobals
JSONFormat: true,
TextFormat: true,
}

// UnmarshalYAML overrides a function used internally by the yaml.v3 lib.
func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
tmp := &Config{}
type plain Config
if err := unmarshal((*plain)(tmp)); err != nil {
return err
}
if err := tmp.Validate(); err != nil {
return err
}
*c = *tmp
return nil
}

func (c *Config) unmarshalENV() error {
prefix := "LANGSERVER"
conf := &struct {
RPCTrace string
LogFormat string
PrometheusURL string
// the envconfig lib is not able to convert an empty string to the value 0
// so we have to convert it manually
RESTAPIPort string
}{}
if err := envconfig.Process(prefix, conf); err != nil {
return err
}
if len(conf.RESTAPIPort) > 0 {
var parseError error
c.RESTAPIPort, parseError = strconv.ParseUint(conf.RESTAPIPort, 10, 64)
if parseError != nil {
return parseError
}
}
c.RPCTrace = conf.RPCTrace
c.PrometheusURL = conf.PrometheusURL
c.LogFormat = LogFormat(conf.LogFormat)
return c.Validate()
}

// Validate returns an error if the config is not valid.
func (c *Config) Validate() error {
if len(c.PrometheusURL) > 0 {
if _, err := url.Parse(c.PrometheusURL); err != nil {
return err
}
}

if len(c.LogFormat) > 0 {
if !mapLogFormat[c.LogFormat] {
return fmt.Errorf(`invalid value for logFormat. "%s" Valid values are "%s" or "%s"`, c.LogFormat, TextFormat, JSONFormat)
}
} else {
// default value
c.LogFormat = TextFormat
}

return nil
}

// ReadConfig gets the GlobalConfig from a configFile (that is a path to the file).
func ReadConfig(configFile string) (*Config, error) {
if len(configFile) == 0 {
fmt.Fprintln(os.Stderr, "No config file provided, configuration is reading from System environment")
return readConfigFromENV()
}
fmt.Fprintln(os.Stderr, "Configuration is reading from configuration file")
return readConfigFromYAML(configFile)
}

func readConfigFromYAML(configFile string) (*Config, error) {
b, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, err
}
res := new(Config)
err = yaml.Unmarshal(b, res)
return res, err
}

func readConfigFromENV() (*Config, error) {
res := new(Config)
err := res.unmarshalENV()
return res, err
}

// DidChangeConfiguration is required by the protocol.Server interface.
func (s *server) DidChangeConfiguration(ctx context.Context, params *protocol.DidChangeConfigurationParams) error {
langserverAddressConfigPath := []string{"promql", "url"}
Expand Down Expand Up @@ -175,3 +60,15 @@ func (s *server) DidChangeConfiguration(ctx context.Context, params *protocol.Di

return nil
}

func (s *server) connectPrometheus(url string) error {
if err := s.metadataService.ChangeDataSource(url); err != nil {
// nolint: errcheck
s.client.ShowMessage(s.lifetime, &protocol.ShowMessageParams{
Type: protocol.Error,
Message: fmt.Sprintf("Failed to connect to Prometheus at %s:\n\n%s ", url, err.Error()),
})
return err
}
return nil
}
Loading