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 4 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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ The following Language Clients have been tested with this language server. More

Feel free to reach out if you want to use it with another Editor/Tool.

Reading this [documentation](./doc/developing_editor.md) can help you in your work
slrtbtfs marked this conversation as resolved.
Show resolved Hide resolved

### VS Code

There exists a VS Code extension based on this language server: <https://github.com/slrtbtfs/vscode-prometheus>
Expand Down Expand Up @@ -100,3 +102,11 @@ The Vim command `:YcmDebugInfo` gives status information and points to logfiles.

1. Install package `LSP`, `LSP-promql` via `Package Control`.
2. Follow the [installation instruction](https://github.com/nevill/lsp-promql#installation).

## Contributing

Refer to [CONTRIBUTING.md](./CONTRIBUTING.md)

## License

Apache License 2.0, see [LICENSE](./LICENSE).
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
30 changes: 30 additions & 0 deletions doc/developing_editor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Development of new client editor
=============================

This documentation will give you some tips to help when you are going to support the promql-server in a new editor.

## Config
There is two different config used by the promql-server.

### YAML configuration (cold configuration)
The first one is a classic yaml file which can be used to customize the server when it is starting. It has the following structure:
slrtbtfs marked this conversation as resolved.
Show resolved Hide resolved

```yaml
activate_rpc_log: false # It's a boolean in order to activate or deactivate the rpc log. It's deactivated by default
slrtbtfs marked this conversation as resolved.
Show resolved Hide resolved
log_format: "text" # The format of the log printed. Possible value: json, text. Default value: "text"
prometheus_url: "http://localhost:9090" # the HTTP URL of the prometheus server.
rest_api_port: 8080 # When set, the server will be started as an HTTP server. Default value: 0
slrtbtfs marked this conversation as resolved.
Show resolved Hide resolved
```

slrtbtfs marked this conversation as resolved.
Show resolved Hide resolved
### JSON configuration (hot configuration)
There is a second configuration which is used only at the runtime.
slrtbtfs marked this conversation as resolved.
Show resolved Hide resolved

```json
{
"promql": {
"url": "http://localhost:9090" # the HTTP URL of the prometheus server.
}
}
```

This configuration will be watched thanks to the method implemented `DidChangeConfiguration`
slrtbtfs marked this conversation as resolved.
Show resolved Hide resolved
Loading