emissary/internal/client/query_agents.go

100 lines
2.3 KiB
Go
Raw Normal View History

2023-02-02 10:55:24 +01:00
package client
import (
"context"
"fmt"
"net/url"
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
"github.com/pkg/errors"
)
type QueryAgentsOptionFunc func(*QueryAgentsOptions)
type QueryAgentsOptions struct {
Options []OptionFunc
Limit *int
Offset *int
Thumbprints []string
IDs []datastore.AgentID
Statuses []datastore.AgentStatus
2023-02-02 10:55:24 +01:00
}
func WithQueryAgentsOptions(funcs ...OptionFunc) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.Options = funcs
}
}
2023-02-02 10:55:24 +01:00
func WithQueryAgentsLimit(limit int) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.Limit = &limit
}
}
func WithQueryAgentsOffset(offset int) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.Offset = &offset
}
}
func WithQueryAgentsThumbprints(thumbprints ...string) QueryAgentsOptionFunc {
2023-02-02 10:55:24 +01:00
return func(opts *QueryAgentsOptions) {
opts.Thumbprints = thumbprints
2023-02-02 10:55:24 +01:00
}
}
func WithQueryAgentsID(ids ...datastore.AgentID) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.IDs = ids
}
}
func WithQueryAgentsStatus(statuses ...datastore.AgentStatus) QueryAgentsOptionFunc {
return func(opts *QueryAgentsOptions) {
opts.Statuses = statuses
}
}
func (c *Client) QueryAgents(ctx context.Context, funcs ...QueryAgentsOptionFunc) ([]*datastore.Agent, int, error) {
options := &QueryAgentsOptions{}
for _, fn := range funcs {
fn(options)
}
query := url.Values{}
if options.IDs != nil && len(options.IDs) > 0 {
query.Set("ids", joinSlice(options.IDs))
}
if options.Thumbprints != nil && len(options.Thumbprints) > 0 {
query.Set("thumbprints", joinSlice(options.Thumbprints))
2023-02-02 10:55:24 +01:00
}
if options.Statuses != nil && len(options.Statuses) > 0 {
2023-02-02 10:55:24 +01:00
query.Set("statuses", joinSlice(options.Statuses))
}
path := fmt.Sprintf("/api/v1/agents?%s", query.Encode())
response := withResponse[struct {
Agents []*datastore.Agent `json:"agents"`
Total int `json:"total"`
}]()
if options.Options == nil {
options.Options = make([]OptionFunc, 0)
}
if err := c.apiGet(ctx, path, &response, options.Options...); err != nil {
2023-02-02 10:55:24 +01:00
return nil, 0, errors.WithStack(err)
}
if response.Error != nil {
return nil, 0, errors.WithStack(response.Error)
}
return response.Data.Agents, response.Data.Total, nil
}