File: query_graphql.go

package info (click to toggle)
balboa 2.0.0%2Bds-7
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,340 kB
  • sloc: ansic: 10,581; makefile: 160; python: 127; sh: 60
file content (414 lines) | stat: -rw-r--r-- 10,025 bytes parent folder | download | duplicates (3)
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// balboa
// Copyright (c) 2018, DCSO GmbH

package query

import (
	"context"
	"fmt"
	"net/http"
	"runtime"
	"time"

	"github.com/DCSO/balboa/db"
	"github.com/DCSO/balboa/observation"

	graphql "github.com/graph-gophers/graphql-go"
	"github.com/graph-gophers/graphql-go/errors"
	"github.com/graph-gophers/graphql-go/relay"
	uuid "github.com/satori/go.uuid"
	log "github.com/sirupsen/logrus"
)

const (
	txtSchema = `# A DNS resource record type.
	enum RRType {
	  A
	  A6
	  AAAA
	  AFSDB
	  ALIAS
	  APL
	  AXFR
	  CAA
	  CDNSKEY
	  CDS
	  CERT
	  CNAME
	  DHCID
	  DLV
	  DNAME
	  DNSKEY
	  DS
	  HINFO
	  HIP
	  IPSECKEY
	  IXFR
	  KEY
	  KX
	  LOC
	  MX
	  NAPTR
	  NS
	  NSEC
	  NSEC3
	  NSEC3PARAM
	  OPENPGPKEY
	  OPT
	  PTR
	  RRSIG
	  RP
	  SIG
	  SOA
	  SPF
	  SRV
	  SSHFP
	  TA
	  TKEY
	  TLSA
	  TSIG
	  TXT
	  URI
	}

	# A single observation, unique for the combination of sensor, rrname,
	# rdata and rrtype. Corresponds, roughly, to a pDNS COF item, but with
	# additional Aliases (linked via IP in A/AAAA records).
	type Entry {
		# The number of observed occurrences of this observation.
		count: Int!

		# The RRName seen in this observation.
		rrname: String!

		# The RRType seen in this observation.
		rrtype: RRType

		# The RData seen in this observation.
		rdata: String!

		# Time this observation was first seen, as Unix timestamp.
		time_first: Int!

		# Time this observation was first seen, as RFC 3339 formatted time.
		time_first_rfc3339: String!

		# Time this observation was last seen, as Unix timestamp.
		time_last: Int!

		# Time this observation was last seen, as RFC 3339 formatted time.
		time_last_rfc3339: String!

		# Some identifier describing the source of this observation.
		sensor_id: String

		# Entries referencing the same IP (for A/AAAA) observed on the same
		# sensor.
		aliases(limit: Int = 1000): [LeafEntry]
	}

	# A single observation, unique for the combination of sensor, rrname,
	# rdata and rrtype. Corresponds, roughly, to a pDNS COF item.
	type LeafEntry {
		# The number of observed occurrences of this observation.
		count: Int!

		# The RRName seen in this observation.
		rrname: String!

		# The RRType seen in this observation.
		rrtype: RRType

		# The RData seen in this observation.
		rdata: String!

		# Time this observation was first seen, as Unix timestamp.
		time_first: Int!

		# Time this observation was first seen, as RFC 3339 formatted time.
		time_first_rfc3339: String!

		# Time this observation was last seen, as Unix timestamp.
		time_last: Int!

		# Time this observation was last seen, as RFC 3339 formatted time.
		time_last_rfc3339: String!

		# Some identifier describing the source of this observation.
		sensor_id: String
	}

	input EntryInput {
		# The number of observed occurrences of this observation.
		count: Int!

		# The RRName seen in this observation.
		rrname: String!

		# The RRType seen in this observation.
		rrtype: RRType!

		# The RData seen in this observation.
		rdata: String!

		# Time this observation was first seen, as Unix timestamp.
		time_first: Int!

		# Time this observation was last seen, as Unix timestamp.
		time_last: Int!

		# Some identifier describing the source of this observation.
		sensor_id: String!
	}

	# Some runtime values describing the current state of the database.
	type Stats {
		# Total number of keys in the database.
		total_count: Int!

		# Number of concurrent goroutines in the server instance.
		num_goroutines: Int!
	}

	type Query {
		# Returns a set of observations satisfying the given query parameters.
		# Providing rdata, rrname, rrtype and/or sensor_id will restrict the
		# results to the set of observations that match all of the given
		# constraints.
		entries(rdata: String, rrname: String, rrtype: RRType, sensor_id: String, limit: Int = 1000): [Entry]

		# Returns some runtime values describing the current state of the database.
		stats(): Stats
	}

	#type Mutation {
	#	announceObservation(observation: EntryInput!): Entry!
	#}

	schema {
		query: Query
		#mutation: Mutation
	}`
)

// GraphQLFrontend represents a concurrent component that provides a GraphQL
// query interface for the database.
type GraphQLFrontend struct {
	Server    *http.Server
	IsRunning bool
}

// Resolver is just used to bundle top level methods.
type Resolver struct{}

