Skip to content

Commit eaf8dcb

Browse files
authored
Merge pull request #179 from Nexucis/feature/config
refactor the way the config is used
2 parents 6f9c9fa + b6ee33e commit eaf8dcb

File tree

10 files changed

+258
-170
lines changed

10 files changed

+258
-170
lines changed

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ The following Language Clients have been tested with this language server. More
6262

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

65+
Reading this [documentation](./doc/developing_editor.md) can help you in your work.
66+
6567
### VS Code
6668

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

101103
1. Install package `LSP`, `LSP-promql` via `Package Control`.
102104
2. Follow the [installation instruction](https://github.com/nevill/lsp-promql#installation).
105+
106+
## Contributing
107+
108+
Refer to [CONTRIBUTING.md](./CONTRIBUTING.md)
109+
110+
## License
111+
112+
Apache License 2.0, see [LICENSE](./LICENSE).

cmd/promql-langserver/promql-langserver.go

+11-10
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"os"
2323

2424
kitlog "github.com/go-kit/kit/log"
25+
"github.com/prometheus-community/promql-langserver/config"
2526
promClient "github.com/prometheus-community/promql-langserver/prometheus"
2627

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

3435
flag.Parse()
3536

36-
config, err := langserver.ReadConfig(*configFilePath)
37+
conf, err := config.ReadConfig(*configFilePath)
3738
if err != nil {
3839
fmt.Fprintln(os.Stderr, "Error reading config file:", err.Error())
3940
os.Exit(1)
4041
}
41-
if config.RESTAPIPort != 0 {
42-
fmt.Fprintln(os.Stderr, "REST API: Listening on port ", config.RESTAPIPort)
43-
prometheusClient, err := promClient.NewClient(config.PrometheusURL)
42+
if conf.RESTAPIPort != 0 {
43+
fmt.Fprintln(os.Stderr, "REST API: Listening on port ", conf.RESTAPIPort)
44+
prometheusClient, err := promClient.NewClient(conf.PrometheusURL)
4445
if err != nil {
4546
log.Fatal(err)
4647
}
4748

4849
var logger kitlog.Logger
4950

50-
switch config.LogFormat {
51-
case langserver.JSONFormat:
51+
switch conf.LogFormat {
52+
case config.JSONFormat:
5253
logger = kitlog.NewJSONLogger(os.Stderr)
53-
case langserver.TextFormat:
54+
case config.TextFormat:
5455
logger = kitlog.NewLogfmtLogger(os.Stderr)
5556
default:
56-
log.Fatalf(`invalid log format: "%s"`, config.LogFormat)
57+
log.Fatalf(`invalid log format: "%s"`, conf.LogFormat)
5758
}
5859

5960
logger = kitlog.NewSyncLogger(logger)
@@ -63,12 +64,12 @@ func main() {
6364
log.Fatal(err)
6465
}
6566

66-
err = http.ListenAndServe(fmt.Sprint(":", config.RESTAPIPort), handler)
67+
err = http.ListenAndServe(fmt.Sprint(":", conf.RESTAPIPort), handler)
6768
if err != nil {
6869
log.Fatal(err)
6970
}
7071
} else {
71-
_, s := langserver.StdioServer(context.Background(), config)
72+
_, s := langserver.StdioServer(context.Background(), conf)
7273
if err := s.Run(); err != nil {
7374
log.Fatal(err)
7475
}

config/config.go

+133
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
// Copyright 2020 The Prometheus Authors
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
package config
14+
15+
import (
16+
"fmt"
17+
"io/ioutil"
18+
"net/url"
19+
"os"
20+
"strconv"
21+
22+
"github.com/kelseyhightower/envconfig"
23+
"gopkg.in/yaml.v3"
24+
)
25+
26+
// ReadConfig gets the GlobalConfig from a configFile (that is a path to the file).
27+
func ReadConfig(configFile string) (*Config, error) {
28+
if len(configFile) == 0 {
29+
fmt.Fprintln(os.Stderr, "No config file provided, configuration is reading from System environment")
30+
return readConfigFromENV()
31+
}
32+
fmt.Fprintln(os.Stderr, "Configuration is reading from configuration file")
33+
return readConfigFromYAML(configFile)
34+
}
35+
36+
func readConfigFromYAML(configFile string) (*Config, error) {
37+
b, err := ioutil.ReadFile(configFile)
38+
if err != nil {
39+
return nil, err
40+
}
41+
res := new(Config)
42+
err = yaml.Unmarshal(b, res)
43+
return res, err
44+
}
45+
46+
func readConfigFromENV() (*Config, error) {
47+
res := new(Config)
48+
err := res.unmarshalENV()
49+
return res, err
50+
}
51+
52+
// LogFormat is the type used for describing the format of logs.
53+
type LogFormat string
54+
55+
const (
56+
// JSONFormat is used for JSON logs.
57+
JSONFormat LogFormat = "json"
58+
// TextFormat is used of structured text logs.
59+
TextFormat LogFormat = "text"
60+
)
61+
62+
var mapLogFormat = map[LogFormat]bool{ // nolint: gochecknoglobals
63+
JSONFormat: true,
64+
TextFormat: true,
65+
}
66+
67+
// Config contains the configuration for a server.
68+
type Config struct {
69+
ActivateRPCLog bool `yaml:"activate_rpc_log"`
70+
LogFormat LogFormat `yaml:"log_format"`
71+
PrometheusURL string `yaml:"prometheus_url"`
72+
RESTAPIPort uint64 `yaml:"rest_api_port"`
73+
}
74+
75+
// UnmarshalYAML overrides a function used internally by the yaml.v3 lib.
76+
func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error {
77+
tmp := &Config{}
78+
type plain Config
79+
if err := unmarshal((*plain)(tmp)); err != nil {
80+
return err
81+
}
82+
if err := tmp.Validate(); err != nil {
83+
return err
84+
}
85+
*c = *tmp
86+
return nil
87+
}
88+
89+
func (c *Config) unmarshalENV() error {
90+
prefix := "LANGSERVER"
91+
conf := &struct {
92+
ActivateRPCLog bool
93+
LogFormat string
94+
PrometheusURL string
95+
// the envconfig lib is not able to convert an empty string to the value 0
96+
// so we have to convert it manually
97+
RESTAPIPort string
98+
}{}
99+
if err := envconfig.Process(prefix, conf); err != nil {
100+
return err
101+
}
102+
if len(conf.RESTAPIPort) > 0 {
103+
var parseError error
104+
c.RESTAPIPort, parseError = strconv.ParseUint(conf.RESTAPIPort, 10, 64)
105+
if parseError != nil {
106+
return parseError
107+
}
108+
}
109+
c.ActivateRPCLog = conf.ActivateRPCLog
110+
c.PrometheusURL = conf.PrometheusURL
111+
c.LogFormat = LogFormat(conf.LogFormat)
112+
return c.Validate()
113+
}
114+
115+
// Validate returns an error if the config is not valid.
116+
func (c *Config) Validate() error {
117+
if len(c.PrometheusURL) > 0 {
118+
if _, err := url.Parse(c.PrometheusURL); err != nil {
119+
return err
120+
}
121+
}
122+
123+
if len(c.LogFormat) > 0 {
124+
if !mapLogFormat[c.LogFormat] {
125+
return fmt.Errorf(`invalid value for logFormat. "%s" Valid values are "%s" or "%s"`, c.LogFormat, TextFormat, JSONFormat)
126+
}
127+
} else {
128+
// default value
129+
c.LogFormat = TextFormat
130+
}
131+
132+
return nil
133+
}

langserver/config_test.go renamed to config/config_test.go

+12-11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2019 The Prometheus Authors
1+
// Copyright 2020 The Prometheus Authors
22
// Licensed under the Apache License, Version 2.0 (the "License");
33
// you may not use this file except in compliance with the License.
44
// You may obtain a copy of the License at
@@ -11,7 +11,7 @@
1111
// See the License for the specific language governing permissions and
1212
// limitations under the License.
1313

14-
package langserver
14+
package config
1515

1616
import (
1717
"os"
@@ -30,22 +30,23 @@ func TestUnmarshalENV(t *testing.T) {
3030
title: "empty config",
3131
variables: map[string]string{},
3232
expected: &Config{
33-
LogFormat: TextFormat,
33+
ActivateRPCLog: false,
34+
LogFormat: TextFormat,
3435
},
3536
},
3637
{
3738
title: "full config",
3839
variables: map[string]string{
39-
"LANGSERVER_RPCTRACE": "text",
40-
"LANGSERVER_PROMETHEUSURL": "http://localhost:9090",
41-
"LANGSERVER_RESTAPIPORT": "8080",
42-
"LANGSERVER_LOGFORMAT": "json",
40+
"LANGSERVER_ACTIVATERPCLOG": "true",
41+
"LANGSERVER_PROMETHEUSURL": "http://localhost:9090",
42+
"LANGSERVER_RESTAPIPORT": "8080",
43+
"LANGSERVER_LOGFORMAT": "json",
4344
},
4445
expected: &Config{
45-
RPCTrace: "text",
46-
PrometheusURL: "http://localhost:9090",
47-
RESTAPIPort: 8080,
48-
LogFormat: JSONFormat,
46+
ActivateRPCLog: true,
47+
PrometheusURL: "http://localhost:9090",
48+
RESTAPIPort: 8080,
49+
LogFormat: JSONFormat,
4950
},
5051
},
5152
}

doc/developing_editor.md

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
Development of new client editor
2+
=============================
3+
4+
This documentation will give you some tips to help when you are going to support the promql-server in a new editor.
5+
6+
## Config
7+
There is two different config used by the promql-server.
8+
9+
### Cold configuration (YAML or by environment)
10+
The first one is a classic yaml file which can be used to customize the server when it is starting. It's specified by adding the `--config-file` command line flag when starting the language server.
11+
12+
It has the following structure:
13+
14+
```yaml
15+
activate_rpc_log: false # It's a boolean in order to activate or deactivate the rpc log. It's deactivated by default and mainly useful for debugging the language server, by inspecting the communication with the language client.
16+
log_format: "text" # The format of the log printed. Possible value: json, text. Default value: "text"
17+
prometheus_url: "http://localhost:9090" # the HTTP URL of the prometheus server.
18+
rest_api_port: 8080 # When set, the server will be started as an HTTP server that provides a REST API instead of the language server protocol. Default value: 0
19+
```
20+
21+
In case the file is not provided, it will read the configuration from the environment variables with the following structure:
22+
23+
```bash
24+
export LANGSERVER_ACTIVATERPCLOG="true"
25+
export LANGSERVER_PROMETHEUSURL="http://localhost:9090"
26+
export LANGSERVER_RESTAPIPORT"="8080"
27+
export LANGSERVER_LOGFORMAT"="json"
28+
```
29+
30+
Note: documentation and default value are the same for both configuration (yaml and environment)
31+
32+
### JSON configuration (hot configuration)
33+
There is a second configuration which is used only at the runtime and can be sent by the language client over the `DidChangeConfiguration` API. It's used to sync configuration from the text editor to the language server.
34+
35+
It has the following structure:
36+
37+
```json
38+
{
39+
"promql": {
40+
"url": "http://localhost:9090" # the HTTP URL of the prometheus server.
41+
}
42+
}
43+
```
44+
45+
Using this way of changing configuration requires both providing those config options in the Text editor and sending them to the language server whenever they are changed.

0 commit comments

Comments
 (0)