~gabe/mortar unlisted

ref: c469f96a78719a6ecc82c4073c92eea7496df0ad mortar/stages/frontend.go -rw-r--r-- 6.7 KiB
c469f96a — Gabe Fierro updates 2 years ago
                                                                                
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package stages

import (
	"context"
	mortarpb "git.sr.ht/~gabe/mortar/proto"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/encoding"
	_ "google.golang.org/grpc/encoding/gzip"
	"google.golang.org/grpc/metadata"
	"net"
	"sync"
	"time"
)

func init() {
	encoding.RegisterCompressor(encoding.GetCompressor("gzip"))
}

var (
	unauthorizedErr = errors.New("Unauthorized")
	requestTimeout  = 60 * time.Minute
)

type ApiFrontendBasicStage struct {
	ctx    context.Context
	output chan *Request
	auth   *CognitoAuth
	sem    chan struct{}
	sync.Mutex
}

type ApiFrontendBasicStageConfig struct {
	TLSCrtFile   string
	TLSKeyFile   string
	ListenAddr   string
	AuthConfig   CognitoAuthConfig
	Upstream     Stage
	StageContext context.Context
}

func NewApiFrontendBasicStage(cfg *ApiFrontendBasicStageConfig) (*ApiFrontendBasicStage, error) {
	stage := &ApiFrontendBasicStage{
		output: make(chan *Request),
		ctx:    cfg.StageContext,
		sem:    make(chan struct{}, 20),
	}
	for i := 0; i < 20; i++ {
		stage.sem <- struct{}{}
	}

	auth, err := NewCognitoAuth(cfg.AuthConfig)
	if err != nil {
		return nil, err
	}
	stage.auth = auth

	var server *grpc.Server

	// handle TLS if it is configured
	log.Infof("Cert file: %s, Key file: %s", cfg.TLSCrtFile, cfg.TLSKeyFile)
	if cfg.TLSCrtFile != "" && cfg.TLSKeyFile != "" {
		creds, err := credentials.NewServerTLSFromFile(cfg.TLSCrtFile, cfg.TLSKeyFile)
		if err != nil {
			return nil, errors.Wrap(err, "could not load TLS keys")
		}
		// this is the lets-encrypt code that we aren't using
		//tls, err := GetTLS(cfg.TLSHost, cfg.TLSCacheDir)
		//if err != nil {
		//	return nil, errors.Wrap(err, "Could not get TLS cert")
		//}
		//creds := credentials.NewTLS(tls)
		log.Info("Using TLS")
		server = grpc.NewServer(
			grpc.Creds(creds),
		)
	} else {
		server = grpc.NewServer()
	}

	l, err := net.Listen("tcp", cfg.ListenAddr)
	if err != nil {
		return nil, errors.Wrapf(err, "Could not listen on address %s", cfg.ListenAddr)
	}
	mortarpb.RegisterMortarServer(server, stage)
	go func() {
		for {
			e := server.Serve(l)
			log.Error(errors.Wrap(e, "Error GRPC serving. Restarting in 10 sec"))
			time.Sleep(10 * time.Second)
		}
	}()
	log.Infof("Listening GRPC on %s", cfg.ListenAddr)

	return stage, nil
}

// get the stage we pull from
func (stage *ApiFrontendBasicStage) GetUpstream() Stage {
	return nil
}

// set the stage we pull from
func (stage *ApiFrontendBasicStage) SetUpstream(upstream Stage) {
	//has no upstream
}

func (stage *ApiFrontendBasicStage) GetQueue() chan *Request {
	return stage.output
}
func (stage *ApiFrontendBasicStage) String() string {
	return "<| api frontend basic stage |>"
}