// Entries returns a collection of Entry resolvers, given parameters such as
// Rdata, RRname, RRtype and sensor ID.
func (r *Resolver) Entries(args struct {
	Rdata    *string
	Rrname   *string
	Rrtype   *string
	SensorID *string
	Limit    int32
}) (*[]*EntryResolver, error) {
	startTime := time.Now()
	defer func() {
		var rdata, rrname, rrtype, sensorID string
		if args.Rdata != nil {
			rdata = *args.Rdata
		} else {
			rdata = ("nil")
		}
		if args.Rrname != nil {
			rrname = *args.Rrname
		} else {
			rrname = ("nil")
		}
		if args.Rrtype != nil {
			rrtype = *args.Rrtype
		} else {
			rrtype = ("nil")
		}
		if args.SensorID != nil {
			sensorID = *args.SensorID
		} else {
			sensorID = ("nil")
		}
		log.Debugf("finished query for (%s/%s/%s/%s) in %v", rdata, rrname, rrtype, sensorID, time.Since(startTime))
	}()

	l := make([]*EntryResolver, 0)
	if args.Rdata == nil && args.Rrname == nil {
		return nil, &errors.QueryError{
			Message: "at least one of the 'rdata' or 'rrname' parameters is required",
		}
	}
	results, err := db.ObservationDB.Search(args.Rdata, args.Rrname, args.Rrtype, args.SensorID, int(args.Limit))
	if err != nil {
		return nil, err
	}
	for _, r := range results {
		er := EntryResolver{
			entry: r,
		}
		l = append(l, &er)
	}
	return &l, nil
}

// AnnounceObservation is a mutation that adds a single new observation
// to the database.
//func (r *Resolver) AnnounceObservation(args struct {
//	Observation struct {
//		Count     int32
//		TimeFirst int32
//		TimeLast  int32
//		RRType    string
//		RRName    string
//		RData     string
//		SensorID  string
//	}
//}) *EntryResolver {
//	inObs := observation.InputObservation{
//		Count:          int(args.Observation.Count),
//		TimestampStart: time.Unix(int64(args.Observation.TimeFirst), 0),
//		TimestampEnd:   time.Unix(int64(args.Observation.TimeLast), 0),
//		Rrname:         args.Observation.RRName,
//		Rrtype:         args.Observation.RRType,
//		Rdata:          args.Observation.RData,
//		SensorID:       args.Observation.SensorID,
//	}
//	resObs := db.ObservationDB.AddObservation(inObs)
//	return &EntryResolver{
//		entry: resObs,
//	}
//}

// Stats returns a Stats resolver.
func (r *Resolver) Stats() (*StatsResolver, error) {
	return &StatsResolver{}, nil
}

// StatsResolver is a resolver for the Stats type.
type StatsResolver struct {
	//totalCount int32
}

// TotalCount returns the total number of keys in the database.
func (r *StatsResolver) TotalCount() int32 {
	val, err := db.ObservationDB.TotalCount()
	if err != nil {
		log.Error(err)
	}
	return int32(val)
}

// NumGoroutines returns the number of currently running goroutines
// in balboa.
func (r *StatsResolver) NumGoroutines() int32 {
	return int32(runtime.NumGoroutine())
}

// EntryResolver is a resolver for the Entry type.
type EntryResolver struct {
	entry observation.Observation
}

// ID returns the ID field of the corresponding entry.
func (r *EntryResolver) ID() graphql.ID {
	id := uuid.NewV4()
	return graphql.ID(id.String())
}

// RRName returns the RRName field of the corresponding entry.
func (r *EntryResolver) RRName() string {
	return r.entry.RRName
}

// Rdata returns the Rdata field of the corresponding entry.
func (r *EntryResolver) Rdata() string {
	return r.entry.RData
}

// RRType returns the RRType field of the corresponding entry.
func (r *EntryResolver) RRType() *string {
	return &r.entry.RRType
}

// Count returns the Count field of the corresponding entry.
func (r *EntryResolver) Count() int32 {
	return int32(r.entry.Count)
}

// TimeFirst returns the first seen timestamp of the corresponding entry.
func (r *EntryResolver) TimeFirst() int32 {
	return int32(r.entry.FirstSeen.Unix())
}

// TimeFirstRFC3339 returns first seen time, as RFC 3339 string, of the corresponding entry.
func (r *EntryResolver) TimeFirstRFC3339() string {
	return r.entry.FirstSeen.Format(time.RFC3339)
}

// TimeLast returns the last seen timestamp of the corresponding entry.
func (r *EntryResolver) TimeLast() int32 {
	return int32(r.entry.LastSeen.Unix())
}

// TimeLastRFC3339 returns last seen time, as RFC 3339 string, of the corresponding entry.
func (r *EntryResolver) TimeLastRFC3339() string {
	return r.entry.LastSeen.Format(time.RFC3339)
}

// SensorID returns the sensor ID field of the corresponding entry.
func (r *EntryResolver) SensorID() *string {
	return &r.entry.SensorID
}

// Aliases returns resolvers for Entries with the same IPs in Rdata (for
// A/AAAA type entries).
func (r *EntryResolver) Aliases(args struct{ Limit int32 }) *[]*EntryResolver {
	l := make([]*EntryResolver, 0)
	if !(r.entry.RRType == "A" || r.entry.RRType == "AAAA") {
		return nil
	}
	results, err := db.ObservationDB.Search(&r.entry.RData, nil, nil, &r.entry.SensorID, int(args.Limit))
	if err != nil {
		return nil
	}
	for _, rs := range results {
		if rs.RRName != r.entry.RRName {
			er := EntryResolver{
				entry: rs,
			}
			l = append(l, &er)
		}
	}
	return &l
}

// Run starts this instance of a GraphQLFrontend in the background, accepting
// new requests on the configured port.
func (g *GraphQLFrontend) Run(port int) {
	schema := graphql.MustParseSchema(txtSchema, &Resolver{})
	g.Server = &http.Server{
		Addr:         fmt.Sprintf(":%v", port),
		Handler:      &relay.Handler{Schema: schema},
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	log.Infof("serving GraphQL on port %v", port)
	go func() {
		err := g.Server.ListenAndServe()
		if err != nil {
			log.Info(err)
		}
		g.IsRunning = true
	}()
}

// Stop causes this instance of a GraphQLFrontend to cease accepting requests.
func (g *GraphQLFrontend) Stop() {
	if g.IsRunning {
		g.Server.Shutdown(context.TODO())
	}
}