-
Notifications
You must be signed in to change notification settings - Fork 113
/
pgserver.go
425 lines (371 loc) · 13.1 KB
/
pgserver.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
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
415
416
417
418
419
420
421
422
423
424
425
package profiles
import (
"bytes"
"context"
"io"
"io/ioutil"
"os"
"github.com/gofrs/uuid"
"github.com/golang/protobuf/ptypes"
pb "github.com/golang/protobuf/ptypes/empty"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/chef/automate/api/interservice/compliance/profiles"
automate_event "github.com/chef/automate/api/interservice/event"
"github.com/chef/automate/components/compliance-service/api/profiles/conversion"
"github.com/chef/automate/components/compliance-service/config"
"github.com/chef/automate/components/compliance-service/ingest/ingestic"
"github.com/chef/automate/components/compliance-service/inspec"
dbstore "github.com/chef/automate/components/compliance-service/profiles/db"
"github.com/chef/automate/components/compliance-service/profiles/market"
"github.com/chef/automate/components/compliance-service/reporting/relaxting"
"github.com/chef/automate/components/compliance-service/reporting/util"
event "github.com/chef/automate/components/event-service/config"
)
// PGProfileServer implements the profile store GRPC interface
type PGProfileServer struct {
es *relaxting.ES2Backend
esClient *ingestic.ESClient
profiles *config.Profiles
store *dbstore.Store
eventsClient automate_event.EventServiceClient
}
func (srv *PGProfileServer) convertProfileToTgz(reader io.ReadCloser, contentType string) (string, error) {
var tmpWithSuffix string
switch contentType {
case "application/gzip", "application/x-gzip", "application/x-gtar", "application/x-tar; charset=gzip":
var err error
// we are good, nothing to do
tmpWithSuffix, err = market.TempUpload(reader, ".tar.gz")
if err != nil {
return "", err
}
case "application/zip", "application/x-zip-compressed":
// need to convert zip to tar.gz
logrus.Debug("convert zip archive to tar.gz")
tmpZipUpload, err := market.TempUpload(reader, ".zip")
defer func() {
if logrus.GetLevel() < 5 {
err := os.Remove(tmpZipUpload)
if err != nil {
logrus.Errorf("could not delete the cache file %s: %s", tmpZipUpload, err.Error())
}
} else {
logrus.Debugf("Did not delete %s for troubleshooting purposes", tmpZipUpload)
}
}()
if err != nil {
return "", err
}
tmpWithSuffix, err = market.TempFileWithSuffix(".tar.gz")
if err != nil {
return "", err
}
err = util.ConvertZipToTarGz(tmpZipUpload, tmpWithSuffix)
if err != nil {
return "", err
}
}
return tmpWithSuffix, nil
}
func (srv *PGProfileServer) storeProfile(owner string, cacheFile string) (inspec.CheckResult, error) {
var inspecCheckResult inspec.CheckResult
// Run InSpec check
inspecCheckResult, err := market.CheckProfile(cacheFile)
if err != nil {
logrus.Errorf("Create CheckProfile error: %s", err.Error())
inspecCheckResult.Summary.Valid = false
inspecCheckResult.Errors = []inspec.CheckMessage{{Msg: err.Error()}}
return inspecCheckResult, status.Error(codes.InvalidArgument, err.Error())
}
sha256, tar, info, err := srv.store.GetProfileInfo(cacheFile)
if err != nil {
logrus.Errorf("Create GetProfileInfo error: %s", err.Error())
inspecCheckResult.Summary.Valid = false
inspecCheckResult.Errors = []inspec.CheckMessage{{Msg: err.Error()}}
return inspecCheckResult, status.Error(codes.Internal, err.Error())
}
// send the profile json to reporting component
esInfo := inspec.Profile{}
err = esInfo.FromJSON(info)
if err != nil {
logrus.Errorf("could not parse json: %s", err.Error())
inspecCheckResult.Summary.Valid = false
inspecCheckResult.Errors = []inspec.CheckMessage{{Msg: err.Error()}}
return inspecCheckResult, status.Error(codes.Internal, err.Error())
}
err = srv.es.StoreProfile(esInfo)
if err != nil {
logrus.Errorf("could not store profile information in elastic: %s", err.Error())
inspecCheckResult.Summary.Valid = false
inspecCheckResult.Errors = []inspec.CheckMessage{{Msg: err.Error()}}
return inspecCheckResult, status.Error(codes.Internal, err.Error())
}
// store profile in profile store
err = srv.store.UploadProfile(sha256, owner, tar, info)
if err != nil {
logrus.Errorf("Create StoreProfile error: %s", err.Error())
return inspecCheckResult, status.Error(codes.Internal, err.Error())
}
// fire profile created event
go srv.fireEvent(event.ProfileCreatedEventName, owner, esInfo.Name, esInfo.Version)
return inspecCheckResult, nil
}
func (srv *PGProfileServer) Create(stream profiles.ProfilesService_CreateServer) error {
in, err := stream.Recv()
if err != io.EOF && err != nil {
return err
}
// ensure that metadata is set
if in.GetMeta() == nil {
return status.Error(codes.InvalidArgument, "meta must be specified for profile upload")
}
// fallback if no content type is set
if len(in.GetMeta().ContentType) == 0 {
in.GetMeta().ContentType = "application/x-gtar"
}
if in.Owner == "" {
return status.Error(codes.InvalidArgument, "owner must be specified for profile upload.")
}
// verify that we accept the content
logrus.Debugf("Content Type %s", in.GetMeta().ContentType)
var reader io.ReadCloser
if in.GetMeta().ContentType == "application/json" || in.GetMeta().ContentType == "application/json+lax" {
namespace := in.Owner
name := in.GetMeta().Name
version := in.GetMeta().Version
if len(namespace) == 0 && len(name) == 0 {
logrus.Errorf("Could not understand the given request")
return status.Error(codes.InvalidArgument, "no namespace given")
}
logrus.Infof("Install market profile %s into %s", name, namespace)
// Verify that the profile exists
_, err := srv.store.ReadMarket(name, version)
if err != nil {
// profile does not exist
return status.Error(codes.NotFound, "could not find profile")
}
// install the profile into the namespace
err = srv.store.InstallMarket(namespace, name, version)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
// fire profile created event
go srv.fireEvent(event.ProfileCreatedEventName, in.Owner, in.Meta.Name, in.Meta.Version)
// send an empty result, since it is not relevant for marketplace installation
res := &profiles.CheckResult{}
res.Summary = &profiles.ResultSummary{}
res.Summary.Valid = true
err = stream.SendAndClose(res)
if err != nil {
logrus.Error(err)
return err
}
} else {
// get reader
reader = ioutil.NopCloser(bytes.NewReader(in.GetChunk().Data))
cacheFile, err := srv.convertProfileToTgz(reader, in.GetMeta().ContentType)
if err != nil {
logrus.Errorf("error during zip to tar.gz conversion: %s", err.Error())
return status.Error(codes.Internal, err.Error())
}
defer func() {
if logrus.GetLevel() < 5 {
err := os.Remove(cacheFile)
if err != nil {
logrus.Errorf("could not delete the cache file %s: %s", cacheFile, err.Error())
}
} else {
logrus.Debugf("did not delete %s for troubleshooting purposes", cacheFile)
}
}()
inspecCheckResult, err := srv.storeProfile(in.Owner, cacheFile)
if err != nil {
return err
}
checkResult := inspecCheckResultToGrpcCheckResult(inspecCheckResult)
err = stream.SendAndClose(&checkResult)
if err != nil {
logrus.Error(err)
return err
}
}
return nil
}
func (srv *PGProfileServer) Read(ctx context.Context, in *profiles.ProfileDetails) (*profiles.Profile, error) {
logrus.Infof("Reading profile: %+v", in)
var profile *inspec.Profile
var err error
if in.Owner == "" {
// market profile
profile, err = srv.store.ReadMarket(in.Name, in.Version)
} else {
// namespaced profile
profile, err = srv.store.Read(in.Owner, in.Name, in.Version)
}
if err != nil {
logrus.Error(err)
return nil, status.Error(codes.NotFound, "could not determine profile information")
}
p, err := conversion.ConvertToPSProfile(*profile, in.Owner)
if err != nil {
logrus.Error(err)
return nil, status.Error(codes.Internal, "could not generate response")
}
return &p, nil
}
func (srv *PGProfileServer) ReadTar(in *profiles.ProfileDetails, stream profiles.ProfilesService_ReadTarServer) (err error) {
logrus.Infof("Reading profile tar: %+v", in)
var tarBlob []byte
if len(in.Owner) > 0 {
tarBlob, err = srv.store.ReadTar(in.Owner, in.Name, in.Version)
if err != nil {
logrus.Errorf("ReadTar ReadFile: %s", err.Error())
return status.Error(codes.NotFound, "we could not find the requested profile")
}
} else {
tarBlob, err = srv.store.ReadMarketTar(in.Name, in.Version)
if err != nil {
logrus.Errorf("ReadTar ReadFile: %s", err.Error())
return status.Error(codes.NotFound, "we could not find the requested profile")
}
}
profileData := &profiles.ProfileData{Data: tarBlob}
err = stream.Send(profileData)
if err != nil {
logrus.Error(err)
return status.Error(codes.Internal, "we could not find the requested profile")
}
return nil
}
// Check the existence of profile IDs(sha256) in the comp-*-profiles ES index
func (srv *PGProfileServer) MetaSearch(ctx context.Context, profileSha256 *profiles.Sha256) (*profiles.Missing, error) {
logrus.Debugf("Checking if profiles with sha256 IDs %v are already stored in ElasticSearch", profileSha256.Sha256)
profilesMetaMissing, err := srv.esClient.ProfilesMissing(profileSha256.Sha256)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
exists := profiles.Missing{
MissingSha256: profilesMetaMissing,
}
return &exists, nil
}
// Delete never deletes a profile, it only deletes the associations
func (srv *PGProfileServer) Delete(ctx context.Context, in *profiles.ProfileDetails) (*pb.Empty, error) {
logrus.Infof("Deleting profile: %+v", in)
err := srv.store.Delete(in.Owner, in.Name, in.Version)
if err != nil {
logrus.Errorf("Delete: %s", err.Error())
return nil, status.Error(codes.NotFound, "we could not delete the requested profile")
}
// fire profile deleted event
go srv.fireEvent(event.ProfileDeletedEventName, in.Owner, in.Name, in.Version)
return &pb.Empty{}, nil
}
func (srv *PGProfileServer) List(ctx context.Context, in *profiles.Query) (*profiles.Profiles, error) {
sortOrder := in.Order.String()
sortField := in.Sort
if sortField == "" {
sortField = "title"
}
filters := make(map[string][]string)
for _, filter := range in.Filters {
filters[filter.Type] = filter.Values
}
logrus.WithFields(logrus.Fields{
"filters": filters,
"name": in.Name,
"namespace": in.Owner,
"page": in.Page,
"per_page": in.PerPage,
"sortField": sortField,
"sortOrder": sortOrder,
}).Infof("Listing profiles")
metadata, total, err := srv.store.ListProfilesMetadata(dbstore.ProfilesListRequest{
Filters: filters,
Name: in.Name,
Namespace: in.Owner,
Order: sortOrder,
Page: int(in.Page),
PerPage: int(in.PerPage),
Sort: sortField,
})
if err != nil {
return nil, err
}
// convert metadata to profile
profiles := conversion.ConvertInspecMetadatasToProfiles(metadata, in.Owner)
profiles.Total = int32(total)
return profiles, nil
}
func (srv *PGProfileServer) RebuildElasticCache(ctx context.Context, in *pb.Empty) (*pb.Empty, error) {
err := srv.rebuildElasticProfileCache()
if err != nil {
logrus.Error(err)
return nil, status.Error(codes.Internal, "we could not rebuild the cache")
}
return &pb.Empty{}, nil
}
func (srv *PGProfileServer) MigrateDiskProfiles(ctx context.Context, in *pb.Empty) (*pb.Empty, error) {
err := srv.migrateDiskProfiles()
if err != nil {
logrus.Error(err)
return nil, status.Error(codes.Internal, "we could not migrate the profiles")
}
return &pb.Empty{}, nil
}
func (srv *PGProfileServer) fireEvent(eventType string, owner string, name string, version string) {
event := srv.newEventMsg(eventType, owner, name, version)
req := automate_event.PublishRequest{Msg: event}
_, err := srv.eventsClient.Publish(context.Background(), &req)
if err != nil {
logrus.Warnf("Error publishing profiles event: %v", err)
return
}
}
func (srv *PGProfileServer) newEventMsg(eventType string, owner string, name string, version string) *automate_event.EventMsg {
var (
verbVal string
tagsVal []string
nameVal = name + " version " + version
userVal = owner
)
switch eventType {
case event.ProfileCreatedEventName:
verbVal = "create"
tagsVal = []string{"profile", userVal, "create", "compliance", event.ProfileCreatedEventName}
case event.ProfileDeletedEventName:
verbVal = "delete"
tagsVal = []string{"profile", userVal, "delete", "compliance", event.ProfileDeletedEventName}
default:
logrus.Warnf("Could not generate event message for profile %s; unknown event type %s", nameVal, eventType)
}
return &automate_event.EventMsg{
EventID: uuid.Must(uuid.NewV4()).String(),
Type: &automate_event.EventType{Name: eventType},
Producer: &automate_event.Producer{
ID: "profile",
ProducerName: "Profile",
ProducerType: "system component",
},
Tags: tagsVal,
Published: ptypes.TimestampNow(),
Actor: &automate_event.Actor{
ID: "",
ObjectType: "User",
DisplayName: userVal,
},
Verb: verbVal,
Object: &automate_event.Object{
ID: uuid.Must(uuid.NewV4()).String(),
ObjectType: "profile",
DisplayName: nameVal,
},
Target: &automate_event.Target{
ID: "",
ObjectType: "Not Applicable",
DisplayName: "Not Applicable",
},
}
}