// identify which sites meet the requirements of the queries
func (stage *ApiFrontendBasicStage) Qualify(ctx context.Context, request *mortarpb.QualifyRequest) (*mortarpb.QualifyResponse, error) {

	t := time.Now()
	defer func() {
		log.Info("Qualify took ", time.Since(t))
		qualifyProcessingTimes.Observe(float64(time.Since(t).Nanoseconds() / 1e6))
	}()

	activeQueries.Inc()
	defer activeQueries.Dec()
	authRequests.Inc()
	headers, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, unauthorizedErr
	}
	if _tokens, ok := headers["token"]; ok && len(_tokens) > 0 && len(_tokens[0]) > 0 {
		token := _tokens[0]
		if _, authErr := stage.auth.verifyToken(token); authErr != nil {
			return nil, authErr
		}
	} else {
		return nil, errors.New("no auth key")
	}
	authRequestsSuccessful.Inc()
	// here we are authenticated to the service.
	validateErr := validateQualifyRequest(request)
	if validateErr != nil {
		return nil, validateErr
	}

	qualifyQueriesProcessed.Inc()

	req := NewQualifyRequest(ctx, request)

	// send the request to the output of this stage so it
	// can be handled by the next stage
	select {
	case stage.output <- req:
	case <-ctx.Done():
		return nil, errors.Wrap(ctx.Err(), "qualify timeout on dispatching query")
	}

	select {
	case resp := <-req.qualify_responses:
		if resp.Error != "" {
			log.Warning(resp.Error)
		}
		close(req.qualify_responses)
		return resp, nil
	case <-ctx.Done():
		return nil, errors.Wrap(ctx.Err(), "qualify timeout on getting query response")
	}

	return nil, errors.New("impossible error")

}

// pull data from Mortar
// gets called from frontend by GRPC server
func (stage *ApiFrontendBasicStage) Fetch(request *mortarpb.FetchRequest, client mortarpb.Mortar_FetchServer) error {
	t := time.Now()
	defer func() {
		log.Info("Fetch took ", time.Since(t))
		fetchProcessingTimes.Observe(float64(time.Since(t).Nanoseconds() / 1e6))
	}()

	authRequests.Inc()
	activeQueries.Inc()
	defer activeQueries.Dec()

	ctx := client.Context()

	headers, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return unauthorizedErr
	}
	if _tokens, ok := headers["token"]; ok && len(_tokens) > 0 && len(_tokens[0]) > 0 {
		token := _tokens[0]
		if _, authErr := stage.auth.verifyToken(token); authErr != nil {
			return authErr
		}
	} else {
		return errors.New("no auth key")
	}
	authRequestsSuccessful.Inc()

	// here we are authenticated to the service.
	validateErr := validateFetchRequest(request)
	if validateErr != nil {
		return validateErr
	}

	fetchQueriesProcessed.Inc()

	select {
	case sem := <-stage.sem:
		defer func() { stage.sem <- sem }()
	case <-ctx.Done():
		return errors.Wrap(ctx.Err(), "fetch timeout on getting semaphore")
	}

	req := NewFetchRequest(ctx, request)

	ret := make(chan error)
	go func() {
		var err error

	sendloop:
		for {
			select {
			case resp := <-req.fetch_responses:
				if resp == nil {
					// if this is nil then we are done, but there's no error (yet)
					break sendloop
				}
				if err = client.Send(resp); err != nil {
					// we have an error on sending, so we tear it all down
					log.Error(errors.Wrap(err, "Error on sending"))
					finishResponse(resp)
					break sendloop
				} else {
					// happy path
					finishResponse(resp)
					messagesSent.Inc()
				}
			case <-ctx.Done():
				// this branch gets triggered because context gets cancelled
				err = errors.Wrapf(ctx.Err(), "fetch timeout on response %v", req.err)
				break sendloop
			}
		}
		ret <- err
		close(req.fetch_responses)
	}()

	select {
	case stage.output <- req:
	case <-ctx.Done():
		return errors.New("timeout")
	}

	select {
	case e := <-ret:
		if e != nil {
			log.Error("Got Error in ret ", e)
		}
		return e
	case <-ctx.Done():
		log.Error("timing out on waiting for result in fetch")
		return errors.New("timeout")
	}

	return nil
}

func (stage *ApiFrontendBasicStage) GetAPIKey(ctx context.Context, request *mortarpb.GetAPIKeyRequest) (*mortarpb.APIKeyResponse, error) {
	access, refresh, err := stage.auth.verifyUserPass(request.Username, request.Password)
	return &mortarpb.APIKeyResponse{
		Token:        access,
		Refreshtoken: refresh,
	}, err
}