-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcheck.go
202 lines (168 loc) · 5.06 KB
/
check.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/krakendio/krakend-cobra/v2/dumper"
"github.com/santhosh-tekuri/jsonschema/v6"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/core"
"github.com/luraproject/lura/v2/logging"
"github.com/luraproject/lura/v2/proxy"
krakendgin "github.com/luraproject/lura/v2/router/gin"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
)
var SchemaURL = "https://www.krakend.io/schema/v%s/krakend.json"
func errorMsg(content string) string {
if !IsTTY {
return content
}
return dumper.ColorRed + content + dumper.ColorReset
}
type LastSourcer interface {
LastSource() ([]byte, error)
}
func NewCheckCmd(rawSchema string) Command {
rawEmbedSchema = rawSchema
return CheckCommand
}
func checkFunc(cmd *cobra.Command, _ []string) { // skipcq: GO-R1005
if cfgFile == "" {
cmd.Println(errorMsg("Please, provide the path to the configuration file with --config or see all the options with --help"))
os.Exit(1) // skipcq: RVV-A0003 // skipcq: RVV-A0003
return
}
cmd.Printf("Parsing configuration file: %s\n", cfgFile)
v, err := parser.Parse(cfgFile)
if err != nil {
cmd.Println(errorMsg("ERROR parsing the configuration file:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1) // skipcq: RVV-A0003 // skipcq: RVV-A0003
return
}
shouldLint := lintCurrentSchema || lintNoNetwork || (lintCustomSchemaPath != "")
if shouldLint {
var data []byte
var err error
if ls, ok := parser.(LastSourcer); ok {
data, err = ls.LastSource()
} else {
data, err = os.ReadFile(cfgFile)
}
if err != nil {
cmd.Println(errorMsg("ERROR loading the configuration content:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1) // skipcq: RVV-A0003
return
}
var raw interface{}
if err := json.Unmarshal(data, &raw); err != nil {
cmd.Println(errorMsg("ERROR converting configuration content to JSON:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1) // skipcq: RVV-A0003
return
}
var sch *jsonschema.Schema
var compilationErr error
if lintNoNetwork {
rawSchema, parseError := jsonschema.UnmarshalJSON(strings.NewReader(rawEmbedSchema))
if parseError != nil {
cmd.Println(errorMsg("ERROR parsing the embed schema:") + fmt.Sprintf("\t%s\n", parseError.Error()))
os.Exit(1) // skipcq: RVV-A0003
return
}
compiler := jsonschema.NewCompiler()
compiler.AddResource("schema.json", rawSchema)
sch, compilationErr = compiler.Compile("schema.json")
} else {
if lintCustomSchemaPath == "" {
lintCustomSchemaPath = fmt.Sprintf(SchemaURL, getVersionMinor(core.KrakendVersion))
}
httpLoader := SchemaHttpLoader(http.Client{
Timeout: 10 * time.Second,
})
loader := jsonschema.SchemeURLLoader{
"file": jsonschema.FileLoader{},
"http": &httpLoader,
"https": &httpLoader,
}
compiler := jsonschema.NewCompiler()
compiler.UseLoader(loader)
sch, compilationErr = compiler.Compile(lintCustomSchemaPath)
}
if compilationErr != nil {
cmd.Println(errorMsg("ERROR compiling the schema:") + fmt.Sprintf("\t%s\n", compilationErr.Error()))
os.Exit(1) // skipcq: RVV-A0003
return
}
if err = sch.Validate(raw); err != nil {
cmd.Println(errorMsg("ERROR linting the configuration file:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1) // skipcq: RVV-A0003
return
}
}
if checkDebug > 0 {
cc := dumper.NewWithColors(cmd, checkDumpPrefix, checkDebug, IsTTY)
if err := cc.Dump(v); err != nil {
cmd.Println(errorMsg("ERROR checking the configuration file:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1) // skipcq: RVV-A0003
return
}
}
if checkGinRoutes {
if err := RunRouterFunc(v); err != nil {
cmd.Println(errorMsg("ERROR testing the configuration file:") + fmt.Sprintf("\t%s\n", err.Error()))
os.Exit(1) // skipcq: RVV-A0003
return
}
}
if IsTTY {
cmd.Printf("%sSyntax OK!%s\n", dumper.ColorGreen, dumper.ColorReset)
return
}
cmd.Println("Syntax OK!")
}
var RunRouterFunc = func(cfg config.ServiceConfig) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(r.(string))
}
}()
gin.SetMode(gin.ReleaseMode)
cfg.Debug = cfg.Debug || debug > 0
if port != 0 {
cfg.Port = port
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
krakendgin.DefaultFactory(proxy.DefaultFactory(logging.NoOp), logging.NoOp).NewWithContext(ctx).Run(cfg)
cancel()
return nil
}
func getVersionMinor(ver string) string {
comps := strings.Split(ver, ".")
if len(comps) < 2 {
return ver
}
return fmt.Sprintf("%s.%s", comps[0], comps[1])
}
type SchemaHttpLoader http.Client
func (l *SchemaHttpLoader) Load(url string) (interface{}, error) {
client := (*http.Client)(l)
resp, err := client.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
_ = resp.Body.Close()
return nil, fmt.Errorf("%s returned status code %d", url, resp.StatusCode)
}
body, err := jsonschema.UnmarshalJSON(resp.Body)
if err != nil {
resp.Body.Close()
return nil, err
}
return body, resp.Body.Close()
}