2016-11-29 18:20:06 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
2017-03-15 15:55:30 +00:00
|
|
|
"context"
|
2016-11-29 18:20:06 +00:00
|
|
|
"fmt"
|
2020-03-23 01:33:04 +00:00
|
|
|
"strconv"
|
2016-11-29 18:20:06 +00:00
|
|
|
"time"
|
|
|
|
|
2020-11-11 17:59:12 +00:00
|
|
|
"github.com/fleetdm/fleet/server/contexts/viewer"
|
|
|
|
"github.com/fleetdm/fleet/server/kolide"
|
2021-05-27 03:45:06 +00:00
|
|
|
"github.com/fleetdm/fleet/server/ptr"
|
2020-11-11 17:59:12 +00:00
|
|
|
"github.com/fleetdm/fleet/server/websocket"
|
2020-12-15 02:13:34 +00:00
|
|
|
"github.com/igm/sockjs-go/v3/sockjs"
|
2016-12-01 21:21:27 +00:00
|
|
|
"github.com/pkg/errors"
|
2016-11-29 18:20:06 +00:00
|
|
|
)
|
|
|
|
|
2021-06-01 00:07:51 +00:00
|
|
|
func (svc Service) NewDistributedQueryCampaignByNames(ctx context.Context, queryString string, queryID *uint, hosts []string, labels []string) (*kolide.DistributedQueryCampaign, error) {
|
2018-05-17 22:54:34 +00:00
|
|
|
hostIDs, err := svc.ds.HostIDsByName(hosts)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "finding host IDs")
|
|
|
|
}
|
|
|
|
|
|
|
|
labelIDs, err := svc.ds.LabelIDsByName(labels)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "finding label IDs")
|
|
|
|
}
|
|
|
|
|
2021-05-27 20:18:00 +00:00
|
|
|
// TODO handle teams
|
|
|
|
|
|
|
|
targets := kolide.HostTargets{HostIDs: hostIDs, LabelIDs: labelIDs}
|
|
|
|
return svc.NewDistributedQueryCampaign(ctx, queryString, queryID, targets)
|
2018-05-17 22:54:34 +00:00
|
|
|
}
|
|
|
|
|
2021-06-01 00:07:51 +00:00
|
|
|
func (svc Service) NewDistributedQueryCampaign(ctx context.Context, queryString string, queryID *uint, targets kolide.HostTargets) (*kolide.DistributedQueryCampaign, error) {
|
2020-01-14 00:53:04 +00:00
|
|
|
if err := svc.StatusLiveQuery(ctx); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2016-11-29 18:20:06 +00:00
|
|
|
vc, ok := viewer.FromContext(ctx)
|
|
|
|
if !ok {
|
2021-06-01 00:07:51 +00:00
|
|
|
return nil, kolide.ErrNoContext
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
|
2021-05-27 03:45:06 +00:00
|
|
|
if queryID == nil && queryString == "" {
|
2021-06-01 00:07:51 +00:00
|
|
|
return nil, kolide.NewInvalidArgumentError("query", "one of query or query_id must be specified")
|
2021-05-27 03:45:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var query *kolide.Query
|
|
|
|
if queryID != nil {
|
|
|
|
query, err := svc.ds.Query(*queryID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
queryString = query.Query
|
|
|
|
} else {
|
|
|
|
query = &kolide.Query{
|
|
|
|
Name: fmt.Sprintf("distributed_%s_%d", vc.Username(), time.Now().Unix()),
|
|
|
|
Query: queryString,
|
|
|
|
Saved: false,
|
|
|
|
AuthorID: ptr.Uint(vc.UserID()),
|
|
|
|
}
|
2020-12-15 02:13:34 +00:00
|
|
|
}
|
|
|
|
if err := query.ValidateSQL(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
query, err := svc.ds.NewQuery(query)
|
2016-11-29 18:20:06 +00:00
|
|
|
if err != nil {
|
2016-12-01 21:21:27 +00:00
|
|
|
return nil, errors.Wrap(err, "new query")
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
campaign, err := svc.ds.NewDistributedQueryCampaign(&kolide.DistributedQueryCampaign{
|
|
|
|
QueryID: query.ID,
|
2016-12-01 18:31:16 +00:00
|
|
|
Status: kolide.QueryWaiting,
|
2016-11-29 18:20:06 +00:00
|
|
|
UserID: vc.UserID(),
|
|
|
|
})
|
|
|
|
if err != nil {
|
2016-12-01 21:21:27 +00:00
|
|
|
return nil, errors.Wrap(err, "new campaign")
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add host targets
|
2021-05-27 20:18:00 +00:00
|
|
|
for _, hid := range targets.HostIDs {
|
2016-11-29 18:20:06 +00:00
|
|
|
_, err = svc.ds.NewDistributedQueryCampaignTarget(&kolide.DistributedQueryCampaignTarget{
|
2020-01-14 00:53:04 +00:00
|
|
|
Type: kolide.TargetHost,
|
2016-11-29 18:20:06 +00:00
|
|
|
DistributedQueryCampaignID: campaign.ID,
|
|
|
|
TargetID: hid,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2016-12-01 21:21:27 +00:00
|
|
|
return nil, errors.Wrap(err, "adding host target")
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add label targets
|
2021-05-27 20:18:00 +00:00
|
|
|
for _, lid := range targets.LabelIDs {
|
2016-11-29 18:20:06 +00:00
|
|
|
_, err = svc.ds.NewDistributedQueryCampaignTarget(&kolide.DistributedQueryCampaignTarget{
|
2020-01-14 00:53:04 +00:00
|
|
|
Type: kolide.TargetLabel,
|
2016-11-29 18:20:06 +00:00
|
|
|
DistributedQueryCampaignID: campaign.ID,
|
|
|
|
TargetID: lid,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2016-12-01 21:21:27 +00:00
|
|
|
return nil, errors.Wrap(err, "adding label target")
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
}
|
2020-03-23 01:33:04 +00:00
|
|
|
|
2021-05-27 20:18:00 +00:00
|
|
|
// Add team targets
|
|
|
|
for _, lid := range targets.TeamIDs {
|
|
|
|
_, err = svc.ds.NewDistributedQueryCampaignTarget(&kolide.DistributedQueryCampaignTarget{
|
|
|
|
Type: kolide.TargetTeam,
|
|
|
|
DistributedQueryCampaignID: campaign.ID,
|
|
|
|
TargetID: lid,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "adding team target")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-25 04:34:08 +00:00
|
|
|
filter := kolide.TeamFilter{User: vc.User}
|
|
|
|
|
2021-05-27 20:18:00 +00:00
|
|
|
hostIDs, err := svc.ds.HostIDsInTargets(filter, targets)
|
2020-03-23 01:33:04 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "get target IDs")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = svc.liveQueryStore.RunQuery(strconv.Itoa(int(campaign.ID)), queryString, hostIDs)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "run query")
|
|
|
|
}
|
|
|
|
|
2021-05-27 20:18:00 +00:00
|
|
|
campaign.Metrics, err = svc.ds.CountHostsInTargets(filter, targets, time.Now())
|
2019-12-04 17:42:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "counting hosts")
|
|
|
|
}
|
2016-11-29 18:20:06 +00:00
|
|
|
return campaign, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type targetTotals struct {
|
2016-12-06 17:37:22 +00:00
|
|
|
Total uint `json:"count"`
|
|
|
|
Online uint `json:"online"`
|
|
|
|
Offline uint `json:"offline"`
|
|
|
|
MissingInAction uint `json:"missing_in_action"`
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
|
2017-01-20 18:57:41 +00:00
|
|
|
const (
|
|
|
|
campaignStatusPending = "pending"
|
|
|
|
campaignStatusFinished = "finished"
|
|
|
|
)
|
|
|
|
|
|
|
|
type campaignStatus struct {
|
|
|
|
ExpectedResults uint `json:"expected_results"`
|
|
|
|
ActualResults uint `json:"actual_results"`
|
|
|
|
Status string `json:"status"`
|
|
|
|
}
|
|
|
|
|
2021-06-01 00:07:51 +00:00
|
|
|
func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Conn, campaignID uint) {
|
2016-11-29 18:20:06 +00:00
|
|
|
// Find the campaign and ensure it is active
|
|
|
|
campaign, err := svc.ds.DistributedQueryCampaign(campaignID)
|
|
|
|
if err != nil {
|
|
|
|
conn.WriteJSONError(fmt.Sprintf("cannot find campaign for ID %d", campaignID))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-07-01 17:51:34 +00:00
|
|
|
// Open the channel from which we will receive incoming query results
|
|
|
|
// (probably from the redis pubsub implementation)
|
|
|
|
readChan, err := svc.resultStore.ReadChannel(context.Background(), *campaign)
|
|
|
|
if err != nil {
|
|
|
|
conn.WriteJSONError(fmt.Sprintf("cannot open read channel for campaign %d ", campaignID))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-12-01 18:31:16 +00:00
|
|
|
// Setting status to running will cause the query to be returned to the
|
|
|
|
// targets when they check in for their queries
|
|
|
|
campaign.Status = kolide.QueryRunning
|
|
|
|
if err := svc.ds.SaveDistributedQueryCampaign(campaign); err != nil {
|
|
|
|
conn.WriteJSONError("error saving campaign state")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Setting the status to completed stops the query from being sent to
|
|
|
|
// targets. If this fails, there is a background job that will clean up
|
|
|
|
// this campaign.
|
|
|
|
defer func() {
|
|
|
|
campaign.Status = kolide.QueryComplete
|
2020-07-01 17:51:34 +00:00
|
|
|
_ = svc.ds.SaveDistributedQueryCampaign(campaign)
|
|
|
|
_ = svc.liveQueryStore.StopQuery(strconv.Itoa(int(campaign.ID)))
|
2016-12-01 18:31:16 +00:00
|
|
|
}()
|
|
|
|
|
2017-01-20 18:57:41 +00:00
|
|
|
status := campaignStatus{
|
|
|
|
Status: campaignStatusPending,
|
|
|
|
}
|
2018-05-17 22:54:34 +00:00
|
|
|
lastStatus := status
|
|
|
|
lastTotals := targetTotals{}
|
2017-01-20 18:57:41 +00:00
|
|
|
|
2017-01-23 17:37:03 +00:00
|
|
|
// to improve performance of the frontend rendering the results table, we
|
2021-02-03 16:47:43 +00:00
|
|
|
// add the "host_hostname" field to every row and clean null rows.
|
|
|
|
mapHostnameRows := func(res *kolide.DistributedQueryResult) {
|
|
|
|
filteredRows := []map[string]string{}
|
|
|
|
for _, row := range res.Rows {
|
|
|
|
if row == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
row["host_hostname"] = res.Host.HostName
|
|
|
|
filteredRows = append(filteredRows, row)
|
2017-01-23 17:37:03 +00:00
|
|
|
}
|
2021-02-03 16:47:43 +00:00
|
|
|
|
|
|
|
res.Rows = filteredRows
|
2017-01-23 17:37:03 +00:00
|
|
|
}
|
|
|
|
|
2021-05-27 20:18:00 +00:00
|
|
|
targets, err := svc.ds.DistributedQueryCampaignTargetIDs(campaign.ID)
|
2020-03-23 01:33:04 +00:00
|
|
|
if err != nil {
|
|
|
|
conn.WriteJSONError("error retrieving campaign targets: " + err.Error())
|
|
|
|
return
|
|
|
|
}
|
2017-02-10 00:12:13 +00:00
|
|
|
|
2020-03-23 01:33:04 +00:00
|
|
|
updateStatus := func() error {
|
2021-05-27 20:18:00 +00:00
|
|
|
metrics, err := svc.CountHostsInTargets(context.Background(), &campaign.QueryID, *targets)
|
2017-02-10 00:12:13 +00:00
|
|
|
if err != nil {
|
|
|
|
if err = conn.WriteJSONError("error retrieving target counts"); err != nil {
|
2021-05-26 01:53:22 +00:00
|
|
|
return errors.Wrap(err, "retrieve target counts, write failed")
|
2017-02-10 00:12:13 +00:00
|
|
|
}
|
2021-05-26 01:53:22 +00:00
|
|
|
return errors.Wrap(err, "retrieve target counts")
|
2017-02-10 00:12:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
totals := targetTotals{
|
|
|
|
Total: metrics.TotalHosts,
|
|
|
|
Online: metrics.OnlineHosts,
|
|
|
|
Offline: metrics.OfflineHosts,
|
|
|
|
MissingInAction: metrics.MissingInActionHosts,
|
|
|
|
}
|
2018-05-17 22:54:34 +00:00
|
|
|
if lastTotals != totals {
|
|
|
|
lastTotals = totals
|
|
|
|
if err = conn.WriteJSONMessage("totals", totals); err != nil {
|
2021-05-25 16:15:39 +00:00
|
|
|
return errors.Wrap(err, "write totals")
|
2018-05-17 22:54:34 +00:00
|
|
|
}
|
2017-02-10 00:12:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
status.ExpectedResults = totals.Online
|
|
|
|
if status.ActualResults >= status.ExpectedResults {
|
|
|
|
status.Status = campaignStatusFinished
|
|
|
|
}
|
|
|
|
// only write status message if status has changed
|
2018-05-17 22:54:34 +00:00
|
|
|
if lastStatus != status {
|
|
|
|
lastStatus = status
|
2017-02-10 00:12:13 +00:00
|
|
|
if err = conn.WriteJSONMessage("status", status); err != nil {
|
2021-05-25 16:15:39 +00:00
|
|
|
return errors.Wrap(err, "write status")
|
2017-02-10 00:12:13 +00:00
|
|
|
}
|
|
|
|
}
|
2018-12-21 01:44:49 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := updateStatus(); err != nil {
|
2020-07-01 17:51:34 +00:00
|
|
|
_ = svc.logger.Log("msg", "error updating status", "err", err)
|
2018-12-21 01:44:49 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Push status updates every 5 seconds at most
|
|
|
|
ticker := time.NewTicker(5 * time.Second)
|
|
|
|
defer ticker.Stop()
|
|
|
|
// Loop, pushing updates to results and expected totals
|
|
|
|
for {
|
|
|
|
// Update the expected hosts total (Should happen before
|
|
|
|
// any results are written, to avoid the frontend showing "x of
|
|
|
|
// 0 Hosts Returning y Records")
|
2016-11-29 18:20:06 +00:00
|
|
|
select {
|
|
|
|
case res := <-readChan:
|
|
|
|
// Receive a result and push it over the websocket
|
|
|
|
switch res := res.(type) {
|
|
|
|
case kolide.DistributedQueryResult:
|
2021-02-03 16:47:43 +00:00
|
|
|
mapHostnameRows(&res)
|
2016-11-29 18:20:06 +00:00
|
|
|
err = conn.WriteJSONMessage("result", res)
|
2020-07-01 17:51:34 +00:00
|
|
|
if errors.Cause(err) == sockjs.ErrSessionNotOpen {
|
|
|
|
// return and stop sending the query if the session was closed
|
|
|
|
// by the client
|
|
|
|
return
|
|
|
|
}
|
2016-11-29 18:20:06 +00:00
|
|
|
if err != nil {
|
2020-07-01 17:51:34 +00:00
|
|
|
_ = svc.logger.Log("msg", "error writing to channel", "err", err)
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
2017-01-20 18:57:41 +00:00
|
|
|
status.ActualResults++
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
|
2018-12-21 01:44:49 +00:00
|
|
|
case <-ticker.C:
|
2020-03-23 01:33:04 +00:00
|
|
|
if conn.GetSessionState() == sockjs.SessionClosed {
|
|
|
|
// return and stop sending the query if the session was closed
|
|
|
|
// by the client
|
|
|
|
return
|
|
|
|
}
|
2018-12-21 01:44:49 +00:00
|
|
|
// Update status
|
|
|
|
if err := updateStatus(); err != nil {
|
|
|
|
svc.logger.Log("msg", "error updating status", "err", err)
|
|
|
|
return
|
|
|
|
}
|
2016-11-29 18:20:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|