forked from uber/kraken
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnginx.go
218 lines (191 loc) · 5.81 KB
/
nginx.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright (c) 2016-2019 Uber Technologies, Inc.
//
// 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 nginx
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"text/template"
"github.com/uber/kraken/nginx/config"
"github.com/uber/kraken/utils/httputil"
"github.com/uber/kraken/utils/log"
)
const (
_genDir = "/tmp/nginx"
)
var _clientCABundle = path.Join(_genDir, "ca.crt")
// Config defines nginx configuration.
type Config struct {
Root bool `yaml:"root"`
// Name defines the default nginx template for each component.
Name string `yaml:"name"`
// TemplatePath takes precedence over Name, overwrites default template.
TemplatePath string `yaml:"template_path"`
CacheDir string `yaml:"cache_dir"`
LogDir string `yaml:"log_dir"`
tls httputil.TLSConfig
}
func (c *Config) inject(params map[string]interface{}) error {
for _, s := range []string{"cache_dir", "log_dir"} {
if _, ok := params[s]; ok {
return fmt.Errorf("invalid params: %s is reserved", s)
}
}
params["cache_dir"] = c.CacheDir
params["log_dir"] = c.LogDir
return nil
}
// GetTemplate returns the template content.
func (c *Config) getTemplate() (string, error) {
if c.TemplatePath != "" {
b, err := ioutil.ReadFile(c.TemplatePath)
if err != nil {
return "", fmt.Errorf("read template: %s", err)
}
return string(b), nil
}
tmpl, err := config.GetDefaultTemplate(c.Name)
if err != nil {
return "", fmt.Errorf("get default template: %s", err)
}
return tmpl, nil
}
// Build builds nginx config.
func (c *Config) Build(params map[string]interface{}) ([]byte, error) {
tmpl, err := c.getTemplate()
if err != nil {
return nil, fmt.Errorf("get template: %s", err)
}
if _, ok := params["client_verification"]; !ok {
params["client_verification"] = config.DefaultClientVerification
}
site, err := populateTemplate(tmpl, params)
if err != nil {
return nil, fmt.Errorf("populate template: %s", err)
}
// Build nginx config with base template and component specific template.
tmpl, err = config.GetDefaultTemplate("base")
if err != nil {
return nil, fmt.Errorf("get default base template: %s", err)
}
src, err := populateTemplate(tmpl, map[string]interface{}{
"site": string(site),
"ssl_enabled": !c.tls.Server.Disabled,
"ssl_certificate": c.tls.Server.Cert.Path,
"ssl_certificate_key": c.tls.Server.Key.Path,
"ssl_password_file": c.tls.Server.Passphrase.Path,
"ssl_client_certificate": _clientCABundle,
})
if err != nil {
return nil, fmt.Errorf("populate base: %s", err)
}
return src, nil
}
// Option allows setting optional nginx configuration.
type Option func(*Config)
// WithTLS configures nginx configuration with tls.
func WithTLS(tls httputil.TLSConfig) Option {
return func(c *Config) { c.tls = tls }
}
// Run injects params into an nginx configuration template and runs it.
func Run(config Config, params map[string]interface{}, opts ...Option) error {
if config.Name == "" && config.TemplatePath == "" {
return errors.New("invalid config: name or template_path required")
}
if config.CacheDir == "" {
return errors.New("invalid config: cache_dir required")
}
if config.LogDir == "" {
return errors.New("invalid config: log_dir required")
}
for _, opt := range opts {
opt(&config)
}
// Create root directory for generated files for nginx.
if err := os.MkdirAll(_genDir, 0775); err != nil {
return err
}
if config.tls.Server.Disabled {
log.Warn("Server TLS is disabled")
} else {
for _, s := range append(
config.tls.CAs,
config.tls.Server.Cert,
config.tls.Server.Key,
config.tls.Server.Passphrase) {
if _, err := os.Stat(s.Path); err != nil {
return fmt.Errorf("invalid TLS config: %s", err)
}
}
// Concat all ca files into bundle.
cabundle, err := os.Create(_clientCABundle)
if err != nil {
return fmt.Errorf("create cabundle: %s", err)
}
if err := config.tls.WriteCABundle(cabundle); err != nil {
return fmt.Errorf("write cabundle: %s", err)
}
cabundle.Close()
}
if err := os.MkdirAll(config.CacheDir, 0775); err != nil {
return err
}
if err := config.inject(params); err != nil {
return err
}
src, err := config.Build(params)
if err != nil {
return fmt.Errorf("build nginx config: %s", err)
}
conf := filepath.Join(_genDir, config.Name)
if err := ioutil.WriteFile(conf, src, 0755); err != nil {
return fmt.Errorf("write src: %s", err)
}
stdoutLog := path.Join(config.LogDir, "nginx-stdout.log")
stdout, err := os.OpenFile(stdoutLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("open stdout log: %s", err)
}
args := []string{"/usr/sbin/nginx", "-g", "daemon off;", "-c", conf}
if config.Root {
args = append([]string{"sudo"}, args...)
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = stdout
cmd.Stderr = stdout
return cmd.Run()
}
func populateTemplate(tmpl string, args map[string]interface{}) ([]byte, error) {
t, err := template.New("nginx").Parse(tmpl)
if err != nil {
return nil, fmt.Errorf("parse: %s", err)
}
out := &bytes.Buffer{}
if err := t.Execute(out, args); err != nil {
return nil, fmt.Errorf("exec: %s", err)
}
return out.Bytes(), nil
}
// GetServer returns a string for an nginx server directive value.
func GetServer(net, addr string) string {
if net == "unix" {
return "unix:" + addr
}
return addr
}