2020-01-24 05:27:20 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
2021-06-26 04:46:51 +00:00
|
|
|
"github.com/fleetdm/fleet/v4/server/fleet"
|
2020-01-24 05:27:20 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// SearchTargets searches for the supplied targets in the Fleet instance.
|
2021-06-06 22:07:29 +00:00
|
|
|
func (c *Client) SearchTargets(query string, hostIDs, labelIDs []uint) (*fleet.TargetSearchResults, error) {
|
2020-01-24 05:27:20 +00:00
|
|
|
req := searchTargetsRequest{
|
2021-05-27 03:45:06 +00:00
|
|
|
MatchQuery: query,
|
2021-06-06 22:07:29 +00:00
|
|
|
Selected: fleet.HostTargets{
|
2021-05-27 20:18:00 +00:00
|
|
|
LabelIDs: labelIDs,
|
|
|
|
HostIDs: hostIDs,
|
|
|
|
// TODO handle TeamIDs
|
2020-01-24 05:27:20 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2021-02-10 20:13:11 +00:00
|
|
|
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/targets", "", req)
|
2020-01-24 05:27:20 +00:00
|
|
|
if err != nil {
|
2021-02-10 20:13:11 +00:00
|
|
|
return nil, errors.Wrap(err, "POST /api/v1/fleet/targets")
|
2020-01-24 05:27:20 +00:00
|
|
|
}
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
return nil, errors.Errorf(
|
|
|
|
"SearchTargets received status %d %s",
|
|
|
|
response.StatusCode,
|
|
|
|
extractServerErrorText(response.Body),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
var responseBody searchTargetsResponse
|
|
|
|
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "decode SearchTargets response")
|
|
|
|
}
|
|
|
|
|
|
|
|
if responseBody.Err != nil {
|
|
|
|
return nil, errors.Errorf("SearchTargets: %s", responseBody.Err)
|
|
|
|
}
|
|
|
|
|
2021-06-06 22:07:29 +00:00
|
|
|
hosts := make([]*fleet.Host, len(responseBody.Targets.Hosts))
|
2020-01-24 05:27:20 +00:00
|
|
|
for i, h := range responseBody.Targets.Hosts {
|
2020-03-31 23:14:26 +00:00
|
|
|
hosts[i] = h.HostResponse.Host
|
2020-01-24 05:27:20 +00:00
|
|
|
}
|
|
|
|
|
2021-06-06 22:07:29 +00:00
|
|
|
labels := make([]*fleet.Label, len(responseBody.Targets.Labels))
|
2020-01-24 05:27:20 +00:00
|
|
|
for i, h := range responseBody.Targets.Labels {
|
|
|
|
labels[i] = h.Label
|
|
|
|
}
|
|
|
|
|
2021-06-06 22:07:29 +00:00
|
|
|
return &fleet.TargetSearchResults{
|
2020-01-24 05:27:20 +00:00
|
|
|
Hosts: hosts,
|
|
|
|
Labels: labels,
|
|
|
|
}, nil
|
|
|
|
}
|