Remove kolide types and packages from backend (#974)

Generally renamed `kolide` -> `fleet`
This commit is contained in:
Zach Wasserman 2021-06-06 15:07:29 -07:00 committed by GitHub
parent fa01df79d5
commit fb32f0cf40
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
256 changed files with 3274 additions and 3264 deletions

View File

@ -57,7 +57,7 @@ wish to override the default value.
return rootCmd
}
func applyDevFlags(cfg *config.KolideConfig) {
func applyDevFlags(cfg *config.FleetConfig) {
cfg.Mysql.Username = "fleet"
cfg.Mysql.Database = "fleet"
cfg.Mysql.Password = "insecure"

View File

@ -8,7 +8,7 @@ import (
"github.com/WatchBeam/clock"
"github.com/fleetdm/fleet/server/config"
"github.com/fleetdm/fleet/server/datastore/mysql"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/spf13/cobra"
)
@ -53,11 +53,11 @@ To setup Fleet infrastructure, use one of the available commands.
}
switch status {
case kolide.AllMigrationsCompleted:
case fleet.AllMigrationsCompleted:
fmt.Println("Migrations already completed. Nothing to do.")
return
case kolide.SomeMigrationsCompleted:
case fleet.SomeMigrationsCompleted:
if !noPrompt {
fmt.Printf("################################################################################\n" +
"# WARNING:\n" +

View File

@ -21,8 +21,8 @@ import (
"github.com/fleetdm/fleet/server/config"
"github.com/fleetdm/fleet/server/datastore/mysql"
"github.com/fleetdm/fleet/server/datastore/s3"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/health"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/launcher"
"github.com/fleetdm/fleet/server/live_query"
"github.com/fleetdm/fleet/server/mail"
@ -129,8 +129,8 @@ the way that the Fleet server works.
}
}
var ds kolide.Datastore
var carveStore kolide.CarveStore
var ds fleet.Datastore
var carveStore fleet.CarveStore
mailService := mail.NewService()
ds, err = mysql.New(config.Mysql, clock.C, mysql.Logger(logger))
@ -152,7 +152,7 @@ the way that the Fleet server works.
}
switch migrationStatus {
case kolide.SomeMigrationsCompleted:
case fleet.SomeMigrationsCompleted:
fmt.Printf("################################################################################\n"+
"# WARNING:\n"+
"# Your Fleet database is missing required migrations. This is likely to cause\n"+
@ -162,7 +162,7 @@ the way that the Fleet server works.
"################################################################################\n",
os.Args[0])
case kolide.NoMigrationsCompleted:
case fleet.NoMigrationsCompleted:
fmt.Printf("################################################################################\n"+
"# ERROR:\n"+
"# Your Fleet database is not initialized. Fleet cannot start up.\n"+
@ -186,7 +186,7 @@ the way that the Fleet server works.
}
if config.Auth.JwtKey == "" && config.Auth.JwtKeyPath == "" {
jwtKey, err := kolide.RandomText(24)
jwtKey, err := fleet.RandomText(24)
if err != nil {
initFatal(err, "generating sample jwt key")
}
@ -218,7 +218,7 @@ the way that the Fleet server works.
initFatal(err, "initializing service")
}
if license.Tier == kolide.TierBasic {
if license.Tier == fleet.TierBasic {
svc, err = eeservice.NewService(svc, ds, logger, config, mailService, clock.C, license)
if err != nil {
initFatal(err, "initial Fleet Basic service")
@ -345,7 +345,7 @@ the way that the Fleet server works.
if debug {
// Add debug endpoints with a random
// authorization token
debugToken, err := kolide.RandomText(24)
debugToken, err := fleet.RandomText(24)
if err != nil {
initFatal(err, "generating debug token")
}

View File

@ -7,7 +7,7 @@ import (
"regexp"
"strings"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
@ -24,18 +24,18 @@ type specMetadata struct {
}
type specGroup struct {
Queries []*kolide.QuerySpec
Packs []*kolide.PackSpec
Labels []*kolide.LabelSpec
AppConfig *kolide.AppConfigPayload
EnrollSecret *kolide.EnrollSecretSpec
Queries []*fleet.QuerySpec
Packs []*fleet.PackSpec
Labels []*fleet.LabelSpec
AppConfig *fleet.AppConfigPayload
EnrollSecret *fleet.EnrollSecretSpec
}
func specGroupFromBytes(b []byte) (*specGroup, error) {
specs := &specGroup{
Queries: []*kolide.QuerySpec{},
Packs: []*kolide.PackSpec{},
Labels: []*kolide.LabelSpec{},
Queries: []*fleet.QuerySpec{},
Packs: []*fleet.PackSpec{},
Labels: []*fleet.LabelSpec{},
}
for _, spec := range splitYaml(string(b)) {
@ -51,44 +51,44 @@ func specGroupFromBytes(b []byte) (*specGroup, error) {
kind := strings.ToLower(s.Kind)
switch kind {
case kolide.QueryKind:
var querySpec *kolide.QuerySpec
case fleet.QueryKind:
var querySpec *fleet.QuerySpec
if err := yaml.Unmarshal(s.Spec, &querySpec); err != nil {
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
}
specs.Queries = append(specs.Queries, querySpec)
case kolide.PackKind:
var packSpec *kolide.PackSpec
case fleet.PackKind:
var packSpec *fleet.PackSpec
if err := yaml.Unmarshal(s.Spec, &packSpec); err != nil {
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
}
specs.Packs = append(specs.Packs, packSpec)
case kolide.LabelKind:
var labelSpec *kolide.LabelSpec
case fleet.LabelKind:
var labelSpec *fleet.LabelSpec
if err := yaml.Unmarshal(s.Spec, &labelSpec); err != nil {
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
}
specs.Labels = append(specs.Labels, labelSpec)
case kolide.AppConfigKind:
case fleet.AppConfigKind:
if specs.AppConfig != nil {
return nil, errors.New("config defined twice in the same file")
}
var appConfigSpec *kolide.AppConfigPayload
var appConfigSpec *fleet.AppConfigPayload
if err := yaml.Unmarshal(s.Spec, &appConfigSpec); err != nil {
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
}
specs.AppConfig = appConfigSpec
case kolide.EnrollSecretKind:
case fleet.EnrollSecretKind:
if specs.AppConfig != nil {
return nil, errors.New("enroll_secret defined twice in the same file")
}
var enrollSecretSpec *kolide.EnrollSecretSpec
var enrollSecretSpec *fleet.EnrollSecretSpec
if err := yaml.Unmarshal(s.Spec, &enrollSecretSpec); err != nil {
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
}

View File

@ -9,25 +9,25 @@ import (
"strconv"
"strings"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
)
func specGroupFromPack(name string, inputPack kolide.PermissivePackContent) (*specGroup, error) {
func specGroupFromPack(name string, inputPack fleet.PermissivePackContent) (*specGroup, error) {
specs := &specGroup{
Queries: []*kolide.QuerySpec{},
Packs: []*kolide.PackSpec{},
Labels: []*kolide.LabelSpec{},
Queries: []*fleet.QuerySpec{},
Packs: []*fleet.PackSpec{},
Labels: []*fleet.LabelSpec{},
}
pack := &kolide.PackSpec{
pack := &fleet.PackSpec{
Name: name,
}
for name, query := range inputPack.Queries {
spec := &kolide.QuerySpec{
spec := &fleet.QuerySpec{
Name: name,
Description: query.Description,
Query: query.Query,
@ -48,7 +48,7 @@ func specGroupFromPack(name string, inputPack kolide.PermissivePackContent) (*sp
}
specs.Queries = append(specs.Queries, spec)
pack.Queries = append(pack.Queries, kolide.PackSpecQuery{
pack.Queries = append(pack.Queries, fleet.PackSpecQuery{
Name: name,
QueryName: name,
Interval: interval,
@ -104,7 +104,7 @@ func convertCommand() *cli.Command {
var specs *specGroup
var pack kolide.PermissivePackContent
var pack fleet.PermissivePackContent
if err := json.Unmarshal(b, &pack); err != nil {
return err
}
@ -126,8 +126,8 @@ func convertCommand() *cli.Command {
}
meta := specMetadata{
Kind: kolide.PackKind,
Version: kolide.ApiVersion,
Kind: fleet.PackKind,
Version: fleet.ApiVersion,
Spec: spec,
}
@ -147,8 +147,8 @@ func convertCommand() *cli.Command {
}
meta := specMetadata{
Kind: kolide.QueryKind,
Version: kolide.ApiVersion,
Kind: fleet.QueryKind,
Version: fleet.ApiVersion,
Spec: spec,
}

View File

@ -7,7 +7,7 @@ import (
"os"
"strconv"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/ghodss/yaml"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
@ -66,10 +66,10 @@ func printYaml(spec interface{}) error {
return nil
}
func printLabel(c *cli.Context, label *kolide.LabelSpec) error {
func printLabel(c *cli.Context, label *fleet.LabelSpec) error {
spec := specGeneric{
Kind: kolide.LabelKind,
Version: kolide.ApiVersion,
Kind: fleet.LabelKind,
Version: fleet.ApiVersion,
Spec: label,
}
@ -84,10 +84,10 @@ func printLabel(c *cli.Context, label *kolide.LabelSpec) error {
return err
}
func printQuery(c *cli.Context, query *kolide.QuerySpec) error {
func printQuery(c *cli.Context, query *fleet.QuerySpec) error {
spec := specGeneric{
Kind: kolide.QueryKind,
Version: kolide.ApiVersion,
Kind: fleet.QueryKind,
Version: fleet.ApiVersion,
Spec: query,
}
@ -102,10 +102,10 @@ func printQuery(c *cli.Context, query *kolide.QuerySpec) error {
return err
}
func printPack(c *cli.Context, pack *kolide.PackSpec) error {
func printPack(c *cli.Context, pack *fleet.PackSpec) error {
spec := specGeneric{
Kind: kolide.PackKind,
Version: kolide.ApiVersion,
Kind: fleet.PackKind,
Version: fleet.ApiVersion,
Spec: pack,
}
@ -120,10 +120,10 @@ func printPack(c *cli.Context, pack *kolide.PackSpec) error {
return err
}
func printSecret(c *cli.Context, secret *kolide.EnrollSecretSpec) error {
func printSecret(c *cli.Context, secret *fleet.EnrollSecretSpec) error {
spec := specGeneric{
Kind: kolide.EnrollSecretKind,
Version: kolide.ApiVersion,
Kind: fleet.EnrollSecretKind,
Version: fleet.ApiVersion,
Spec: secret,
}
@ -138,10 +138,10 @@ func printSecret(c *cli.Context, secret *kolide.EnrollSecretSpec) error {
return err
}
func printHost(c *cli.Context, host *kolide.Host) error {
func printHost(c *cli.Context, host *fleet.Host) error {
spec := specGeneric{
Kind: kolide.HostKind,
Version: kolide.ApiVersion,
Kind: fleet.HostKind,
Version: fleet.ApiVersion,
Spec: host,
}
@ -156,10 +156,10 @@ func printHost(c *cli.Context, host *kolide.Host) error {
return err
}
func printConfig(c *cli.Context, config *kolide.AppConfigPayload) error {
func printConfig(c *cli.Context, config *fleet.AppConfigPayload) error {
spec := specGeneric{
Kind: kolide.AppConfigKind,
Version: kolide.ApiVersion,
Kind: fleet.AppConfigKind,
Version: fleet.ApiVersion,
Spec: config,
}
var err error
@ -203,7 +203,7 @@ func getQueriesCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
@ -212,7 +212,7 @@ func getQueriesCommand() *cli.Command {
// if name wasn't provided, list all queries
if name == "" {
queries, err := fleet.GetQueries()
queries, err := client.GetQueries()
if err != nil {
return errors.Wrap(err, "could not list queries")
}
@ -248,7 +248,7 @@ func getQueriesCommand() *cli.Command {
return nil
}
query, err := fleet.GetQuery(name)
query, err := client.GetQuery(name)
if err != nil {
return err
}
@ -280,7 +280,7 @@ func getPacksCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
@ -289,7 +289,7 @@ func getPacksCommand() *cli.Command {
shouldPrintQueries := c.Bool(withQueriesFlagName)
queriesToPrint := make(map[string]bool)
addQueries := func(pack *kolide.PackSpec) {
addQueries := func(pack *fleet.PackSpec) {
if shouldPrintQueries {
for _, q := range pack.Queries {
queriesToPrint[q.QueryName] = true
@ -302,7 +302,7 @@ func getPacksCommand() *cli.Command {
return nil
}
queries, err := fleet.GetQueries()
queries, err := client.GetQueries()
if err != nil {
return errors.Wrap(err, "could not list queries")
}
@ -324,7 +324,7 @@ func getPacksCommand() *cli.Command {
// if name wasn't provided, list all packs
if name == "" {
packs, err := fleet.GetPacks()
packs, err := client.GetPacks()
if err != nil {
return errors.Wrap(err, "could not list packs")
}
@ -366,7 +366,7 @@ func getPacksCommand() *cli.Command {
}
// Name was specified
pack, err := fleet.GetPack(name)
pack, err := client.GetPack(name)
if err != nil {
return err
}
@ -396,7 +396,7 @@ func getLabelsCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
@ -405,7 +405,7 @@ func getLabelsCommand() *cli.Command {
// if name wasn't provided, list all labels
if name == "" {
labels, err := fleet.GetLabels()
labels, err := client.GetLabels()
if err != nil {
return errors.Wrap(err, "could not list labels")
}
@ -443,7 +443,7 @@ func getLabelsCommand() *cli.Command {
}
// Label name was specified
label, err := fleet.GetLabel(name)
label, err := client.GetLabel(name)
if err != nil {
return err
}
@ -468,12 +468,12 @@ func getEnrollSecretCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
secrets, err := fleet.GetEnrollSecretSpec()
secrets, err := client.GetEnrollSecretSpec()
if err != nil {
return err
}
@ -500,12 +500,12 @@ func getAppConfigCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
config, err := fleet.GetAppConfig()
config, err := client.GetAppConfig()
if err != nil {
return err
}
@ -533,7 +533,7 @@ func getHostsCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
@ -541,7 +541,7 @@ func getHostsCommand() *cli.Command {
identifier := c.Args().First()
if identifier == "" {
hosts, err := fleet.GetHosts()
hosts, err := client.GetHosts()
if err != nil {
return errors.Wrap(err, "could not list hosts")
}
@ -579,7 +579,7 @@ func getHostsCommand() *cli.Command {
table.AppendBulk(data)
table.Render()
} else {
host, err := fleet.HostByIdentifier(identifier)
host, err := client.HostByIdentifier(identifier)
if err != nil {
return errors.Wrap(err, "could not get host")
}
@ -609,14 +609,14 @@ func getCarvesCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
expired := c.Bool(expiredFlagName)
carves, err := fleet.ListCarves(kolide.CarveListOptions{Expired: expired})
carves, err := client.ListCarves(fleet.CarveListOptions{Expired: expired})
if err != nil {
return err
}
@ -670,7 +670,7 @@ func getCarveCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
@ -704,7 +704,7 @@ func getCarveCommand() *cli.Command {
out = f
}
reader, err := fleet.DownloadCarve(id)
reader, err := client.DownloadCarve(id)
if err != nil {
return err
}
@ -716,7 +716,7 @@ func getCarveCommand() *cli.Command {
return nil
}
carve, err := fleet.GetCarve(id)
carve, err := client.GetCarve(id)
if err != nil {
return err
}

View File

@ -8,7 +8,7 @@ import (
gqconfig "github.com/AbGuthrie/goquery/v2/config"
gqhosts "github.com/AbGuthrie/goquery/v2/hosts"
gqmodels "github.com/AbGuthrie/goquery/v2/models"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/service"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
@ -44,7 +44,7 @@ func (c *goqueryClient) CheckHost(query string) (gqhosts.Host, error) {
return gqhosts.Host{}, err
}
var host *kolide.Host
var host *fleet.Host
for _, h := range res.Hosts {
// We allow hosts to be looked up by hostname in addition to UUID
if query == h.UUID || query == h.HostName || query == h.ComputerName {

View File

@ -5,13 +5,13 @@ import (
"os"
"sort"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/gosuri/uilive"
"github.com/olekukonko/tablewriter"
)
type outputWriter interface {
WriteResult(res kolide.DistributedQueryResult) error
WriteResult(res fleet.DistributedQueryResult) error
}
type resultOutput struct {
@ -26,7 +26,7 @@ func newJsonWriter() *jsonWriter {
return &jsonWriter{}
}
func (w *jsonWriter) WriteResult(res kolide.DistributedQueryResult) error {
func (w *jsonWriter) WriteResult(res fleet.DistributedQueryResult) error {
out := resultOutput{
HostIdentifier: res.Host.HostName,
Rows: res.Rows,
@ -36,7 +36,7 @@ func (w *jsonWriter) WriteResult(res kolide.DistributedQueryResult) error {
}
type prettyWriter struct {
results []kolide.DistributedQueryResult
results []fleet.DistributedQueryResult
columns map[string]bool
writer *uilive.Writer
}
@ -48,7 +48,7 @@ func newPrettyWriter() *prettyWriter {
}
}
func (w *prettyWriter) WriteResult(res kolide.DistributedQueryResult) error {
func (w *prettyWriter) WriteResult(res fleet.DistributedQueryResult) error {
w.results = append(w.results, res)
// Recompute columns

View File

@ -5,7 +5,7 @@ import (
"fmt"
"os"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/ssh/terminal"
@ -65,7 +65,7 @@ func createUserCommand() *cli.Command {
debugFlag(),
},
Action: func(c *cli.Context) error {
fleet, err := clientFromCLI(c)
client, err := clientFromCLI(c)
if err != nil {
return err
}
@ -106,7 +106,7 @@ func createUserCommand() *cli.Command {
// Only set the password reset flag if SSO is not enabled. Otherwise
// the user will be stuck in a bad state and not be able to log in.
force_reset := !sso
err = fleet.CreateUser(kolide.UserPayload{
err = client.CreateUser(fleet.UserPayload{
Username: &username,
Password: &password,
Email: &email,

View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
@ -40,10 +40,10 @@ func loadPublicKey() (*ecdsa.PublicKey, error) {
}
// LoadLicense loads and validates the license key.
func LoadLicense(licenseKey string) (*kolide.LicenseInfo, error) {
func LoadLicense(licenseKey string) (*fleet.LicenseInfo, error) {
// No license key
if licenseKey == "" {
return &kolide.LicenseInfo{Tier: kolide.TierCore}, nil
return &fleet.LicenseInfo{Tier: fleet.TierCore}, nil
}
parsedToken, err := jwt.ParseWithClaims(
@ -74,7 +74,7 @@ type licenseClaims struct {
Note string `json:"note"`
}
func validate(token *jwt.Token) (*kolide.LicenseInfo, error) {
func validate(token *jwt.Token) (*fleet.LicenseInfo, error) {
// token.IssuedAt, token.ExpiresAt, token.NotBefore already validated by JWT
// library.
if !token.Valid {
@ -108,7 +108,7 @@ func validate(token *jwt.Token) (*kolide.LicenseInfo, error) {
return nil, errors.Errorf("unexpected issuer %s", claims.Issuer)
}
return &kolide.LicenseInfo{
return &fleet.LicenseInfo{
Tier: claims.Tier,
Organization: claims.Subject,
DeviceCount: claims.Devices,

View File

@ -4,7 +4,7 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@ -24,8 +24,8 @@ func TestLoadLicense(t *testing.T) {
license, err := LoadLicense(key)
require.NoError(t, err)
assert.Equal(t,
&kolide.LicenseInfo{
Tier: kolide.TierBasic,
&fleet.LicenseInfo{
Tier: fleet.TierBasic,
Organization: "development",
DeviceCount: 100,
Expiration: time.Unix(1640995200, 0),
@ -33,7 +33,7 @@ func TestLoadLicense(t *testing.T) {
},
license,
)
assert.Equal(t, kolide.TierBasic, license.Tier)
assert.Equal(t, fleet.TierBasic, license.Tier)
}
func TestLoadLicenseExpired(t *testing.T) {

View File

@ -4,30 +4,30 @@ import (
"github.com/WatchBeam/clock"
"github.com/fleetdm/fleet/server/authz"
"github.com/fleetdm/fleet/server/config"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
kitlog "github.com/go-kit/kit/log"
"github.com/pkg/errors"
)
type Service struct {
kolide.Service
fleet.Service
ds kolide.Datastore
ds fleet.Datastore
logger kitlog.Logger
config config.KolideConfig
config config.FleetConfig
clock clock.Clock
authz *authz.Authorizer
license *kolide.LicenseInfo
license *fleet.LicenseInfo
}
func NewService(
svc kolide.Service,
ds kolide.Datastore,
svc fleet.Service,
ds fleet.Datastore,
logger kitlog.Logger,
config config.KolideConfig,
mailService kolide.MailService,
config config.FleetConfig,
mailService fleet.MailService,
c clock.Clock,
license *kolide.LicenseInfo,
license *fleet.LicenseInfo,
) (*Service, error) {
authorizer, err := authz.NewAuthorizer()

View File

@ -6,22 +6,22 @@ import (
"fmt"
"github.com/fleetdm/fleet/server/contexts/viewer"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
func (svc *Service) NewTeam(ctx context.Context, p kolide.TeamPayload) (*kolide.Team, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{}, kolide.ActionWrite); err != nil {
func (svc *Service) NewTeam(ctx context.Context, p fleet.TeamPayload) (*fleet.Team, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{}, fleet.ActionWrite); err != nil {
return nil, err
}
team := &kolide.Team{}
team := &fleet.Team{}
if p.Name == nil {
return nil, kolide.NewInvalidArgumentError("name", "missing required argument")
return nil, fleet.NewInvalidArgumentError("name", "missing required argument")
}
if *p.Name == "" {
return nil, kolide.NewInvalidArgumentError("name", "may not be empty")
return nil, fleet.NewInvalidArgumentError("name", "may not be empty")
}
team.Name = *p.Name
@ -33,11 +33,11 @@ func (svc *Service) NewTeam(ctx context.Context, p kolide.TeamPayload) (*kolide.
team.Secrets = p.Secrets
} else {
// Set up a default enroll secret
secret, err := kolide.RandomText(kolide.EnrollSecretDefaultLength)
secret, err := fleet.RandomText(fleet.EnrollSecretDefaultLength)
if err != nil {
return nil, errors.Wrap(err, "generate enroll secret string")
}
team.Secrets = []*kolide.EnrollSecret{{Secret: secret}}
team.Secrets = []*fleet.EnrollSecret{{Secret: secret}}
}
team, err := svc.ds.NewTeam(team)
if err != nil {
@ -46,8 +46,8 @@ func (svc *Service) NewTeam(ctx context.Context, p kolide.TeamPayload) (*kolide.
return team, nil
}
func (svc *Service) ModifyTeam(ctx context.Context, teamID uint, payload kolide.TeamPayload) (*kolide.Team, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{ID: teamID}, kolide.ActionWrite); err != nil {
func (svc *Service) ModifyTeam(ctx context.Context, teamID uint, payload fleet.TeamPayload) (*fleet.Team, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{ID: teamID}, fleet.ActionWrite); err != nil {
return nil, err
}
@ -57,7 +57,7 @@ func (svc *Service) ModifyTeam(ctx context.Context, teamID uint, payload kolide.
}
if payload.Name != nil {
if *payload.Name == "" {
return nil, kolide.NewInvalidArgumentError("name", "may not be empty")
return nil, fleet.NewInvalidArgumentError("name", "may not be empty")
}
team.Name = *payload.Name
}
@ -71,8 +71,8 @@ func (svc *Service) ModifyTeam(ctx context.Context, teamID uint, payload kolide.
return svc.ds.SaveTeam(team)
}
func (svc *Service) ModifyTeamAgentOptions(ctx context.Context, teamID uint, options json.RawMessage) (*kolide.Team, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{ID: teamID}, kolide.ActionWrite); err != nil {
func (svc *Service) ModifyTeamAgentOptions(ctx context.Context, teamID uint, options json.RawMessage) (*fleet.Team, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{ID: teamID}, fleet.ActionWrite); err != nil {
return nil, err
}
@ -90,15 +90,15 @@ func (svc *Service) ModifyTeamAgentOptions(ctx context.Context, teamID uint, opt
return svc.ds.SaveTeam(team)
}
func (svc *Service) AddTeamUsers(ctx context.Context, teamID uint, users []kolide.TeamUser) (*kolide.Team, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{ID: teamID}, kolide.ActionWrite); err != nil {
func (svc *Service) AddTeamUsers(ctx context.Context, teamID uint, users []fleet.TeamUser) (*fleet.Team, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{ID: teamID}, fleet.ActionWrite); err != nil {
return nil, err
}
idMap := make(map[uint]kolide.TeamUser)
idMap := make(map[uint]fleet.TeamUser)
for _, user := range users {
if !kolide.ValidTeamRole(user.Role) {
return nil, kolide.NewInvalidArgumentError("users", fmt.Sprintf("%s is not a valid role for a team user", user.Role))
if !fleet.ValidTeamRole(user.Role) {
return nil, fleet.NewInvalidArgumentError("users", fmt.Sprintf("%s is not a valid role for a team user", user.Role))
}
idMap[user.ID] = user
}
@ -124,8 +124,8 @@ func (svc *Service) AddTeamUsers(ctx context.Context, teamID uint, users []kolid
return svc.ds.SaveTeam(team)
}
func (svc *Service) DeleteTeamUsers(ctx context.Context, teamID uint, users []kolide.TeamUser) (*kolide.Team, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{ID: teamID}, kolide.ActionWrite); err != nil {
func (svc *Service) DeleteTeamUsers(ctx context.Context, teamID uint, users []fleet.TeamUser) (*fleet.Team, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{ID: teamID}, fleet.ActionWrite); err != nil {
return nil, err
}
@ -139,7 +139,7 @@ func (svc *Service) DeleteTeamUsers(ctx context.Context, teamID uint, users []ko
return nil, err
}
newUsers := []kolide.TeamUser{}
newUsers := []fleet.TeamUser{}
// Delete existing
for _, existingUser := range team.Users {
if _, ok := idMap[existingUser.ID]; !ok {
@ -152,8 +152,8 @@ func (svc *Service) DeleteTeamUsers(ctx context.Context, teamID uint, users []ko
return svc.ds.SaveTeam(team)
}
func (svc *Service) ListTeamUsers(ctx context.Context, teamID uint, opt kolide.ListOptions) ([]*kolide.User, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{ID: teamID}, kolide.ActionRead); err != nil {
func (svc *Service) ListTeamUsers(ctx context.Context, teamID uint, opt fleet.ListOptions) ([]*fleet.User, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{ID: teamID}, fleet.ActionRead); err != nil {
return nil, err
}
@ -162,33 +162,33 @@ func (svc *Service) ListTeamUsers(ctx context.Context, teamID uint, opt kolide.L
return nil, err
}
return svc.ds.ListUsers(kolide.UserListOptions{ListOptions: opt, TeamID: team.ID})
return svc.ds.ListUsers(fleet.UserListOptions{ListOptions: opt, TeamID: team.ID})
}
func (svc *Service) ListTeams(ctx context.Context, opt kolide.ListOptions) ([]*kolide.Team, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{}, kolide.ActionRead); err != nil {
func (svc *Service) ListTeams(ctx context.Context, opt fleet.ListOptions) ([]*fleet.Team, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{}, fleet.ActionRead); err != nil {
return nil, err
}
vc, ok := viewer.FromContext(ctx)
if !ok {
return nil, kolide.ErrNoContext
return nil, fleet.ErrNoContext
}
filter := kolide.TeamFilter{User: vc.User, IncludeObserver: true}
filter := fleet.TeamFilter{User: vc.User, IncludeObserver: true}
return svc.ds.ListTeams(filter, opt)
}
func (svc *Service) DeleteTeam(ctx context.Context, teamID uint) error {
if err := svc.authz.Authorize(ctx, &kolide.Team{ID: teamID}, kolide.ActionWrite); err != nil {
if err := svc.authz.Authorize(ctx, &fleet.Team{ID: teamID}, fleet.ActionWrite); err != nil {
return err
}
return svc.ds.DeleteTeam(teamID)
}
func (svc *Service) TeamEnrollSecrets(ctx context.Context, teamID uint) ([]*kolide.EnrollSecret, error) {
if err := svc.authz.Authorize(ctx, &kolide.Team{ID: teamID}, kolide.ActionRead); err != nil {
func (svc *Service) TeamEnrollSecrets(ctx context.Context, teamID uint) ([]*fleet.EnrollSecret, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{ID: teamID}, fleet.ActionRead); err != nil {
return nil, err
}

View File

@ -16,7 +16,7 @@ import (
authz_ctx "github.com/fleetdm/fleet/server/contexts/authz"
"github.com/fleetdm/fleet/server/contexts/viewer"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/open-policy-agent/opa/rego"
"github.com/pkg/errors"
)
@ -164,7 +164,7 @@ func jsonToInterface(in interface{}) (interface{}, error) {
// userFromContext retrieves a user from the viewer context, returning nil if
// there is no user.
func userFromContext(ctx context.Context) *kolide.User {
func userFromContext(ctx context.Context) *fleet.User {
vc, ok := viewer.FromContext(ctx)
if !ok {
return nil

View File

@ -3,13 +3,13 @@ package authz
import (
"net/http"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
// Forbidden is the error type for authorization errors
type Forbidden struct {
internal string
subject *kolide.User
subject *fleet.User
object interface{}
action interface{}
}
@ -17,7 +17,7 @@ type Forbidden struct {
// ForbiddenWithInternal creates a new error that will return a simple
// "forbidden" to the client, logging internally the more detailed message
// provided.
func ForbiddenWithInternal(internal string, subject *kolide.User, object, action interface{}) *Forbidden {
func ForbiddenWithInternal(internal string, subject *fleet.User, object, action interface{}) *Forbidden {
return &Forbidden{
internal: internal,
subject: subject,

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
@ -12,11 +12,11 @@ import (
)
const (
read = kolide.ActionRead
list = kolide.ActionList
write = kolide.ActionWrite
writeRole = kolide.ActionWriteRole
run = kolide.ActionRun
read = fleet.ActionRead
list = fleet.ActionList
write = fleet.ActionWrite
writeRole = fleet.ActionWriteRole
run = fleet.ActionRun
)
var auth *Authorizer
@ -30,7 +30,7 @@ func init() {
}
type authTestCase struct {
user *kolide.User
user *fleet.User
object interface{}
action interface{}
allow bool
@ -39,7 +39,7 @@ type authTestCase struct {
func TestAuthorizeAppConfig(t *testing.T) {
t.Parallel()
config := &kolide.AppConfig{}
config := &fleet.AppConfig{}
runTestCases(t, []authTestCase{
{user: nil, object: config, action: read, allow: false},
{user: nil, object: config, action: write, allow: false},
@ -61,7 +61,7 @@ func TestAuthorizeAppConfig(t *testing.T) {
func TestAuthorizeSession(t *testing.T) {
t.Parallel()
session := &kolide.Session{UserID: 42}
session := &fleet.Session{UserID: 42}
runTestCases(t, []authTestCase{
{user: nil, object: session, action: read, allow: false},
{user: nil, object: session, action: write, allow: false},
@ -73,25 +73,25 @@ func TestAuthorizeSession(t *testing.T) {
// Regular users can read self
{user: test.UserMaintainer, object: session, action: read, allow: false},
{user: test.UserMaintainer, object: session, action: write, allow: false},
{user: test.UserMaintainer, object: &kolide.Session{UserID: test.UserMaintainer.ID}, action: read, allow: true},
{user: test.UserMaintainer, object: &kolide.Session{UserID: test.UserMaintainer.ID}, action: write, allow: true},
{user: test.UserMaintainer, object: &fleet.Session{UserID: test.UserMaintainer.ID}, action: read, allow: true},
{user: test.UserMaintainer, object: &fleet.Session{UserID: test.UserMaintainer.ID}, action: write, allow: true},
{user: test.UserNoRoles, object: session, action: read, allow: false},
{user: test.UserNoRoles, object: session, action: write, allow: false},
{user: test.UserNoRoles, object: &kolide.Session{UserID: test.UserNoRoles.ID}, action: read, allow: true},
{user: test.UserNoRoles, object: &kolide.Session{UserID: test.UserNoRoles.ID}, action: write, allow: true},
{user: test.UserNoRoles, object: &fleet.Session{UserID: test.UserNoRoles.ID}, action: read, allow: true},
{user: test.UserNoRoles, object: &fleet.Session{UserID: test.UserNoRoles.ID}, action: write, allow: true},
{user: test.UserObserver, object: session, action: read, allow: false},
{user: test.UserObserver, object: session, action: write, allow: false},
{user: test.UserObserver, object: &kolide.Session{UserID: test.UserObserver.ID}, action: read, allow: true},
{user: test.UserObserver, object: &kolide.Session{UserID: test.UserObserver.ID}, action: write, allow: true},
{user: test.UserObserver, object: &fleet.Session{UserID: test.UserObserver.ID}, action: read, allow: true},
{user: test.UserObserver, object: &fleet.Session{UserID: test.UserObserver.ID}, action: write, allow: true},
})
}
func TestAuthorizeUser(t *testing.T) {
t.Parallel()
user := &kolide.User{ID: 42}
user := &fleet.User{ID: 42}
runTestCases(t, []authTestCase{
{user: nil, object: user, action: read, allow: false},
{user: nil, object: user, action: write, allow: false},
@ -129,7 +129,7 @@ func TestAuthorizeUser(t *testing.T) {
func TestAuthorizeInvite(t *testing.T) {
t.Parallel()
invite := &kolide.Invite{}
invite := &fleet.Invite{}
runTestCases(t, []authTestCase{
{user: nil, object: invite, action: read, allow: false},
{user: nil, object: invite, action: write, allow: false},
@ -151,18 +151,18 @@ func TestAuthorizeInvite(t *testing.T) {
func TestAuthorizeEnrollSecret(t *testing.T) {
t.Parallel()
teamMaintainer := &kolide.User{
Teams: []kolide.UserTeam{
{Team: kolide.Team{ID: 1}, Role: kolide.RoleMaintainer},
teamMaintainer := &fleet.User{
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: 1}, Role: fleet.RoleMaintainer},
},
}
teamObserver := &kolide.User{
Teams: []kolide.UserTeam{
{Team: kolide.Team{ID: 1}, Role: kolide.RoleObserver},
teamObserver := &fleet.User{
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: 1}, Role: fleet.RoleObserver},
},
}
globalSecret := &kolide.EnrollSecret{}
teamSecret := &kolide.EnrollSecret{TeamID: ptr.Uint(1)}
globalSecret := &fleet.EnrollSecret{}
teamSecret := &fleet.EnrollSecret{TeamID: ptr.Uint(1)}
runTestCases(t, []authTestCase{
// No access
{user: nil, object: globalSecret, action: read, allow: false},
@ -205,7 +205,7 @@ func TestAuthorizeEnrollSecret(t *testing.T) {
func TestAuthorizeTeam(t *testing.T) {
t.Parallel()
team := &kolide.Team{}
team := &fleet.Team{}
runTestCases(t, []authTestCase{
{user: nil, object: team, action: read, allow: false},
{user: nil, object: team, action: write, allow: false},
@ -227,7 +227,7 @@ func TestAuthorizeTeam(t *testing.T) {
func TestAuthorizeLabel(t *testing.T) {
t.Parallel()
label := &kolide.Label{}
label := &fleet.Label{}
runTestCases(t, []authTestCase{
{user: nil, object: label, action: read, allow: false},
{user: nil, object: label, action: write, allow: false},
@ -249,19 +249,19 @@ func TestAuthorizeLabel(t *testing.T) {
func TestAuthorizeHost(t *testing.T) {
t.Parallel()
teamMaintainer := &kolide.User{
Teams: []kolide.UserTeam{
{Team: kolide.Team{ID: 1}, Role: kolide.RoleMaintainer},
teamMaintainer := &fleet.User{
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: 1}, Role: fleet.RoleMaintainer},
},
}
teamObserver := &kolide.User{
Teams: []kolide.UserTeam{
{Team: kolide.Team{ID: 1}, Role: kolide.RoleObserver},
teamObserver := &fleet.User{
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: 1}, Role: fleet.RoleObserver},
},
}
host := &kolide.Host{}
hostTeam1 := &kolide.Host{TeamID: ptr.Uint(1)}
hostTeam2 := &kolide.Host{TeamID: ptr.Uint(2)}
host := &fleet.Host{}
hostTeam1 := &fleet.Host{TeamID: ptr.Uint(1)}
hostTeam2 := &fleet.Host{TeamID: ptr.Uint(2)}
runTestCases(t, []authTestCase{
// No access
{user: nil, object: host, action: read, allow: false},
@ -327,18 +327,18 @@ func TestAuthorizeHost(t *testing.T) {
func TestAuthorizeQuery(t *testing.T) {
t.Parallel()
teamMaintainer := &kolide.User{
Teams: []kolide.UserTeam{
{Team: kolide.Team{ID: 1}, Role: kolide.RoleMaintainer},
teamMaintainer := &fleet.User{
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: 1}, Role: fleet.RoleMaintainer},
},
}
teamObserver := &kolide.User{
Teams: []kolide.UserTeam{
{Team: kolide.Team{ID: 1}, Role: kolide.RoleObserver},
teamObserver := &fleet.User{
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: 1}, Role: fleet.RoleObserver},
},
}
query := &kolide.Query{}
observerQuery := &kolide.Query{ObserverCanRun: true}
query := &fleet.Query{}
observerQuery := &fleet.Query{ObserverCanRun: true}
runTestCases(t, []authTestCase{
// No access
{user: nil, object: query, action: read, allow: false},
@ -403,7 +403,7 @@ func TestAuthorizeQuery(t *testing.T) {
func TestAuthorizeTargets(t *testing.T) {
t.Parallel()
target := &kolide.Target{}
target := &fleet.Target{}
runTestCases(t, []authTestCase{
{user: nil, object: target, action: read, allow: false},
@ -419,7 +419,7 @@ func TestAuthorizeTargets(t *testing.T) {
func TestAuthorizePacks(t *testing.T) {
t.Parallel()
pack := &kolide.Pack{}
pack := &fleet.Pack{}
runTestCases(t, []authTestCase{
{user: nil, object: pack, action: read, allow: false},
{user: nil, object: pack, action: write, allow: false},
@ -441,7 +441,7 @@ func TestAuthorizePacks(t *testing.T) {
func TestAuthorizeCarves(t *testing.T) {
t.Parallel()
carve := &kolide.CarveMetadata{}
carve := &fleet.CarveMetadata{}
runTestCases(t, []authTestCase{
{user: nil, object: carve, action: read, allow: false},
{user: nil, object: carve, action: write, allow: false},
@ -458,13 +458,13 @@ func TestAuthorizeCarves(t *testing.T) {
})
}
func assertAuthorized(t *testing.T, user *kolide.User, object, action interface{}) {
func assertAuthorized(t *testing.T, user *fleet.User, object, action interface{}) {
t.Helper()
assert.NoError(t, auth.Authorize(test.UserContext(user), object, action), "should be authorized\n%v\n%v\n%v", user, object, action)
}
func assertUnauthorized(t *testing.T, user *kolide.User, object, action interface{}) {
func assertUnauthorized(t *testing.T, user *fleet.User, object, action interface{}) {
t.Helper()
assert.Error(t, auth.Authorize(test.UserContext(user), object, action), "should be unauthorized\n%v\n%v\n%v", user, object, action)
@ -490,18 +490,18 @@ func runTestCases(t *testing.T, testCases []authTestCase) {
func TestJSONToInterfaceUser(t *testing.T) {
t.Parallel()
subject, err := jsonToInterface(&kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)})
subject, err := jsonToInterface(&fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)})
require.NoError(t, err)
{
subject := subject.(map[string]interface{})
assert.Equal(t, kolide.RoleAdmin, subject["global_role"])
assert.Equal(t, fleet.RoleAdmin, subject["global_role"])
assert.Nil(t, subject["teams"])
}
subject, err = jsonToInterface(&kolide.User{
Teams: []kolide.UserTeam{
{Team: kolide.Team{ID: 3}, Role: kolide.RoleObserver},
{Team: kolide.Team{ID: 42}, Role: kolide.RoleMaintainer},
subject, err = jsonToInterface(&fleet.User{
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: 3}, Role: fleet.RoleObserver},
{Team: fleet.Team{ID: 42}, Role: fleet.RoleMaintainer},
},
})
require.NoError(t, err)
@ -509,9 +509,9 @@ func TestJSONToInterfaceUser(t *testing.T) {
subject := subject.(map[string]interface{})
assert.Equal(t, nil, subject["global_role"])
assert.Len(t, subject["teams"], 2)
assert.Equal(t, kolide.RoleObserver, subject["teams"].([]interface{})[0].(map[string]interface{})["role"])
assert.Equal(t, fleet.RoleObserver, subject["teams"].([]interface{})[0].(map[string]interface{})["role"])
assert.Equal(t, json.Number("3"), subject["teams"].([]interface{})[0].(map[string]interface{})["id"])
assert.Equal(t, kolide.RoleMaintainer, subject["teams"].([]interface{})[1].(map[string]interface{})["role"])
assert.Equal(t, fleet.RoleMaintainer, subject["teams"].([]interface{})[1].(map[string]interface{})["role"])
assert.Equal(t, json.Number("42"), subject["teams"].([]interface{})[1].(map[string]interface{})["id"])
}
}

View File

@ -160,11 +160,11 @@ type LicenseConfig struct {
Key string `yaml:"key"`
}
// KolideConfig stores the application configuration. Each subcategory is
// FleetConfig stores the application configuration. Each subcategory is
// broken up into it's own struct, defined above. When editing any of these
// structs, Manager.addConfigs and Manager.LoadConfig should be
// updated to set and retrieve the configurations as appropriate.
type KolideConfig struct {
type FleetConfig struct {
Mysql MysqlConfig
Redis RedisConfig
Server ServerConfig
@ -183,20 +183,20 @@ type KolideConfig struct {
}
// addConfigs adds the configuration keys and default values that will be
// filled into the KolideConfig struct
// filled into the FleetConfig struct
func (man Manager) addConfigs() {
// MySQL
man.addConfigString("mysql.protocol", "tcp",
"MySQL server communication protocol (tcp,unix,...)")
man.addConfigString("mysql.address", "localhost:3306",
"MySQL server address (host:port)")
man.addConfigString("mysql.username", "kolide",
man.addConfigString("mysql.username", "fleet",
"MySQL server username")
man.addConfigString("mysql.password", "",
"MySQL server password (prefer env variable for security)")
man.addConfigString("mysql.password_path", "",
"Path to file containg MySQL server password")
man.addConfigString("mysql.database", "kolide",
man.addConfigString("mysql.database", "fleet",
"MySQL database name")
man.addConfigString("mysql.tls_cert", "",
"MySQL TLS client certificate path")
@ -225,9 +225,9 @@ func (man Manager) addConfigs() {
// Server
man.addConfigString("server.address", "0.0.0.0:8080",
"Fleet server address (host:port)")
man.addConfigString("server.cert", "./tools/osquery/kolide.crt",
man.addConfigString("server.cert", "./tools/osquery/fleet.crt",
"Fleet TLS certificate path")
man.addConfigString("server.key", "./tools/osquery/kolide.key",
man.addConfigString("server.key", "./tools/osquery/fleet.key",
"Fleet TLS key path")
man.addConfigBool("server.tls", true,
"Enable TLS (required for osqueryd communication)")
@ -354,11 +354,11 @@ func (man Manager) addConfigs() {
}
// LoadConfig will load the config variables into a fully initialized
// KolideConfig struct
func (man Manager) LoadConfig() KolideConfig {
// FleetConfig struct
func (man Manager) LoadConfig() FleetConfig {
man.loadConfigFile()
return KolideConfig{
return FleetConfig{
Mysql: MysqlConfig{
Protocol: man.getConfigString("mysql.protocol"),
Address: man.getConfigString("mysql.address"),
@ -490,7 +490,7 @@ func flagNameFromConfigKey(key string) string {
// Manager manages the addition and retrieval of config values for Fleet
// configs. It's only public API method is LoadConfig, which will return the
// populated KolideConfig struct.
// populated FleetConfig struct.
type Manager struct {
viper *viper.Viper
command *cobra.Command
@ -666,8 +666,8 @@ func (man Manager) loadConfigFile() {
// TestConfig returns a barebones configuration suitable for use in tests.
// Individual tests may want to override some of the values provided.
func TestConfig() KolideConfig {
return KolideConfig{
func TestConfig() FleetConfig {
return FleetConfig{
App: AppConfig{
TokenKeySize: 24,
InviteTokenValidityPeriod: 5 * 24 * time.Hour,

View File

@ -28,7 +28,7 @@ func TestConfigRoundtrip(t *testing.T) {
// values to be verified on the roundtrip. Note that bools are always
// set to true, which could false positive if the default value is
// true.
original := &KolideConfig{}
original := &FleetConfig{}
v := reflect.ValueOf(original)
for conf_index := 0; conf_index < v.Elem().NumField(); conf_index++ {
conf_v := v.Elem().Field(conf_index)

View File

@ -5,7 +5,7 @@ package host
import (
"context"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
type key int
@ -13,12 +13,12 @@ type key int
const hostKey key = 0
// NewContext returns a new context carrying the current osquery host.
func NewContext(ctx context.Context, host kolide.Host) context.Context {
func NewContext(ctx context.Context, host fleet.Host) context.Context {
return context.WithValue(ctx, hostKey, host)
}
// FromContext extracts the osquery host from context if present.
func FromContext(ctx context.Context) (kolide.Host, bool) {
host, ok := ctx.Value(hostKey).(kolide.Host)
func FromContext(ctx context.Context) (fleet.Host, bool) {
host, ok := ctx.Value(hostKey).(fleet.Host)
return host, ok
}

View File

@ -5,7 +5,7 @@ package viewer
import (
"context"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
type key int
@ -26,8 +26,8 @@ func FromContext(ctx context.Context) (Viewer, bool) {
// Viewer holds information about the current
// user and the user's session
type Viewer struct {
User *kolide.User
Session *kolide.Session
User *fleet.User
Session *fleet.Session
}
// UserID is a helper that enables quick access to the user ID of the current

View File

@ -4,7 +4,7 @@ import (
"context"
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
)
@ -12,7 +12,7 @@ var (
// Weird states
nilViewer = Viewer{}
noSessionViewer = Viewer{
User: &kolide.User{
User: &fleet.User{
ID: 41,
Name: "No Session",
Username: "nosession",
@ -21,25 +21,25 @@ var (
// Regular users
userViewer = Viewer{
User: &kolide.User{
User: &fleet.User{
ID: 45,
Name: "Regular User",
Username: "user",
},
Session: &kolide.Session{
Session: &fleet.Session{
ID: 4,
UserID: 45,
},
}
needsPasswordResetUserViewer = Viewer{
User: &kolide.User{
User: &fleet.User{
ID: 47,
Name: "Regular User Needs Password Reset",
Username: "reset_user",
AdminForcedPasswordReset: true,
},
Session: &kolide.Session{
Session: &fleet.Session{
ID: 6,
UserID: 47,
},
@ -47,24 +47,24 @@ var (
// Admin users
adminViewer = Viewer{
User: &kolide.User{
User: &fleet.User{
ID: 42,
Name: "The Admin",
Username: "admin",
},
Session: &kolide.Session{
Session: &fleet.Session{
ID: 1,
UserID: 42,
},
}
needsPasswordResetAdminViewer = Viewer{
User: &kolide.User{
User: &fleet.User{
ID: 44,
Name: "The Admin Requires Password Reset",
Username: "reset_admin",
AdminForcedPasswordReset: true,
},
Session: &kolide.Session{
Session: &fleet.Session{
ID: 3,
UserID: 44,
},

View File

@ -4,12 +4,12 @@ package datastore
import (
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
// TestFunctions are the test functions that a Datastore implementation should
// run to verify proper implementation.
var TestFunctions = [...]func(*testing.T, kolide.Datastore){
var TestFunctions = [...]func(*testing.T, fleet.Datastore){
testOrgInfo,
testAdditionalQueries,
testEnrollSecrets,

View File

@ -5,13 +5,13 @@ import (
"sort"
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testOrgInfo(t *testing.T, ds kolide.Datastore) {
info := &kolide.AppConfig{
func testOrgInfo(t *testing.T, ds fleet.Datastore) {
info := &fleet.AppConfig{
OrgName: "Kolide",
OrgLogoURL: "localhost:8080/logo.png",
}
@ -31,11 +31,11 @@ func testOrgInfo(t *testing.T, ds kolide.Datastore) {
info2.SMTPSenderAddress = "123"
info2.SMTPServer = "server"
info2.SMTPPort = 100
info2.SMTPAuthenticationType = kolide.AuthTypeUserNamePassword
info2.SMTPAuthenticationType = fleet.AuthTypeUserNamePassword
info2.SMTPUserName = "username"
info2.SMTPPassword = "password"
info2.SMTPEnableTLS = false
info2.SMTPAuthenticationMethod = kolide.AuthMethodCramMD5
info2.SMTPAuthenticationMethod = fleet.AuthMethodCramMD5
info2.SMTPVerifySSLCerts = true
info2.SMTPEnableStartTLS = true
info2.EnableSSO = true
@ -56,9 +56,9 @@ func testOrgInfo(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, info3, info4)
}
func testAdditionalQueries(t *testing.T, ds kolide.Datastore) {
func testAdditionalQueries(t *testing.T, ds fleet.Datastore) {
additional := json.RawMessage("not valid json")
info := &kolide.AppConfig{
info := &fleet.AppConfig{
OrgName: "Kolide",
OrgLogoURL: "localhost:8080/logo.png",
AdditionalQueries: &additional,
@ -77,8 +77,8 @@ func testAdditionalQueries(t *testing.T, ds kolide.Datastore) {
assert.JSONEq(t, `{"foo":"bar"}`, string(*info.AdditionalQueries))
}
func testEnrollSecrets(t *testing.T, ds kolide.Datastore) {
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
func testEnrollSecrets(t *testing.T, ds fleet.Datastore) {
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
secret, err := ds.VerifyEnrollSecret("missing")
@ -86,7 +86,7 @@ func testEnrollSecrets(t *testing.T, ds kolide.Datastore) {
assert.Nil(t, secret)
err = ds.ApplyEnrollSecrets(&team1.ID,
[]*kolide.EnrollSecret{
[]*fleet.EnrollSecret{
{Secret: "one_secret", TeamID: &team1.ID},
},
)
@ -105,7 +105,7 @@ func testEnrollSecrets(t *testing.T, ds kolide.Datastore) {
// Add global secret
err = ds.ApplyEnrollSecrets(
nil,
[]*kolide.EnrollSecret{
[]*fleet.EnrollSecret{
{Secret: "two_secret"},
},
)
@ -119,7 +119,7 @@ func testEnrollSecrets(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, (*uint)(nil), secret.TeamID)
// Remove team secret
err = ds.ApplyEnrollSecrets(&team1.ID, []*kolide.EnrollSecret{})
err = ds.ApplyEnrollSecrets(&team1.ID, []*fleet.EnrollSecret{})
assert.NoError(t, err)
secret, err = ds.VerifyEnrollSecret("one_secret")
assert.Error(t, err)
@ -129,10 +129,10 @@ func testEnrollSecrets(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, (*uint)(nil), secret.TeamID)
}
func testEnrollSecretsCaseSensitive(t *testing.T, ds kolide.Datastore) {
func testEnrollSecretsCaseSensitive(t *testing.T, ds fleet.Datastore) {
err := ds.ApplyEnrollSecrets(
nil,
[]*kolide.EnrollSecret{
[]*fleet.EnrollSecret{
{Secret: "one_secret"},
},
)
@ -144,8 +144,8 @@ func testEnrollSecretsCaseSensitive(t *testing.T, ds kolide.Datastore) {
assert.Error(t, err, "enroll secret with different case should not verify")
}
func testEnrollSecretRoundtrip(t *testing.T, ds kolide.Datastore) {
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
func testEnrollSecretRoundtrip(t *testing.T, ds fleet.Datastore) {
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
secrets, err := ds.GetEnrollSecrets(nil)
@ -156,7 +156,7 @@ func testEnrollSecretRoundtrip(t *testing.T, ds kolide.Datastore) {
require.NoError(t, err)
assert.Len(t, secrets, 0)
expectedSecrets := []*kolide.EnrollSecret{
expectedSecrets := []*fleet.EnrollSecret{
{Secret: "one_secret"},
{Secret: "two_secret"},
}
@ -183,11 +183,11 @@ func testEnrollSecretRoundtrip(t *testing.T, ds kolide.Datastore) {
}
func testEnrollSecretUniqueness(t *testing.T, ds kolide.Datastore) {
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
func testEnrollSecretUniqueness(t *testing.T, ds fleet.Datastore) {
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
expectedSecrets := []*kolide.EnrollSecret{
expectedSecrets := []*fleet.EnrollSecret{
{Secret: "one_secret"},
}
err = ds.ApplyEnrollSecrets(&team1.ID, expectedSecrets)

View File

@ -5,13 +5,13 @@ import (
"time"
"github.com/WatchBeam/clock"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func checkTargets(t *testing.T, ds kolide.Datastore, campaignID uint, expectedTargets kolide.HostTargets) {
func checkTargets(t *testing.T, ds fleet.Datastore, campaignID uint, expectedTargets fleet.HostTargets) {
targets, err := ds.DistributedQueryCampaignTargetIDs(campaignID)
require.Nil(t, err)
assert.ElementsMatch(t, expectedTargets.HostIDs, targets.HostIDs)
@ -19,14 +19,14 @@ func checkTargets(t *testing.T, ds kolide.Datastore, campaignID uint, expectedTa
assert.ElementsMatch(t, expectedTargets.TeamIDs, targets.TeamIDs)
}
func testDistributedQueryCampaign(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
func testDistributedQueryCampaign(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
mockClock := clock.NewMockClock()
query := test.NewQuery(t, ds, "test", "select * from time", user.ID, false)
campaign := test.NewCampaign(t, ds, query.ID, kolide.QueryRunning, mockClock.Now())
campaign := test.NewCampaign(t, ds, query.ID, fleet.QueryRunning, mockClock.Now())
{
retrieved, err := ds.DistributedQueryCampaign(campaign.ID)
@ -39,46 +39,46 @@ func testDistributedQueryCampaign(t *testing.T, ds kolide.Datastore) {
h2 := test.NewHost(t, ds, "bar.local", "192.168.1.11", "2", "2", mockClock.Now().Add(-1*time.Hour))
h3 := test.NewHost(t, ds, "baz.local", "192.168.1.12", "3", "3", mockClock.Now().Add(-13*time.Minute))
l1 := kolide.LabelSpec{
l1 := fleet.LabelSpec{
ID: 1,
Name: "label foo",
Query: "query foo",
}
l2 := kolide.LabelSpec{
l2 := fleet.LabelSpec{
ID: 2,
Name: "label bar",
Query: "query bar",
}
err := ds.ApplyLabelSpecs([]*kolide.LabelSpec{&l1, &l2})
err := ds.ApplyLabelSpecs([]*fleet.LabelSpec{&l1, &l2})
require.Nil(t, err)
checkTargets(t, ds, campaign.ID, kolide.HostTargets{})
checkTargets(t, ds, campaign.ID, fleet.HostTargets{})
test.AddHostToCampaign(t, ds, campaign.ID, h1.ID)
checkTargets(t, ds, campaign.ID, kolide.HostTargets{HostIDs: []uint{h1.ID}})
checkTargets(t, ds, campaign.ID, fleet.HostTargets{HostIDs: []uint{h1.ID}})
test.AddLabelToCampaign(t, ds, campaign.ID, l1.ID)
checkTargets(t, ds, campaign.ID, kolide.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l1.ID}})
checkTargets(t, ds, campaign.ID, fleet.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l1.ID}})
test.AddLabelToCampaign(t, ds, campaign.ID, l2.ID)
checkTargets(t, ds, campaign.ID, kolide.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l1.ID, l2.ID}})
checkTargets(t, ds, campaign.ID, fleet.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l1.ID, l2.ID}})
test.AddHostToCampaign(t, ds, campaign.ID, h2.ID)
test.AddHostToCampaign(t, ds, campaign.ID, h3.ID)
checkTargets(t, ds, campaign.ID, kolide.HostTargets{HostIDs: []uint{h1.ID, h2.ID, h3.ID}, LabelIDs: []uint{l1.ID, l2.ID}})
checkTargets(t, ds, campaign.ID, fleet.HostTargets{HostIDs: []uint{h1.ID, h2.ID, h3.ID}, LabelIDs: []uint{l1.ID, l2.ID}})
}
func testCleanupDistributedQueryCampaigns(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
func testCleanupDistributedQueryCampaigns(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
mockClock := clock.NewMockClock()
query := test.NewQuery(t, ds, "test", "select * from time", user.ID, false)
c1 := test.NewCampaign(t, ds, query.ID, kolide.QueryWaiting, mockClock.Now())
c2 := test.NewCampaign(t, ds, query.ID, kolide.QueryRunning, mockClock.Now())
c1 := test.NewCampaign(t, ds, query.ID, fleet.QueryWaiting, mockClock.Now())
c2 := test.NewCampaign(t, ds, query.ID, fleet.QueryRunning, mockClock.Now())
// Cleanup and verify that nothing changed (because time has not
// advanced)
@ -113,7 +113,7 @@ func testCleanupDistributedQueryCampaigns(t *testing.T, ds kolide.Datastore) {
retrieved, err := ds.DistributedQueryCampaign(c1.ID)
require.Nil(t, err)
assert.Equal(t, c1.QueryID, retrieved.QueryID)
assert.Equal(t, kolide.QueryComplete, retrieved.Status)
assert.Equal(t, fleet.QueryComplete, retrieved.Status)
}
{
retrieved, err := ds.DistributedQueryCampaign(c2.ID)
@ -133,14 +133,14 @@ func testCleanupDistributedQueryCampaigns(t *testing.T, ds kolide.Datastore) {
retrieved, err := ds.DistributedQueryCampaign(c1.ID)
require.Nil(t, err)
assert.Equal(t, c1.QueryID, retrieved.QueryID)
assert.Equal(t, kolide.QueryComplete, retrieved.Status)
assert.Equal(t, fleet.QueryComplete, retrieved.Status)
}
{
// c2 should now be complete
retrieved, err := ds.DistributedQueryCampaign(c2.ID)
require.Nil(t, err)
assert.Equal(t, c2.QueryID, retrieved.QueryID)
assert.Equal(t, kolide.QueryComplete, retrieved.Status)
assert.Equal(t, fleet.QueryComplete, retrieved.Status)
}
}

View File

@ -5,7 +5,7 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -13,10 +13,10 @@ import (
var mockCreatedAt time.Time = time.Now().UTC().Truncate(time.Second)
func testCarveMetadata(t *testing.T, ds kolide.Datastore) {
func testCarveMetadata(t *testing.T, ds fleet.Datastore) {
h := test.NewHost(t, ds, "foo.local", "192.168.1.10", "1", "1", time.Now())
expectedCarve := &kolide.CarveMetadata{
expectedCarve := &fleet.CarveMetadata{
HostId: h.ID,
Name: "foobar",
BlockCount: 10,
@ -71,12 +71,12 @@ func testCarveMetadata(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, expectedCarve, carve)
}
func testCarveBlocks(t *testing.T, ds kolide.Datastore) {
func testCarveBlocks(t *testing.T, ds fleet.Datastore) {
h := test.NewHost(t, ds, "foo.local", "192.168.1.10", "1", "1", time.Now())
blockCount := int64(25)
blockSize := int64(30)
carve := &kolide.CarveMetadata{
carve := &fleet.CarveMetadata{
HostId: h.ID,
Name: "foobar",
BlockCount: blockCount,
@ -112,12 +112,12 @@ func testCarveBlocks(t *testing.T, ds kolide.Datastore) {
}
func testCarveCleanupCarves(t *testing.T, ds kolide.Datastore) {
func testCarveCleanupCarves(t *testing.T, ds fleet.Datastore) {
h := test.NewHost(t, ds, "foo.local", "192.168.1.10", "1", "1", time.Now())
blockCount := int64(25)
blockSize := int64(30)
carve := &kolide.CarveMetadata{
carve := &fleet.CarveMetadata{
HostId: h.ID,
Name: "foobar",
BlockCount: blockCount,
@ -164,10 +164,10 @@ func testCarveCleanupCarves(t *testing.T, ds kolide.Datastore) {
assert.True(t, carve.Expired)
}
func testCarveListCarves(t *testing.T, ds kolide.Datastore) {
func testCarveListCarves(t *testing.T, ds fleet.Datastore) {
h := test.NewHost(t, ds, "foo.local", "192.168.1.10", "1", "1", time.Now())
expectedCarve := &kolide.CarveMetadata{
expectedCarve := &fleet.CarveMetadata{
HostId: h.ID,
Name: "foobar",
BlockCount: 10,
@ -188,7 +188,7 @@ func testCarveListCarves(t *testing.T, ds kolide.Datastore) {
require.NoError(t, err)
expectedCarve.MaxBlock = 0
expectedCarve2 := &kolide.CarveMetadata{
expectedCarve2 := &fleet.CarveMetadata{
HostId: h.ID,
Name: "foobar2",
BlockCount: 42,
@ -205,28 +205,28 @@ func testCarveListCarves(t *testing.T, ds kolide.Datastore) {
assert.NotEqual(t, 0, expectedCarve2.ID)
expectedCarve2.MaxBlock = -1
carves, err := ds.ListCarves(kolide.CarveListOptions{Expired: true})
carves, err := ds.ListCarves(fleet.CarveListOptions{Expired: true})
require.NoError(t, err)
assert.Equal(t, []*kolide.CarveMetadata{expectedCarve, expectedCarve2}, carves)
assert.Equal(t, []*fleet.CarveMetadata{expectedCarve, expectedCarve2}, carves)
// Expire the carves
_, err = ds.CleanupCarves(time.Now().Add(24 * time.Hour))
require.NoError(t, err)
carves, err = ds.ListCarves(kolide.CarveListOptions{Expired: false})
carves, err = ds.ListCarves(fleet.CarveListOptions{Expired: false})
require.NoError(t, err)
assert.Empty(t, carves)
carves, err = ds.ListCarves(kolide.CarveListOptions{Expired: true})
carves, err = ds.ListCarves(fleet.CarveListOptions{Expired: true})
require.NoError(t, err)
assert.Len(t, carves, 2)
}
func testCarveUpdateCarve(t *testing.T, ds kolide.Datastore) {
func testCarveUpdateCarve(t *testing.T, ds fleet.Datastore) {
h := test.NewHost(t, ds, "foo.local", "192.168.1.10", "1", "1", time.Now())
actualCount := int64(10)
carve := &kolide.CarveMetadata{
carve := &fleet.CarveMetadata{
HostId: h.ID,
Name: "foobar",
BlockCount: actualCount,

View File

@ -3,16 +3,16 @@ package datastore
import (
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testChangeEmail(t *testing.T, ds kolide.Datastore) {
func testChangeEmail(t *testing.T, ds fleet.Datastore) {
if ds.Name() == "inmem" {
t.Skip("inmem is being deprecated, test skipped")
}
user := &kolide.User{
user := &fleet.User{
Username: "bob",
Password: []byte("foobar"),
Email: "bob@bob.com",
@ -34,7 +34,7 @@ func testChangeEmail(t *testing.T, ds kolide.Datastore) {
// test that wrong user can't confirm e-mail change
err = ds.PendingEmailChange(user.ID, "other@bob.com", "uniquetoken")
require.Nil(t, err)
otheruser, err := ds.NewUser(&kolide.User{
otheruser, err := ds.NewUser(&fleet.User{
Username: "fred",
Password: []byte("supersecret"),
Email: "other@bobcom",

View File

@ -10,7 +10,7 @@ import (
"time"
"github.com/WatchBeam/clock"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
@ -21,17 +21,17 @@ var enrollTests = []struct {
uuid, hostname, platform, nodeKey string
}{
0: {uuid: "6D14C88F-8ECF-48D5-9197-777647BF6B26",
hostname: "web.kolide.co",
hostname: "web.fleet.co",
platform: "linux",
nodeKey: "key0",
},
1: {uuid: "B998C0EB-38CE-43B1-A743-FBD7A5C9513B",
hostname: "mail.kolide.co",
hostname: "mail.fleet.co",
platform: "linux",
nodeKey: "key1",
},
2: {uuid: "008F0688-5311-4C59-86EE-00C2D6FC3EC2",
hostname: "home.kolide.co",
hostname: "home.fleet.co",
platform: "darwin",
nodeKey: "key2",
},
@ -42,8 +42,8 @@ var enrollTests = []struct {
},
}
func testSaveHosts(t *testing.T, ds kolide.Datastore) {
host, err := ds.NewHost(&kolide.Host{
func testSaveHosts(t *testing.T, ds fleet.Datastore) {
host, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -93,8 +93,8 @@ func testSaveHosts(t *testing.T, ds kolide.Datastore) {
assert.Nil(t, host)
}
func testSaveHostPackStats(t *testing.T, ds kolide.Datastore) {
host, err := ds.NewHost(&kolide.Host{
func testSaveHostPackStats(t *testing.T, ds fleet.Datastore) {
host, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -111,7 +111,7 @@ func testSaveHostPackStats(t *testing.T, ds kolide.Datastore) {
pack1 := test.NewPack(t, ds, "test1")
query1 := test.NewQuery(t, ds, "time", "select * from time", 0, true)
squery1 := test.NewScheduledQuery(t, ds, pack1.ID, query1.ID, 30, true, true, "time-scheduled")
stats1 := []kolide.ScheduledQueryStats{
stats1 := []fleet.ScheduledQueryStats{
{
ScheduledQueryName: squery1.Name,
ScheduledQueryID: squery1.ID,
@ -134,7 +134,7 @@ func testSaveHostPackStats(t *testing.T, ds kolide.Datastore) {
squery2 := test.NewScheduledQuery(t, ds, pack2.ID, query1.ID, 30, true, true, "time-scheduled")
query2 := test.NewQuery(t, ds, "processes", "select * from processes", 0, true)
squery3 := test.NewScheduledQuery(t, ds, pack2.ID, query2.ID, 30, true, true, "processes")
stats2 := []kolide.ScheduledQueryStats{
stats2 := []fleet.ScheduledQueryStats{
{
ScheduledQueryName: squery2.Name,
ScheduledQueryID: squery2.ID,
@ -169,13 +169,13 @@ func testSaveHostPackStats(t *testing.T, ds kolide.Datastore) {
},
}
host.PackStats = []kolide.PackStats{
host.PackStats = []fleet.PackStats{
{
PackName: "test1",
// Append an additional entry to be sure that receiving stats for a
// now-deleted query doesn't break saving. This extra entry should
// not be returned on loading the host.
QueryStats: append(stats1, kolide.ScheduledQueryStats{PackName: "foo", ScheduledQueryName: "bar"}),
QueryStats: append(stats1, fleet.ScheduledQueryStats{PackName: "foo", ScheduledQueryName: "bar"}),
},
{
PackName: "test2",
@ -205,15 +205,15 @@ func testSaveHostPackStats(t *testing.T, ds kolide.Datastore) {
require.Len(t, host.PackStats, 2)
// Set to empty should make it empty
host.PackStats = []kolide.PackStats{}
host.PackStats = []fleet.PackStats{}
require.NoError(t, ds.SaveHost(host))
host, err = ds.Host(host.ID)
require.NoError(t, err)
require.Len(t, host.PackStats, 0)
}
func testDeleteHost(t *testing.T, ds kolide.Datastore) {
host, err := ds.NewHost(&kolide.Host{
func testDeleteHost(t *testing.T, ds fleet.Datastore) {
host, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -231,10 +231,10 @@ func testDeleteHost(t *testing.T, ds kolide.Datastore) {
assert.NotNil(t, err)
}
func testListHosts(t *testing.T, ds kolide.Datastore) {
hosts := []*kolide.Host{}
func testListHosts(t *testing.T, ds fleet.Datastore) {
hosts := []*fleet.Host{}
for i := 0; i < 10; i++ {
host, err := ds.NewHost(&kolide.Host{
host, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -250,35 +250,35 @@ func testListHosts(t *testing.T, ds kolide.Datastore) {
hosts = append(hosts, host)
}
filter := kolide.TeamFilter{User: test.UserAdmin}
hosts2, err := ds.ListHosts(filter, kolide.HostListOptions{})
filter := fleet.TeamFilter{User: test.UserAdmin}
hosts2, err := ds.ListHosts(filter, fleet.HostListOptions{})
require.Nil(t, err)
assert.Equal(t, len(hosts), len(hosts2))
// Test with logic for only a few hosts
hosts2, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{PerPage: 4, Page: 0}})
hosts2, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{PerPage: 4, Page: 0}})
require.Nil(t, err)
assert.Equal(t, 4, len(hosts2))
err = ds.DeleteHost(hosts[0].ID)
require.Nil(t, err)
hosts2, err = ds.ListHosts(filter, kolide.HostListOptions{})
hosts2, err = ds.ListHosts(filter, fleet.HostListOptions{})
require.Nil(t, err)
assert.Equal(t, len(hosts)-1, len(hosts2))
hosts, err = ds.ListHosts(filter, kolide.HostListOptions{})
hosts, err = ds.ListHosts(filter, fleet.HostListOptions{})
require.Nil(t, err)
require.Equal(t, len(hosts2), len(hosts))
err = ds.SaveHost(hosts[0])
require.Nil(t, err)
hosts2, err = ds.ListHosts(filter, kolide.HostListOptions{})
hosts2, err = ds.ListHosts(filter, fleet.HostListOptions{})
require.Nil(t, err)
require.Equal(t, hosts[0].ID, hosts2[0].ID)
}
func testListHostsFilterAdditional(t *testing.T, ds kolide.Datastore) {
h, err := ds.NewHost(&kolide.Host{
func testListHostsFilterAdditional(t *testing.T, ds fleet.Datastore) {
h, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -289,34 +289,34 @@ func testListHostsFilterAdditional(t *testing.T, ds kolide.Datastore) {
})
require.Nil(t, err)
filter := kolide.TeamFilter{User: test.UserAdmin}
filter := fleet.TeamFilter{User: test.UserAdmin}
// Add additional
additional := json.RawMessage(`{"field1": "v1", "field2": "v2"}`)
h.Additional = &additional
require.NoError(t, ds.SaveHostAdditional(h))
hosts, err := ds.ListHosts(filter, kolide.HostListOptions{})
hosts, err := ds.ListHosts(filter, fleet.HostListOptions{})
require.Nil(t, err)
assert.Nil(t, hosts[0].Additional)
hosts, err = ds.ListHosts(filter, kolide.HostListOptions{AdditionalFilters: []string{"field1", "field2"}})
hosts, err = ds.ListHosts(filter, fleet.HostListOptions{AdditionalFilters: []string{"field1", "field2"}})
require.Nil(t, err)
assert.Equal(t, &additional, hosts[0].Additional)
hosts, err = ds.ListHosts(filter, kolide.HostListOptions{AdditionalFilters: []string{"*"}})
hosts, err = ds.ListHosts(filter, fleet.HostListOptions{AdditionalFilters: []string{"*"}})
require.Nil(t, err)
assert.Equal(t, &additional, hosts[0].Additional)
additional = json.RawMessage(`{"field1": "v1", "missing": null}`)
hosts, err = ds.ListHosts(filter, kolide.HostListOptions{AdditionalFilters: []string{"field1", "missing"}})
hosts, err = ds.ListHosts(filter, fleet.HostListOptions{AdditionalFilters: []string{"field1", "missing"}})
require.Nil(t, err)
assert.Equal(t, &additional, hosts[0].Additional)
}
func testListHostsStatus(t *testing.T, ds kolide.Datastore) {
func testListHostsStatus(t *testing.T, ds fleet.Datastore) {
for i := 0; i < 10; i++ {
_, err := ds.NewHost(&kolide.Host{
_, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now().Add(-time.Duration(i) * time.Minute),
@ -331,29 +331,29 @@ func testListHostsStatus(t *testing.T, ds kolide.Datastore) {
}
}
filter := kolide.TeamFilter{User: test.UserAdmin}
filter := fleet.TeamFilter{User: test.UserAdmin}
hosts, err := ds.ListHosts(filter, kolide.HostListOptions{StatusFilter: "online"})
hosts, err := ds.ListHosts(filter, fleet.HostListOptions{StatusFilter: "online"})
require.Nil(t, err)
assert.Equal(t, 1, len(hosts))
hosts, err = ds.ListHosts(filter, kolide.HostListOptions{StatusFilter: "offline"})
hosts, err = ds.ListHosts(filter, fleet.HostListOptions{StatusFilter: "offline"})
require.Nil(t, err)
assert.Equal(t, 9, len(hosts))
hosts, err = ds.ListHosts(filter, kolide.HostListOptions{StatusFilter: "mia"})
hosts, err = ds.ListHosts(filter, fleet.HostListOptions{StatusFilter: "mia"})
require.Nil(t, err)
assert.Equal(t, 0, len(hosts))
hosts, err = ds.ListHosts(filter, kolide.HostListOptions{StatusFilter: "new"})
hosts, err = ds.ListHosts(filter, fleet.HostListOptions{StatusFilter: "new"})
require.Nil(t, err)
assert.Equal(t, 10, len(hosts))
}
func testListHostsQuery(t *testing.T, ds kolide.Datastore) {
hosts := []*kolide.Host{}
func testListHostsQuery(t *testing.T, ds fleet.Datastore) {
hosts := []*fleet.Host{}
for i := 0; i < 10; i++ {
host, err := ds.NewHost(&kolide.Host{
host, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -369,57 +369,57 @@ func testListHostsQuery(t *testing.T, ds kolide.Datastore) {
hosts = append(hosts, host)
}
filter := kolide.TeamFilter{User: test.UserAdmin}
filter := fleet.TeamFilter{User: test.UserAdmin}
gotHosts, err := ds.ListHosts(filter, kolide.HostListOptions{})
gotHosts, err := ds.ListHosts(filter, fleet.HostListOptions{})
require.Nil(t, err)
assert.Equal(t, len(hosts), len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "00"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "00"}})
require.Nil(t, err)
assert.Equal(t, 10, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "000"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "000"}})
require.Nil(t, err)
assert.Equal(t, 1, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "192.168."}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "192.168."}})
require.Nil(t, err)
assert.Equal(t, 10, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "192.168.1.1"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "192.168.1.1"}})
require.Nil(t, err)
assert.Equal(t, 1, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "hostname%00"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "hostname%00"}})
require.Nil(t, err)
assert.Equal(t, 10, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "hostname%003"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "hostname%003"}})
require.Nil(t, err)
assert.Equal(t, 1, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "uuid_"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "uuid_"}})
require.Nil(t, err)
assert.Equal(t, 10, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "uuid_006"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "uuid_006"}})
require.Nil(t, err)
assert.Equal(t, 1, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "serial"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "serial"}})
require.Nil(t, err)
assert.Equal(t, 10, len(gotHosts))
gotHosts, err = ds.ListHosts(filter, kolide.HostListOptions{ListOptions: kolide.ListOptions{MatchQuery: "serial009"}})
gotHosts, err = ds.ListHosts(filter, fleet.HostListOptions{ListOptions: fleet.ListOptions{MatchQuery: "serial009"}})
require.Nil(t, err)
assert.Equal(t, 1, len(gotHosts))
}
func testEnrollHost(t *testing.T, ds kolide.Datastore) {
func testEnrollHost(t *testing.T, ds fleet.Datastore) {
test.AddAllHostsLabel(t, ds)
team, err := ds.NewTeam(&kolide.Team{Name: "team1"})
team, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
for _, tt := range enrollTests {
@ -439,7 +439,7 @@ func testEnrollHost(t *testing.T, ds kolide.Datastore) {
}
}
func testAuthenticateHost(t *testing.T, ds kolide.Datastore) {
func testAuthenticateHost(t *testing.T, ds fleet.Datastore) {
test.AddAllHostsLabel(t, ds)
for _, tt := range enrollTests {
h, err := ds.EnrollHost(tt.uuid, tt.nodeKey, nil, 0)
@ -457,7 +457,7 @@ func testAuthenticateHost(t *testing.T, ds kolide.Datastore) {
assert.Error(t, err)
}
func testAuthenticateHostCaseSensitive(t *testing.T, ds kolide.Datastore) {
func testAuthenticateHostCaseSensitive(t *testing.T, ds fleet.Datastore) {
test.AddAllHostsLabel(t, ds)
for _, tt := range enrollTests {
h, err := ds.EnrollHost(tt.uuid, tt.nodeKey, nil, 0)
@ -468,8 +468,8 @@ func testAuthenticateHostCaseSensitive(t *testing.T, ds kolide.Datastore) {
}
}
func testSearchHosts(t *testing.T, ds kolide.Datastore) {
_, err := ds.NewHost(&kolide.Host{
func testSearchHosts(t *testing.T, ds fleet.Datastore) {
_, err := ds.NewHost(&fleet.Host{
OsqueryHostID: "1234",
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
@ -480,7 +480,7 @@ func testSearchHosts(t *testing.T, ds kolide.Datastore) {
})
require.Nil(t, err)
h2, err := ds.NewHost(&kolide.Host{
h2, err := ds.NewHost(&fleet.Host{
OsqueryHostID: "5679",
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
@ -491,7 +491,7 @@ func testSearchHosts(t *testing.T, ds kolide.Datastore) {
})
require.Nil(t, err)
h3, err := ds.NewHost(&kolide.Host{
h3, err := ds.NewHost(&fleet.Host{
OsqueryHostID: "99999",
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
@ -502,8 +502,8 @@ func testSearchHosts(t *testing.T, ds kolide.Datastore) {
})
require.Nil(t, err)
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
// We once threw errors when the search query was empty. Verify that we
// don't error.
@ -557,11 +557,11 @@ func testSearchHosts(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, 1, len(hits))
}
func testSearchHostsLimit(t *testing.T, ds kolide.Datastore) {
filter := kolide.TeamFilter{User: test.UserAdmin}
func testSearchHostsLimit(t *testing.T, ds fleet.Datastore) {
filter := fleet.TeamFilter{User: test.UserAdmin}
for i := 0; i < 15; i++ {
_, err := ds.NewHost(&kolide.Host{
_, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -578,8 +578,8 @@ func testSearchHostsLimit(t *testing.T, ds kolide.Datastore) {
assert.Len(t, hosts, 10)
}
func testGenerateHostStatusStatistics(t *testing.T, ds kolide.Datastore) {
filter := kolide.TeamFilter{User: test.UserAdmin}
func testGenerateHostStatusStatistics(t *testing.T, ds fleet.Datastore) {
filter := fleet.TeamFilter{User: test.UserAdmin}
mockClock := clock.NewMockClock()
online, offline, mia, new, err := ds.GenerateHostStatusStatistics(filter, mockClock.Now())
@ -590,7 +590,7 @@ func testGenerateHostStatusStatistics(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, uint(0), new)
// Online
h, err := ds.NewHost(&kolide.Host{
h, err := ds.NewHost(&fleet.Host{
ID: 1,
OsqueryHostID: "1",
NodeKey: "1",
@ -604,7 +604,7 @@ func testGenerateHostStatusStatistics(t *testing.T, ds kolide.Datastore) {
require.Nil(t, ds.SaveHost(h))
// Online
h, err = ds.NewHost(&kolide.Host{
h, err = ds.NewHost(&fleet.Host{
ID: 2,
OsqueryHostID: "2",
NodeKey: "2",
@ -618,7 +618,7 @@ func testGenerateHostStatusStatistics(t *testing.T, ds kolide.Datastore) {
require.Nil(t, ds.SaveHost(h))
// Offline
h, err = ds.NewHost(&kolide.Host{
h, err = ds.NewHost(&fleet.Host{
ID: 3,
OsqueryHostID: "3",
NodeKey: "3",
@ -632,7 +632,7 @@ func testGenerateHostStatusStatistics(t *testing.T, ds kolide.Datastore) {
require.Nil(t, ds.SaveHost(h))
// MIA
h, err = ds.NewHost(&kolide.Host{
h, err = ds.NewHost(&fleet.Host{
ID: 4,
OsqueryHostID: "4",
NodeKey: "4",
@ -657,13 +657,13 @@ func testGenerateHostStatusStatistics(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, uint(4), new)
}
func testMarkHostSeen(t *testing.T, ds kolide.Datastore) {
func testMarkHostSeen(t *testing.T, ds fleet.Datastore) {
mockClock := clock.NewMockClock()
anHourAgo := mockClock.Now().Add(-1 * time.Hour).UTC()
aDayAgo := mockClock.Now().Add(-24 * time.Hour).UTC()
h1, err := ds.NewHost(&kolide.Host{
h1, err := ds.NewHost(&fleet.Host{
ID: 1,
OsqueryHostID: "1",
UUID: "1",
@ -692,14 +692,14 @@ func testMarkHostSeen(t *testing.T, ds kolide.Datastore) {
}
}
func testMarkHostsSeen(t *testing.T, ds kolide.Datastore) {
func testMarkHostsSeen(t *testing.T, ds fleet.Datastore) {
mockClock := clock.NewMockClock()
aSecondAgo := mockClock.Now().Add(-1 * time.Second).UTC()
anHourAgo := mockClock.Now().Add(-1 * time.Hour).UTC()
aDayAgo := mockClock.Now().Add(-24 * time.Hour).UTC()
h1, err := ds.NewHost(&kolide.Host{
h1, err := ds.NewHost(&fleet.Host{
ID: 1,
OsqueryHostID: "1",
UUID: "1",
@ -710,7 +710,7 @@ func testMarkHostsSeen(t *testing.T, ds kolide.Datastore) {
})
require.Nil(t, err)
h2, err := ds.NewHost(&kolide.Host{
h2, err := ds.NewHost(&fleet.Host{
ID: 2,
OsqueryHostID: "2",
UUID: "2",
@ -753,10 +753,10 @@ func testMarkHostsSeen(t *testing.T, ds kolide.Datastore) {
}
func testCleanupIncomingHosts(t *testing.T, ds kolide.Datastore) {
func testCleanupIncomingHosts(t *testing.T, ds fleet.Datastore) {
mockClock := clock.NewMockClock()
h1, err := ds.NewHost(&kolide.Host{
h1, err := ds.NewHost(&fleet.Host{
ID: 1,
OsqueryHostID: "1",
UUID: "1",
@ -767,7 +767,7 @@ func testCleanupIncomingHosts(t *testing.T, ds kolide.Datastore) {
})
require.Nil(t, err)
h2, err := ds.NewHost(&kolide.Host{
h2, err := ds.NewHost(&fleet.Host{
ID: 2,
OsqueryHostID: "2",
UUID: "2",
@ -799,9 +799,9 @@ func testCleanupIncomingHosts(t *testing.T, ds kolide.Datastore) {
assert.Nil(t, err)
}
func testHostIDsByName(t *testing.T, ds kolide.Datastore) {
func testHostIDsByName(t *testing.T, ds fleet.Datastore) {
for i := 0; i < 10; i++ {
_, err := ds.NewHost(&kolide.Host{
_, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -813,15 +813,15 @@ func testHostIDsByName(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
}
filter := kolide.TeamFilter{User: test.UserAdmin}
filter := fleet.TeamFilter{User: test.UserAdmin}
hosts, err := ds.HostIDsByName(filter, []string{"foo.2.local", "foo.1.local", "foo.5.local"})
require.Nil(t, err)
sort.Slice(hosts, func(i, j int) bool { return hosts[i] < hosts[j] })
assert.Equal(t, hosts, []uint{2, 3, 6})
}
func testHostAdditional(t *testing.T, ds kolide.Datastore) {
_, err := ds.NewHost(&kolide.Host{
func testHostAdditional(t *testing.T, ds fleet.Datastore) {
_, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -891,9 +891,9 @@ func testHostAdditional(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, &additional, h.Additional)
}
func testHostByIdentifier(t *testing.T, ds kolide.Datastore) {
func testHostByIdentifier(t *testing.T, ds fleet.Datastore) {
for i := 1; i <= 10; i++ {
_, err := ds.NewHost(&kolide.Host{
_, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -906,7 +906,7 @@ func testHostByIdentifier(t *testing.T, ds kolide.Datastore) {
}
var (
h *kolide.Host
h *fleet.Host
err error
)
h, err = ds.HostByIdentifier("uuid_1")
@ -929,10 +929,10 @@ func testHostByIdentifier(t *testing.T, ds kolide.Datastore) {
require.Error(t, err)
}
func testAddHostsToTeam(t *testing.T, ds kolide.Datastore) {
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
func testAddHostsToTeam(t *testing.T, ds fleet.Datastore) {
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
team2, err := ds.NewTeam(&kolide.Team{Name: "team2"})
team2, err := ds.NewTeam(&fleet.Team{Name: "team2"})
require.NoError(t, err)
for i := 0; i < 10; i++ {

View File

@ -5,26 +5,26 @@ import (
"fmt"
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/guregu/null.v3"
)
func testCreateInvite(t *testing.T, ds kolide.Datastore) {
func testCreateInvite(t *testing.T, ds fleet.Datastore) {
for i := 0; i < 3; i++ {
_, err := ds.NewTeam(&kolide.Team{Name: fmt.Sprintf("%d", i)})
_, err := ds.NewTeam(&fleet.Team{Name: fmt.Sprintf("%d", i)})
require.NoError(t, err)
}
invite := &kolide.Invite{
invite := &fleet.Invite{
Email: "user@foo.com",
Name: "user",
Token: "some_user",
Teams: []kolide.UserTeam{
{Role: "observer", Team: kolide.Team{ID: 1}},
{Role: "maintainer", Team: kolide.Team{ID: 3}},
Teams: []fleet.UserTeam{
{Role: "observer", Team: fleet.Team{ID: 1}},
{Role: "maintainer", Team: fleet.Team{ID: 3}},
},
}
@ -38,9 +38,9 @@ func testCreateInvite(t *testing.T, ds kolide.Datastore) {
assert.Len(t, invite.Teams, 2)
}
func setupTestInvites(t *testing.T, ds kolide.Datastore) {
func setupTestInvites(t *testing.T, ds fleet.Datastore) {
var err error
admin := &kolide.Invite{
admin := &fleet.Invite{
Email: "admin@foo.com",
Name: "Xadmin",
Token: "admin",
@ -51,7 +51,7 @@ func setupTestInvites(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
for user := 0; user < 23; user++ {
i := kolide.Invite{
i := fleet.Invite{
InvitedBy: admin.ID,
Email: fmt.Sprintf("user%d@foo.com", user),
Name: fmt.Sprintf("User%02d", user),
@ -65,13 +65,13 @@ func setupTestInvites(t *testing.T, ds kolide.Datastore) {
}
func testListInvites(t *testing.T, ds kolide.Datastore) {
func testListInvites(t *testing.T, ds fleet.Datastore) {
setupTestInvites(t, ds)
opt := kolide.ListOptions{
opt := fleet.ListOptions{
Page: 0,
PerPage: 10,
OrderDirection: kolide.OrderAscending,
OrderDirection: fleet.OrderAscending,
OrderKey: "name",
}
@ -84,7 +84,7 @@ func testListInvites(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, null.StringFrom("observer"), result[9].GlobalRole)
opt.Page = 2
opt.OrderDirection = kolide.OrderDescending
opt.OrderDirection = fleet.OrderDescending
result, err = ds.ListInvites(opt)
assert.Nil(t, err)
assert.Equal(t, 4, len(result)) // allow for admin we created
@ -92,7 +92,7 @@ func testListInvites(t *testing.T, ds kolide.Datastore) {
}
func testDeleteInvite(t *testing.T, ds kolide.Datastore) {
func testDeleteInvite(t *testing.T, ds fleet.Datastore) {
setupTestInvites(t, ds)
@ -110,7 +110,7 @@ func testDeleteInvite(t *testing.T, ds kolide.Datastore) {
}
func testInviteByToken(t *testing.T, ds kolide.Datastore) {
func testInviteByToken(t *testing.T, ds fleet.Datastore) {
setupTestInvites(t, ds)
var inviteTests = []struct {
@ -142,7 +142,7 @@ func testInviteByToken(t *testing.T, ds kolide.Datastore) {
}
}
func testInviteByEmail(t *testing.T, ds kolide.Datastore) {
func testInviteByEmail(t *testing.T, ds fleet.Datastore) {
setupTestInvites(t, ds)
var inviteTests = []struct {

View File

@ -7,17 +7,17 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testLabels(t *testing.T, db kolide.Datastore) {
func testLabels(t *testing.T, db fleet.Datastore) {
test.AddAllHostsLabel(t, db)
hosts := []kolide.Host{}
var host *kolide.Host
hosts := []fleet.Host{}
var host *fleet.Host
var err error
for i := 0; i < 10; i++ {
host, err = db.EnrollHost(fmt.Sprint(i), fmt.Sprint(i), nil, 0)
@ -39,23 +39,23 @@ func testLabels(t *testing.T, db kolide.Datastore) {
assert.Nil(t, err)
assert.Len(t, labels, 1)
newLabels := []*kolide.LabelSpec{
newLabels := []*fleet.LabelSpec{
// Note these are intentionally out of order
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "label3",
Query: "query3",
Platform: "darwin",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "label1",
Query: "query1",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "label2",
Query: "query2",
Platform: "darwin",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "label4",
Query: "query4",
Platform: "darwin",
@ -101,8 +101,8 @@ func testLabels(t *testing.T, db kolide.Datastore) {
// A new label targeting another platform should not effect the labels for
// this host
err = db.ApplyLabelSpecs([]*kolide.LabelSpec{
&kolide.LabelSpec{
err = db.ApplyLabelSpecs([]*fleet.LabelSpec{
&fleet.LabelSpec{
Name: "label5",
Platform: "not-matching",
Query: "query5",
@ -114,8 +114,8 @@ func testLabels(t *testing.T, db kolide.Datastore) {
assert.Len(t, queries, 0)
// If a new label is added, all labels should be returned
err = db.ApplyLabelSpecs([]*kolide.LabelSpec{
&kolide.LabelSpec{
err = db.ApplyLabelSpecs([]*fleet.LabelSpec{
&fleet.LabelSpec{
Name: "label6",
Platform: "",
Query: "query6",
@ -156,32 +156,32 @@ func testLabels(t *testing.T, db kolide.Datastore) {
assert.Len(t, labels, 1)
}
func testManagingLabelsOnPacks(t *testing.T, ds kolide.Datastore) {
pack := &kolide.PackSpec{
func testManagingLabelsOnPacks(t *testing.T, ds fleet.Datastore) {
pack := &fleet.PackSpec{
ID: 1,
Name: "pack1",
}
err := ds.ApplyPackSpecs([]*kolide.PackSpec{pack})
err := ds.ApplyPackSpecs([]*fleet.PackSpec{pack})
require.Nil(t, err)
labels, err := ds.ListLabelsForPack(pack.ID)
require.Nil(t, err)
assert.Len(t, labels, 0)
mysqlLabel := &kolide.LabelSpec{
mysqlLabel := &fleet.LabelSpec{
ID: 1,
Name: "MySQL Monitoring",
Query: "select pid from processes where name = 'mysqld';",
}
err = ds.ApplyLabelSpecs([]*kolide.LabelSpec{mysqlLabel})
err = ds.ApplyLabelSpecs([]*fleet.LabelSpec{mysqlLabel})
require.Nil(t, err)
pack.Targets = kolide.PackSpecTargets{
pack.Targets = fleet.PackSpecTargets{
Labels: []string{
mysqlLabel.Name,
},
}
err = ds.ApplyPackSpecs([]*kolide.PackSpec{pack})
err = ds.ApplyPackSpecs([]*fleet.PackSpec{pack})
require.Nil(t, err)
labels, err = ds.ListLabelsForPack(pack.ID)
@ -190,21 +190,21 @@ func testManagingLabelsOnPacks(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, "MySQL Monitoring", labels[0].Name)
}
osqueryLabel := &kolide.LabelSpec{
osqueryLabel := &fleet.LabelSpec{
ID: 2,
Name: "Osquery Monitoring",
Query: "select pid from processes where name = 'osqueryd';",
}
err = ds.ApplyLabelSpecs([]*kolide.LabelSpec{mysqlLabel, osqueryLabel})
err = ds.ApplyLabelSpecs([]*fleet.LabelSpec{mysqlLabel, osqueryLabel})
require.Nil(t, err)
pack.Targets = kolide.PackSpecTargets{
pack.Targets = fleet.PackSpecTargets{
Labels: []string{
mysqlLabel.Name,
osqueryLabel.Name,
},
}
err = ds.ApplyPackSpecs([]*kolide.PackSpec{pack})
err = ds.ApplyPackSpecs([]*fleet.PackSpec{pack})
require.Nil(t, err)
labels, err = ds.ListLabelsForPack(pack.ID)
@ -212,24 +212,24 @@ func testManagingLabelsOnPacks(t *testing.T, ds kolide.Datastore) {
assert.Len(t, labels, 2)
}
func testSearchLabels(t *testing.T, db kolide.Datastore) {
specs := []*kolide.LabelSpec{
&kolide.LabelSpec{
func testSearchLabels(t *testing.T, db fleet.Datastore) {
specs := []*fleet.LabelSpec{
&fleet.LabelSpec{
ID: 1,
Name: "foo",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
ID: 2,
Name: "bar",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
ID: 3,
Name: "foo-bar",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
ID: 4,
Name: "All Hosts",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
}
err := db.ApplyLabelSpecs(specs)
@ -240,8 +240,8 @@ func testSearchLabels(t *testing.T, db kolide.Datastore) {
l3, err := db.Label(specs[2].ID)
require.Nil(t, err)
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
// We once threw errors when the search query was empty. Verify that we
// don't error.
@ -265,36 +265,36 @@ func testSearchLabels(t *testing.T, db kolide.Datastore) {
assert.Contains(t, labels, all)
}
func testSearchLabelsLimit(t *testing.T, db kolide.Datastore) {
func testSearchLabelsLimit(t *testing.T, db fleet.Datastore) {
if db.Name() == "inmem" {
t.Skip("inmem is being deprecated, test skipped")
}
all := &kolide.LabelSpec{
all := &fleet.LabelSpec{
Name: "All Hosts",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
}
err := db.ApplyLabelSpecs([]*kolide.LabelSpec{all})
err := db.ApplyLabelSpecs([]*fleet.LabelSpec{all})
require.Nil(t, err)
for i := 0; i < 15; i++ {
l := &kolide.LabelSpec{
l := &fleet.LabelSpec{
Name: fmt.Sprintf("foo%d", i),
}
err := db.ApplyLabelSpecs([]*kolide.LabelSpec{l})
err := db.ApplyLabelSpecs([]*fleet.LabelSpec{l})
require.Nil(t, err)
}
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
labels, err := db.SearchLabels(filter, "foo")
require.Nil(t, err)
assert.Len(t, labels, 11)
}
func testListHostsInLabel(t *testing.T, db kolide.Datastore) {
h1, err := db.NewHost(&kolide.Host{
func testListHostsInLabel(t *testing.T, db fleet.Datastore) {
h1, err := db.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -305,7 +305,7 @@ func testListHostsInLabel(t *testing.T, db kolide.Datastore) {
})
require.Nil(t, err)
h2, err := db.NewHost(&kolide.Host{
h2, err := db.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -316,7 +316,7 @@ func testListHostsInLabel(t *testing.T, db kolide.Datastore) {
})
require.Nil(t, err)
h3, err := db.NewHost(&kolide.Host{
h3, err := db.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -327,52 +327,52 @@ func testListHostsInLabel(t *testing.T, db kolide.Datastore) {
})
require.Nil(t, err)
l1 := &kolide.LabelSpec{
l1 := &fleet.LabelSpec{
ID: 1,
Name: "label foo",
Query: "query1",
}
err = db.ApplyLabelSpecs([]*kolide.LabelSpec{l1})
err = db.ApplyLabelSpecs([]*fleet.LabelSpec{l1})
require.Nil(t, err)
filter := kolide.TeamFilter{User: test.UserAdmin}
filter := fleet.TeamFilter{User: test.UserAdmin}
{
hosts, err := db.ListHostsInLabel(filter, l1.ID, kolide.HostListOptions{})
hosts, err := db.ListHostsInLabel(filter, l1.ID, fleet.HostListOptions{})
require.Nil(t, err)
assert.Len(t, hosts, 0)
}
for _, h := range []*kolide.Host{h1, h2, h3} {
for _, h := range []*fleet.Host{h1, h2, h3} {
err = db.RecordLabelQueryExecutions(h, map[uint]bool{l1.ID: true}, time.Now())
assert.Nil(t, err)
}
{
hosts, err := db.ListHostsInLabel(filter, l1.ID, kolide.HostListOptions{})
hosts, err := db.ListHostsInLabel(filter, l1.ID, fleet.HostListOptions{})
require.Nil(t, err)
assert.Len(t, hosts, 3)
}
}
func testBuiltInLabels(t *testing.T, db kolide.Datastore) {
func testBuiltInLabels(t *testing.T, db fleet.Datastore) {
require.Nil(t, db.MigrateData())
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
hits, err := db.SearchLabels(filter, "macOS")
require.Nil(t, err)
// Should get Mac OS X and All Hosts
assert.Equal(t, 2, len(hits))
assert.Equal(t, kolide.LabelTypeBuiltIn, hits[0].LabelType)
assert.Equal(t, kolide.LabelTypeBuiltIn, hits[1].LabelType)
assert.Equal(t, fleet.LabelTypeBuiltIn, hits[0].LabelType)
assert.Equal(t, fleet.LabelTypeBuiltIn, hits[1].LabelType)
}
func testListUniqueHostsInLabels(t *testing.T, db kolide.Datastore) {
hosts := []*kolide.Host{}
func testListUniqueHostsInLabels(t *testing.T, db fleet.Datastore) {
hosts := []*fleet.Host{}
for i := 0; i < 4; i++ {
h, err := db.NewHost(&kolide.Host{
h, err := db.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -386,17 +386,17 @@ func testListUniqueHostsInLabels(t *testing.T, db kolide.Datastore) {
hosts = append(hosts, h)
}
l1 := kolide.LabelSpec{
l1 := fleet.LabelSpec{
ID: 1,
Name: "label foo",
Query: "query1",
}
l2 := kolide.LabelSpec{
l2 := fleet.LabelSpec{
ID: 2,
Name: "label bar",
Query: "query2",
}
err := db.ApplyLabelSpecs([]*kolide.LabelSpec{&l1, &l2})
err := db.ApplyLabelSpecs([]*fleet.LabelSpec{&l1, &l2})
require.Nil(t, err)
for i := 0; i < 3; i++ {
@ -409,35 +409,35 @@ func testListUniqueHostsInLabels(t *testing.T, db kolide.Datastore) {
assert.Nil(t, err)
}
filter := kolide.TeamFilter{User: test.UserAdmin}
filter := fleet.TeamFilter{User: test.UserAdmin}
uniqueHosts, err := db.ListUniqueHostsInLabels(filter, []uint{l1.ID, l2.ID})
assert.Nil(t, err)
assert.Equal(t, len(hosts), len(uniqueHosts))
labels, err := db.ListLabels(filter, kolide.ListOptions{})
labels, err := db.ListLabels(filter, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, labels, 2)
}
func testChangeLabelDetails(t *testing.T, db kolide.Datastore) {
func testChangeLabelDetails(t *testing.T, db fleet.Datastore) {
if db.Name() == "inmem" {
t.Skip("inmem is being deprecated")
}
label := kolide.LabelSpec{
label := fleet.LabelSpec{
ID: 1,
Name: "my label",
Description: "a label",
Query: "select 1 from processes",
Platform: "darwin",
}
err := db.ApplyLabelSpecs([]*kolide.LabelSpec{&label})
err := db.ApplyLabelSpecs([]*fleet.LabelSpec{&label})
require.Nil(t, err)
label.Description = "changed description"
err = db.ApplyLabelSpecs([]*kolide.LabelSpec{&label})
err = db.ApplyLabelSpecs([]*fleet.LabelSpec{&label})
require.Nil(t, err)
saved, err := db.Label(label.ID)
@ -445,9 +445,9 @@ func testChangeLabelDetails(t *testing.T, db kolide.Datastore) {
assert.Equal(t, label.Name, saved.Name)
}
func setupLabelSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.LabelSpec {
func setupLabelSpecsTest(t *testing.T, ds fleet.Datastore) []*fleet.LabelSpec {
for i := 0; i < 10; i++ {
_, err := ds.NewHost(&kolide.Host{
_, err := ds.NewHost(&fleet.Host{
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
SeenTime: time.Now(),
@ -459,30 +459,30 @@ func setupLabelSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.LabelSpec
require.Nil(t, err)
}
expectedSpecs := []*kolide.LabelSpec{
&kolide.LabelSpec{
expectedSpecs := []*fleet.LabelSpec{
&fleet.LabelSpec{
Name: "foo",
Query: "select * from foo",
Description: "foo description",
Platform: "darwin",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "bar",
Query: "select * from bar",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "bing",
Query: "select * from bing",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "All Hosts",
Query: "SELECT 1",
LabelType: kolide.LabelTypeBuiltIn,
LabelMembershipType: kolide.LabelMembershipTypeManual,
LabelType: fleet.LabelTypeBuiltIn,
LabelMembershipType: fleet.LabelMembershipTypeManual,
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "Manual Label",
LabelMembershipType: kolide.LabelMembershipTypeManual,
LabelMembershipType: fleet.LabelMembershipTypeManual,
Hosts: []string{
"1", "2", "3", "4",
},
@ -494,7 +494,7 @@ func setupLabelSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.LabelSpec
return expectedSpecs
}
func testGetLabelSpec(t *testing.T, ds kolide.Datastore) {
func testGetLabelSpec(t *testing.T, ds fleet.Datastore) {
expectedSpecs := setupLabelSpecsTest(t, ds)
for _, s := range expectedSpecs {
@ -504,7 +504,7 @@ func testGetLabelSpec(t *testing.T, ds kolide.Datastore) {
}
}
func testApplyLabelSpecsRoundtrip(t *testing.T, ds kolide.Datastore) {
func testApplyLabelSpecsRoundtrip(t *testing.T, ds fleet.Datastore) {
expectedSpecs := setupLabelSpecsTest(t, ds)
specs, err := ds.GetLabelSpecs()
@ -519,7 +519,7 @@ func testApplyLabelSpecsRoundtrip(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, expectedSpecs, specs)
}
func testLabelIDsByName(t *testing.T, ds kolide.Datastore) {
func testLabelIDsByName(t *testing.T, ds fleet.Datastore) {
setupLabelSpecsTest(t, ds)
labels, err := ds.LabelIDsByName([]string{"foo", "bar", "bing"})
@ -528,8 +528,8 @@ func testLabelIDsByName(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, []uint{1, 2, 3}, labels)
}
func testSaveLabel(t *testing.T, db kolide.Datastore) {
label := &kolide.Label{
func testSaveLabel(t *testing.T, db fleet.Datastore) {
label := &fleet.Label{
Name: "my label",
Description: "a label",
Query: "select 1 from processes;",

View File

@ -3,12 +3,12 @@ package datastore
import (
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testMigrationStatus(t *testing.T, ds kolide.Datastore) {
func testMigrationStatus(t *testing.T, ds fleet.Datastore) {
if ds.Name() == "inmem" {
t.Skip("inmem is being deprecated, test skipped")
}
@ -17,17 +17,17 @@ func testMigrationStatus(t *testing.T, ds kolide.Datastore) {
status, err := ds.MigrationStatus()
require.Nil(t, err)
assert.EqualValues(t, kolide.NoMigrationsCompleted, status)
assert.EqualValues(t, fleet.NoMigrationsCompleted, status)
require.Nil(t, ds.MigrateTables())
status, err = ds.MigrationStatus()
require.Nil(t, err)
assert.EqualValues(t, kolide.SomeMigrationsCompleted, status)
assert.EqualValues(t, fleet.SomeMigrationsCompleted, status)
require.Nil(t, ds.MigrateData())
status, err = ds.MigrationStatus()
require.Nil(t, err)
assert.EqualValues(t, kolide.AllMigrationsCompleted, status)
assert.EqualValues(t, fleet.AllMigrationsCompleted, status)
}

View File

@ -4,14 +4,14 @@ import (
"testing"
"github.com/WatchBeam/clock"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testDeletePack(t *testing.T, ds kolide.Datastore) {
func testDeletePack(t *testing.T, ds fleet.Datastore) {
pack := test.NewPack(t, ds, "foo")
assert.NotEqual(t, uint(0), pack.ID)
@ -26,8 +26,8 @@ func testDeletePack(t *testing.T, ds kolide.Datastore) {
assert.NotNil(t, err)
}
func testNewPack(t *testing.T, ds kolide.Datastore) {
pack := &kolide.Pack{
func testNewPack(t *testing.T, ds fleet.Datastore) {
pack := &fleet.Pack{
Name: "foo",
}
@ -40,7 +40,7 @@ func testNewPack(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, "foo", pack.Name)
}
func testGetPackByName(t *testing.T, ds kolide.Datastore) {
func testGetPackByName(t *testing.T, ds fleet.Datastore) {
pack := test.NewPack(t, ds, "foo")
assert.NotEqual(t, uint(0), pack.ID)
@ -57,59 +57,59 @@ func testGetPackByName(t *testing.T, ds kolide.Datastore) {
}
func testListPacks(t *testing.T, ds kolide.Datastore) {
p1 := &kolide.PackSpec{
func testListPacks(t *testing.T, ds fleet.Datastore) {
p1 := &fleet.PackSpec{
ID: 1,
Name: "foo_pack",
}
p2 := &kolide.PackSpec{
p2 := &fleet.PackSpec{
ID: 2,
Name: "bar_pack",
}
err := ds.ApplyPackSpecs([]*kolide.PackSpec{p1})
err := ds.ApplyPackSpecs([]*fleet.PackSpec{p1})
require.Nil(t, err)
packs, err := ds.ListPacks(kolide.ListOptions{})
packs, err := ds.ListPacks(fleet.ListOptions{})
require.Nil(t, err)
assert.Len(t, packs, 1)
err = ds.ApplyPackSpecs([]*kolide.PackSpec{p1, p2})
err = ds.ApplyPackSpecs([]*fleet.PackSpec{p1, p2})
require.Nil(t, err)
packs, err = ds.ListPacks(kolide.ListOptions{})
packs, err = ds.ListPacks(fleet.ListOptions{})
require.Nil(t, err)
assert.Len(t, packs, 2)
}
func testListHostsInPack(t *testing.T, ds kolide.Datastore) {
func testListHostsInPack(t *testing.T, ds fleet.Datastore) {
if ds.Name() == "inmem" {
t.Skip("inmem is deprecated")
}
mockClock := clock.NewMockClock()
l1 := kolide.LabelSpec{
l1 := fleet.LabelSpec{
ID: 1,
Name: "foo",
}
err := ds.ApplyLabelSpecs([]*kolide.LabelSpec{&l1})
err := ds.ApplyLabelSpecs([]*fleet.LabelSpec{&l1})
require.Nil(t, err)
p1 := &kolide.PackSpec{
p1 := &fleet.PackSpec{
ID: 1,
Name: "foo_pack",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
l1.Name,
},
},
}
err = ds.ApplyPackSpecs([]*kolide.PackSpec{p1})
err = ds.ApplyPackSpecs([]*fleet.PackSpec{p1})
require.Nil(t, err)
h1 := test.NewHost(t, ds, "h1.local", "10.10.10.1", "1", "1", mockClock.Now())
hostsInPack, err := ds.ListHostsInPack(p1.ID, kolide.ListOptions{})
hostsInPack, err := ds.ListHostsInPack(p1.ID, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, hostsInPack, 0)
@ -120,11 +120,11 @@ func testListHostsInPack(t *testing.T, ds kolide.Datastore) {
)
require.Nil(t, err)
hostsInPack, err = ds.ListHostsInPack(p1.ID, kolide.ListOptions{})
hostsInPack, err = ds.ListHostsInPack(p1.ID, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, hostsInPack, 1)
explicitHostsInPack, err := ds.ListExplicitHostsInPack(p1.ID, kolide.ListOptions{})
explicitHostsInPack, err := ds.ListExplicitHostsInPack(p1.ID, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, explicitHostsInPack, 0)
@ -137,37 +137,37 @@ func testListHostsInPack(t *testing.T, ds kolide.Datastore) {
)
require.Nil(t, err)
hostsInPack, err = ds.ListHostsInPack(p1.ID, kolide.ListOptions{})
hostsInPack, err = ds.ListHostsInPack(p1.ID, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, hostsInPack, 2)
}
func testAddLabelToPackTwice(t *testing.T, ds kolide.Datastore) {
l1 := kolide.LabelSpec{
func testAddLabelToPackTwice(t *testing.T, ds fleet.Datastore) {
l1 := fleet.LabelSpec{
ID: 1,
Name: "l1",
Query: "select 1",
}
err := ds.ApplyLabelSpecs([]*kolide.LabelSpec{&l1})
err := ds.ApplyLabelSpecs([]*fleet.LabelSpec{&l1})
require.Nil(t, err)
p1 := &kolide.PackSpec{
p1 := &fleet.PackSpec{
ID: 1,
Name: "pack1",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
l1.Name,
l1.Name,
},
},
}
err = ds.ApplyPackSpecs([]*kolide.PackSpec{p1})
err = ds.ApplyPackSpecs([]*fleet.PackSpec{p1})
require.NotNil(t, err)
}
func setupPackSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.PackSpec {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
queries := []*kolide.Query{
func setupPackSpecsTest(t *testing.T, ds fleet.Datastore) []*fleet.PackSpec {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
queries := []*fleet.Query{
{Name: "foo", Description: "get the foos", Query: "select * from foo"},
{Name: "bar", Description: "do some bars", Query: "select baz from bar"},
}
@ -175,16 +175,16 @@ func setupPackSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.PackSpec {
err := ds.ApplyQueries(zwass.ID, queries)
require.Nil(t, err)
labels := []*kolide.LabelSpec{
&kolide.LabelSpec{
labels := []*fleet.LabelSpec{
&fleet.LabelSpec{
Name: "foo",
Query: "select * from foo",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "bar",
Query: "select * from bar",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "bing",
Query: "select * from bing",
},
@ -192,32 +192,32 @@ func setupPackSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.PackSpec {
err = ds.ApplyLabelSpecs(labels)
require.Nil(t, err)
expectedSpecs := []*kolide.PackSpec{
&kolide.PackSpec{
expectedSpecs := []*fleet.PackSpec{
&fleet.PackSpec{
ID: 1,
Name: "test_pack",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
"foo",
"bar",
"bing",
},
},
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: queries[0].Name,
Name: "q0",
Description: "test_foo",
Interval: 42,
},
kolide.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: queries[0].Name,
Name: "foo_snapshot",
Interval: 600,
Snapshot: ptr.Bool(true),
Denylist: ptr.Bool(false),
},
kolide.PackSpecQuery{
fleet.PackSpecQuery{
Name: "q2",
QueryName: queries[1].Name,
Interval: 600,
@ -229,31 +229,31 @@ func setupPackSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.PackSpec {
},
},
},
&kolide.PackSpec{
&fleet.PackSpec{
ID: 2,
Name: "test_pack_disabled",
Disabled: true,
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
"foo",
"bar",
"bing",
},
},
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: queries[0].Name,
Name: "q0",
Description: "test_foo",
Interval: 42,
},
kolide.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: queries[0].Name,
Name: "foo_snapshot",
Interval: 600,
Snapshot: ptr.Bool(true),
},
kolide.PackSpecQuery{
fleet.PackSpecQuery{
Name: "q2",
QueryName: queries[1].Name,
Interval: 600,
@ -271,7 +271,7 @@ func setupPackSpecsTest(t *testing.T, ds kolide.Datastore) []*kolide.PackSpec {
return expectedSpecs
}
func testApplyPackSpecRoundtrip(t *testing.T, ds kolide.Datastore) {
func testApplyPackSpecRoundtrip(t *testing.T, ds fleet.Datastore) {
expectedSpecs := setupPackSpecsTest(t, ds)
gotSpec, err := ds.GetPackSpecs()
@ -279,7 +279,7 @@ func testApplyPackSpecRoundtrip(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, expectedSpecs, gotSpec)
}
func testGetPackSpec(t *testing.T, ds kolide.Datastore) {
func testGetPackSpec(t *testing.T, ds fleet.Datastore) {
expectedSpecs := setupPackSpecsTest(t, ds)
for _, s := range expectedSpecs {
@ -289,17 +289,17 @@ func testGetPackSpec(t *testing.T, ds kolide.Datastore) {
}
}
func testApplyPackSpecMissingQueries(t *testing.T, ds kolide.Datastore) {
func testApplyPackSpecMissingQueries(t *testing.T, ds fleet.Datastore) {
// Do not define queries mentioned in spec
specs := []*kolide.PackSpec{
&kolide.PackSpec{
specs := []*fleet.PackSpec{
&fleet.PackSpec{
ID: 1,
Name: "test_pack",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{},
},
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: "bar",
Interval: 600,
},
@ -314,17 +314,17 @@ func testApplyPackSpecMissingQueries(t *testing.T, ds kolide.Datastore) {
}
}
func testApplyPackSpecMissingName(t *testing.T, ds kolide.Datastore) {
func testApplyPackSpecMissingName(t *testing.T, ds fleet.Datastore) {
setupPackSpecsTest(t, ds)
specs := []*kolide.PackSpec{
&kolide.PackSpec{
specs := []*fleet.PackSpec{
&fleet.PackSpec{
Name: "test2",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{},
},
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: "foo",
Interval: 600,
},
@ -340,17 +340,17 @@ func testApplyPackSpecMissingName(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, "foo", spec.Queries[0].Name)
}
func testListLabelsForPack(t *testing.T, ds kolide.Datastore) {
labelSpecs := []*kolide.LabelSpec{
&kolide.LabelSpec{
func testListLabelsForPack(t *testing.T, ds fleet.Datastore) {
labelSpecs := []*fleet.LabelSpec{
&fleet.LabelSpec{
Name: "foo",
Query: "select * from foo",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "bar",
Query: "select * from bar",
},
&kolide.LabelSpec{
&fleet.LabelSpec{
Name: "bing",
Query: "select * from bing",
},
@ -358,11 +358,11 @@ func testListLabelsForPack(t *testing.T, ds kolide.Datastore) {
err := ds.ApplyLabelSpecs(labelSpecs)
require.Nil(t, err)
specs := []*kolide.PackSpec{
&kolide.PackSpec{
specs := []*fleet.PackSpec{
&fleet.PackSpec{
ID: 1,
Name: "test_pack",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
"foo",
"bar",
@ -370,16 +370,16 @@ func testListLabelsForPack(t *testing.T, ds kolide.Datastore) {
},
},
},
&kolide.PackSpec{
&fleet.PackSpec{
ID: 2,
Name: "test 2",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
"bing",
},
},
},
&kolide.PackSpec{
&fleet.PackSpec{
ID: 3,
Name: "test 3",
},
@ -401,44 +401,44 @@ func testListLabelsForPack(t *testing.T, ds kolide.Datastore) {
assert.Len(t, labels, 0)
}
func testListPacksForHost(t *testing.T, ds kolide.Datastore) {
func testListPacksForHost(t *testing.T, ds fleet.Datastore) {
if ds.Name() == "inmem" {
t.Skip("inmem is deprecated")
}
mockClock := clock.NewMockClock()
l1 := &kolide.LabelSpec{
l1 := &fleet.LabelSpec{
ID: 1,
Name: "foo",
}
l2 := &kolide.LabelSpec{
l2 := &fleet.LabelSpec{
ID: 2,
Name: "bar",
}
err := ds.ApplyLabelSpecs([]*kolide.LabelSpec{l1, l2})
err := ds.ApplyLabelSpecs([]*fleet.LabelSpec{l1, l2})
require.Nil(t, err)
p1 := &kolide.PackSpec{
p1 := &fleet.PackSpec{
ID: 1,
Name: "foo_pack",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
l1.Name,
l2.Name,
},
},
}
p2 := &kolide.PackSpec{
p2 := &fleet.PackSpec{
ID: 2,
Name: "shmoo_pack",
Targets: kolide.PackSpecTargets{
Targets: fleet.PackSpecTargets{
Labels: []string{
l2.Name,
},
},
}
err = ds.ApplyPackSpecs([]*kolide.PackSpec{p1, p2})
err = ds.ApplyPackSpecs([]*fleet.PackSpec{p1, p2})
require.Nil(t, err)
h1 := test.NewHost(t, ds, "h1.local", "10.10.10.1", "1", "1", mockClock.Now())

View File

@ -4,11 +4,11 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
)
func testPasswordResetRequests(t *testing.T, db kolide.Datastore) {
func testPasswordResetRequests(t *testing.T, db fleet.Datastore) {
createTestUsers(t, db)
now := time.Now().UTC()
tomorrow := now.Add(time.Hour * 24)
@ -21,7 +21,7 @@ func testPasswordResetRequests(t *testing.T, db kolide.Datastore) {
}
for _, tt := range passwordResetTests {
r := &kolide.PasswordResetRequest{
r := &fleet.PasswordResetRequest{
UserID: tt.userID,
ExpiresAt: tt.expires,
Token: tt.token,

View File

@ -5,18 +5,18 @@ import (
"sort"
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testApplyQueries(t *testing.T, ds kolide.Datastore) {
func testApplyQueries(t *testing.T, ds fleet.Datastore) {
test.AddAllHostsLabel(t, ds)
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
groob := test.NewUser(t, ds, "Victor", "groob", "victor@kolide.co", true)
expectedQueries := []*kolide.Query{
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
groob := test.NewUser(t, ds, "Victor", "groob", "victor@fleet.co", true)
expectedQueries := []*fleet.Query{
{Name: "foo", Description: "get the foos", Query: "select * from foo", ObserverCanRun: true},
{Name: "bar", Description: "do some bars", Query: "select baz from bar"},
}
@ -25,7 +25,7 @@ func testApplyQueries(t *testing.T, ds kolide.Datastore) {
err := ds.ApplyQueries(zwass.ID, expectedQueries)
require.Nil(t, err)
queries, err := ds.ListQueries(kolide.ListOptions{})
queries, err := ds.ListQueries(fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, queries, len(expectedQueries))
for i, q := range queries {
@ -43,7 +43,7 @@ func testApplyQueries(t *testing.T, ds kolide.Datastore) {
err = ds.ApplyQueries(groob.ID, expectedQueries)
require.Nil(t, err)
queries, err = ds.ListQueries(kolide.ListOptions{})
queries, err = ds.ListQueries(fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, queries, len(expectedQueries))
for i, q := range queries {
@ -56,12 +56,12 @@ func testApplyQueries(t *testing.T, ds kolide.Datastore) {
// Zach adds a third query (but does not re-apply the others)
expectedQueries = append(expectedQueries,
&kolide.Query{Name: "trouble", Description: "Look out!", Query: "select * from time"},
&fleet.Query{Name: "trouble", Description: "Look out!", Query: "select * from time"},
)
err = ds.ApplyQueries(zwass.ID, []*kolide.Query{expectedQueries[2]})
err = ds.ApplyQueries(zwass.ID, []*fleet.Query{expectedQueries[2]})
require.Nil(t, err)
queries, err = ds.ListQueries(kolide.ListOptions{})
queries, err = ds.ListQueries(fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, queries, len(expectedQueries))
for i, q := range queries {
@ -75,10 +75,10 @@ func testApplyQueries(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, &zwass.ID, queries[2].AuthorID)
}
func testDeleteQuery(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
func testDeleteQuery(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
query := &kolide.Query{
query := &fleet.Query{
Name: "foo",
Query: "bar",
AuthorID: &user.ID,
@ -96,8 +96,8 @@ func testDeleteQuery(t *testing.T, ds kolide.Datastore) {
assert.NotNil(t, err)
}
func testGetQueryByName(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
func testGetQueryByName(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
test.NewQuery(t, ds, "q1", "select * from time", user.ID, true)
actual, err := ds.QueryByName("q1")
require.Nil(t, err)
@ -106,18 +106,18 @@ func testGetQueryByName(t *testing.T, ds kolide.Datastore) {
actual, err = ds.QueryByName("xxx")
assert.Error(t, err)
assert.True(t, kolide.IsNotFound(err))
assert.True(t, fleet.IsNotFound(err))
}
func testDeleteQueries(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
func testDeleteQueries(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
q1 := test.NewQuery(t, ds, "q1", "select * from time", user.ID, true)
q2 := test.NewQuery(t, ds, "q2", "select * from processes", user.ID, true)
q3 := test.NewQuery(t, ds, "q3", "select 1", user.ID, true)
q4 := test.NewQuery(t, ds, "q4", "select * from osquery_info", user.ID, true)
queries, err := ds.ListQueries(kolide.ListOptions{})
queries, err := ds.ListQueries(fleet.ListOptions{})
require.Nil(t, err)
assert.Len(t, queries, 4)
@ -125,7 +125,7 @@ func testDeleteQueries(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
assert.Equal(t, uint(2), deleted)
queries, err = ds.ListQueries(kolide.ListOptions{})
queries, err = ds.ListQueries(fleet.ListOptions{})
require.Nil(t, err)
assert.Len(t, queries, 2)
@ -133,7 +133,7 @@ func testDeleteQueries(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
assert.Equal(t, uint(1), deleted)
queries, err = ds.ListQueries(kolide.ListOptions{})
queries, err = ds.ListQueries(fleet.ListOptions{})
require.Nil(t, err)
assert.Len(t, queries, 1)
@ -141,16 +141,16 @@ func testDeleteQueries(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
assert.Equal(t, uint(1), deleted)
queries, err = ds.ListQueries(kolide.ListOptions{})
queries, err = ds.ListQueries(fleet.ListOptions{})
require.Nil(t, err)
assert.Len(t, queries, 0)
}
func testSaveQuery(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
func testSaveQuery(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
query := &kolide.Query{
query := &fleet.Query{
Name: "foo",
Query: "bar",
AuthorID: &user.ID,
@ -174,11 +174,11 @@ func testSaveQuery(t *testing.T, ds kolide.Datastore) {
assert.True(t, queryVerify.ObserverCanRun)
}
func testListQuery(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
func testListQuery(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
for i := 0; i < 10; i++ {
_, err := ds.NewQuery(&kolide.Query{
_, err := ds.NewQuery(&fleet.Query{
Name: fmt.Sprintf("name%02d", i),
Query: fmt.Sprintf("query%02d", i),
Saved: true,
@ -188,7 +188,7 @@ func testListQuery(t *testing.T, ds kolide.Datastore) {
}
// One unsaved query should not be returned
_, err := ds.NewQuery(&kolide.Query{
_, err := ds.NewQuery(&fleet.Query{
Name: "unsaved",
Query: "select * from time",
Saved: false,
@ -196,25 +196,25 @@ func testListQuery(t *testing.T, ds kolide.Datastore) {
})
require.Nil(t, err)
opts := kolide.ListOptions{}
opts := fleet.ListOptions{}
results, err := ds.ListQueries(opts)
assert.Nil(t, err)
assert.Equal(t, 10, len(results))
}
func testLoadPacksForQueries(t *testing.T, ds kolide.Datastore) {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
queries := []*kolide.Query{
func testLoadPacksForQueries(t *testing.T, ds fleet.Datastore) {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
queries := []*fleet.Query{
{Name: "q1", Query: "select * from time"},
{Name: "q2", Query: "select * from osquery_info"},
}
err := ds.ApplyQueries(zwass.ID, queries)
require.Nil(t, err)
specs := []*kolide.PackSpec{
&kolide.PackSpec{Name: "p1"},
&kolide.PackSpec{Name: "p2"},
&kolide.PackSpec{Name: "p3"},
specs := []*fleet.PackSpec{
&fleet.PackSpec{Name: "p1"},
&fleet.PackSpec{Name: "p2"},
&fleet.PackSpec{Name: "p3"},
}
err = ds.ApplyPackSpecs(specs)
require.Nil(t, err)
@ -227,11 +227,11 @@ func testLoadPacksForQueries(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
assert.Empty(t, q1.Packs)
specs = []*kolide.PackSpec{
&kolide.PackSpec{
specs = []*fleet.PackSpec{
&fleet.PackSpec{
Name: "p2",
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
Name: "q0",
QueryName: queries[0].Name,
Interval: 60,
@ -252,20 +252,20 @@ func testLoadPacksForQueries(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
assert.Empty(t, q1.Packs)
specs = []*kolide.PackSpec{
&kolide.PackSpec{
specs = []*fleet.PackSpec{
&fleet.PackSpec{
Name: "p1",
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: queries[1].Name,
Interval: 60,
},
},
},
&kolide.PackSpec{
&fleet.PackSpec{
Name: "p3",
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
QueryName: queries[1].Name,
Interval: 60,
},
@ -289,16 +289,16 @@ func testLoadPacksForQueries(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, "p3", q1.Packs[1].Name)
}
specs = []*kolide.PackSpec{
&kolide.PackSpec{
specs = []*fleet.PackSpec{
&fleet.PackSpec{
Name: "p3",
Queries: []kolide.PackSpecQuery{
kolide.PackSpecQuery{
Queries: []fleet.PackSpecQuery{
fleet.PackSpecQuery{
Name: "q0",
QueryName: queries[0].Name,
Interval: 60,
},
kolide.PackSpecQuery{
fleet.PackSpecQuery{
Name: "q1",
QueryName: queries[1].Name,
Interval: 60,
@ -326,9 +326,9 @@ func testLoadPacksForQueries(t *testing.T, ds kolide.Datastore) {
}
}
func testDuplicateNewQuery(t *testing.T, ds kolide.Datastore) {
user := test.NewUser(t, ds, "Mike Arpaia", "marpaia", "mike@kolide.co", true)
q1, err := ds.NewQuery(&kolide.Query{
func testDuplicateNewQuery(t *testing.T, ds fleet.Datastore) {
user := test.NewUser(t, ds, "Mike Arpaia", "marpaia", "mike@fleet.co", true)
q1, err := ds.NewQuery(&fleet.Query{
Name: "foo",
Query: "select * from time;",
AuthorID: &user.ID,
@ -336,7 +336,7 @@ func testDuplicateNewQuery(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
assert.NotZero(t, q1.ID)
_, err = ds.NewQuery(&kolide.Query{
_, err = ds.NewQuery(&fleet.Query{
Name: "foo",
Query: "select * from osquery_info;",
})

View File

@ -3,27 +3,27 @@ package datastore
import (
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testListScheduledQueriesInPack(t *testing.T, ds kolide.Datastore) {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
queries := []*kolide.Query{
func testListScheduledQueriesInPack(t *testing.T, ds fleet.Datastore) {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
queries := []*fleet.Query{
{Name: "foo", Description: "get the foos", Query: "select * from foo"},
{Name: "bar", Description: "do some bars", Query: "select baz from bar"},
}
err := ds.ApplyQueries(zwass.ID, queries)
require.Nil(t, err)
specs := []*kolide.PackSpec{
specs := []*fleet.PackSpec{
{
Name: "baz",
Targets: kolide.PackSpecTargets{Labels: []string{}},
Queries: []kolide.PackSpecQuery{
Targets: fleet.PackSpecTargets{Labels: []string{}},
Queries: []fleet.PackSpecQuery{
{
QueryName: queries[0].Name,
Description: "test_foo",
@ -35,18 +35,18 @@ func testListScheduledQueriesInPack(t *testing.T, ds kolide.Datastore) {
err = ds.ApplyPackSpecs(specs)
require.Nil(t, err)
gotQueries, err := ds.ListScheduledQueriesInPack(1, kolide.ListOptions{})
gotQueries, err := ds.ListScheduledQueriesInPack(1, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, gotQueries, 1)
assert.Equal(t, uint(60), gotQueries[0].Interval)
assert.Equal(t, "test_foo", gotQueries[0].Description)
assert.Equal(t, "select * from foo", gotQueries[0].Query)
specs = []*kolide.PackSpec{
specs = []*fleet.PackSpec{
{
Name: "baz",
Targets: kolide.PackSpecTargets{Labels: []string{}},
Queries: []kolide.PackSpecQuery{
Targets: fleet.PackSpecTargets{Labels: []string{}},
Queries: []fleet.PackSpecQuery{
{
QueryName: queries[0].Name,
Description: "test_foo",
@ -71,17 +71,17 @@ func testListScheduledQueriesInPack(t *testing.T, ds kolide.Datastore) {
err = ds.ApplyPackSpecs(specs)
require.Nil(t, err)
gotQueries, err = ds.ListScheduledQueriesInPack(1, kolide.ListOptions{})
gotQueries, err = ds.ListScheduledQueriesInPack(1, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, gotQueries, 3)
}
func testNewScheduledQuery(t *testing.T, ds kolide.Datastore) {
u1 := test.NewUser(t, ds, "Admin", "admin", "admin@kolide.co", true)
func testNewScheduledQuery(t *testing.T, ds fleet.Datastore) {
u1 := test.NewUser(t, ds, "Admin", "admin", "admin@fleet.co", true)
q1 := test.NewQuery(t, ds, "foo", "select * from time;", u1.ID, true)
p1 := test.NewPack(t, ds, "baz")
query, err := ds.NewScheduledQuery(&kolide.ScheduledQuery{
query, err := ds.NewScheduledQuery(&fleet.ScheduledQuery{
PackID: p1.ID,
QueryID: q1.ID,
Name: "foo-scheduled",
@ -92,8 +92,8 @@ func testNewScheduledQuery(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, "select * from time;", query.Query)
}
func testScheduledQuery(t *testing.T, ds kolide.Datastore) {
u1 := test.NewUser(t, ds, "Admin", "admin", "admin@kolide.co", true)
func testScheduledQuery(t *testing.T, ds fleet.Datastore) {
u1 := test.NewUser(t, ds, "Admin", "admin", "admin@fleet.co", true)
q1 := test.NewQuery(t, ds, "foo", "select * from time;", u1.ID, true)
p1 := test.NewPack(t, ds, "baz")
sq1 := test.NewScheduledQuery(t, ds, p1.ID, q1.ID, 60, false, false, "")
@ -116,8 +116,8 @@ func testScheduledQuery(t *testing.T, ds kolide.Datastore) {
assert.False(t, *query.Denylist)
}
func testDeleteScheduledQuery(t *testing.T, ds kolide.Datastore) {
u1 := test.NewUser(t, ds, "Admin", "admin", "admin@kolide.co", true)
func testDeleteScheduledQuery(t *testing.T, ds fleet.Datastore) {
u1 := test.NewUser(t, ds, "Admin", "admin", "admin@fleet.co", true)
q1 := test.NewQuery(t, ds, "foo", "select * from time;", u1.ID, true)
p1 := test.NewPack(t, ds, "baz")
sq1 := test.NewScheduledQuery(t, ds, p1.ID, q1.ID, 60, false, false, "")
@ -133,20 +133,20 @@ func testDeleteScheduledQuery(t *testing.T, ds kolide.Datastore) {
require.NotNil(t, err)
}
func testCascadingDeletionOfQueries(t *testing.T, ds kolide.Datastore) {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@kolide.co", true)
queries := []*kolide.Query{
func testCascadingDeletionOfQueries(t *testing.T, ds fleet.Datastore) {
zwass := test.NewUser(t, ds, "Zach", "zwass", "zwass@fleet.co", true)
queries := []*fleet.Query{
{Name: "foo", Description: "get the foos", Query: "select * from foo"},
{Name: "bar", Description: "do some bars", Query: "select baz from bar"},
}
err := ds.ApplyQueries(zwass.ID, queries)
require.Nil(t, err)
specs := []*kolide.PackSpec{
specs := []*fleet.PackSpec{
{
Name: "baz",
Targets: kolide.PackSpecTargets{Labels: []string{}},
Queries: []kolide.PackSpecQuery{
Targets: fleet.PackSpecTargets{Labels: []string{}},
Queries: []fleet.PackSpecQuery{
{
QueryName: queries[0].Name,
Description: "test_foo",
@ -170,14 +170,14 @@ func testCascadingDeletionOfQueries(t *testing.T, ds kolide.Datastore) {
err = ds.ApplyPackSpecs(specs)
require.Nil(t, err)
gotQueries, err := ds.ListScheduledQueriesInPack(1, kolide.ListOptions{})
gotQueries, err := ds.ListScheduledQueriesInPack(1, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, gotQueries, 3)
err = ds.DeleteQuery(queries[1].Name)
require.Nil(t, err)
gotQueries, err = ds.ListScheduledQueriesInPack(1, kolide.ListOptions{})
gotQueries, err = ds.ListScheduledQueriesInPack(1, fleet.ListOptions{})
require.Nil(t, err)
require.Len(t, gotQueries, 1)

View File

@ -4,27 +4,27 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testSaveHostSoftware(t *testing.T, ds kolide.Datastore) {
func testSaveHostSoftware(t *testing.T, ds fleet.Datastore) {
host1 := test.NewHost(t, ds, "host1", "", "host1key", "host1uuid", time.Now())
host2 := test.NewHost(t, ds, "host2", "", "host2key", "host2uuid", time.Now())
soft1 := kolide.HostSoftware{
soft1 := fleet.HostSoftware{
Modified: true,
Software: []kolide.Software{
Software: []fleet.Software{
{Name: "foo", Version: "0.0.1", Source: "chrome_extensions"},
{Name: "foo", Version: "0.0.3", Source: "chrome_extensions"},
},
}
host1.HostSoftware = soft1
soft2 := kolide.HostSoftware{
soft2 := fleet.HostSoftware{
Modified: true,
Software: []kolide.Software{
Software: []fleet.Software{
{Name: "foo", Version: "0.0.2", Source: "chrome_extensions"},
{Name: "foo", Version: "0.0.3", Source: "chrome_extensions"},
{Name: "bar", Version: "0.0.3", Source: "deb_packages"},
@ -47,18 +47,18 @@ func testSaveHostSoftware(t *testing.T, ds kolide.Datastore) {
assert.False(t, host2.HostSoftware.Modified)
test.ElementsMatchSkipID(t, soft2.Software, host2.HostSoftware.Software)
soft1 = kolide.HostSoftware{
soft1 = fleet.HostSoftware{
Modified: true,
Software: []kolide.Software{
Software: []fleet.Software{
{Name: "foo", Version: "0.0.1", Source: "chrome_extensions"},
{Name: "foo", Version: "0.0.3", Source: "chrome_extensions"},
{Name: "towel", Version: "42.0.0", Source: "apps"},
},
}
host1.HostSoftware = soft1
soft2 = kolide.HostSoftware{
soft2 = fleet.HostSoftware{
Modified: true,
Software: []kolide.Software{},
Software: []fleet.Software{},
}
host2.HostSoftware = soft2

View File

@ -6,27 +6,27 @@ import (
"time"
"github.com/WatchBeam/clock"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testCountHostsInTargets(t *testing.T, ds kolide.Datastore) {
func testCountHostsInTargets(t *testing.T, ds fleet.Datastore) {
if ds.Name() == "inmem" {
t.Skip("inmem is being deprecated, test skipped")
}
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
mockClock := clock.NewMockClock()
hostCount := 0
initHost := func(seenTime time.Time, distributedInterval uint, configTLSRefresh uint, teamID *uint) *kolide.Host {
initHost := func(seenTime time.Time, distributedInterval uint, configTLSRefresh uint, teamID *uint) *fleet.Host {
hostCount += 1
h, err := ds.NewHost(&kolide.Host{
h, err := ds.NewHost(&fleet.Host{
OsqueryHostID: strconv.Itoa(hostCount),
DetailUpdateTime: mockClock.Now(),
LabelUpdateTime: mockClock.Now(),
@ -41,11 +41,11 @@ func testCountHostsInTargets(t *testing.T, ds kolide.Datastore) {
return h
}
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
team2, err := ds.NewTeam(&kolide.Team{Name: "team2"})
team2, err := ds.NewTeam(&fleet.Team{Name: "team2"})
require.NoError(t, err)
team3, err := ds.NewTeam(&kolide.Team{Name: "team3"})
team3, err := ds.NewTeam(&fleet.Team{Name: "team3"})
require.NoError(t, err)
h1 := initHost(mockClock.Now().Add(-1*time.Second), 10, 60, &team1.ID)
@ -56,92 +56,92 @@ func testCountHostsInTargets(t *testing.T, ds kolide.Datastore) {
const thirtyDaysAndAMinuteAgo = -1 * (30*24*60 + 1)
h6 := initHost(mockClock.Now().Add(thirtyDaysAndAMinuteAgo*time.Minute), 3600, 3600, nil)
l1 := kolide.LabelSpec{
l1 := fleet.LabelSpec{
ID: 1,
Name: "label foo",
Query: "query foo",
}
l2 := kolide.LabelSpec{
l2 := fleet.LabelSpec{
ID: 2,
Name: "label bar",
Query: "query bar",
}
require.NoError(t, ds.ApplyLabelSpecs([]*kolide.LabelSpec{&l1, &l2}))
require.NoError(t, ds.ApplyLabelSpecs([]*fleet.LabelSpec{&l1, &l2}))
for _, h := range []*kolide.Host{h1, h2, h3, h6} {
for _, h := range []*fleet.Host{h1, h2, h3, h6} {
err = ds.RecordLabelQueryExecutions(h, map[uint]bool{l1.ID: true}, mockClock.Now())
assert.Nil(t, err)
}
for _, h := range []*kolide.Host{h3, h4, h5} {
for _, h := range []*fleet.Host{h3, h4, h5} {
err = ds.RecordLabelQueryExecutions(h, map[uint]bool{l2.ID: true}, mockClock.Now())
assert.Nil(t, err)
}
metrics, err := ds.CountHostsInTargets(filter, kolide.HostTargets{LabelIDs: []uint{l1.ID, l2.ID}}, mockClock.Now())
metrics, err := ds.CountHostsInTargets(filter, fleet.HostTargets{LabelIDs: []uint{l1.ID, l2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(6), metrics.TotalHosts)
assert.Equal(t, uint(2), metrics.OfflineHosts)
assert.Equal(t, uint(3), metrics.OnlineHosts)
assert.Equal(t, uint(1), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h1.ID, h2.ID}, LabelIDs: []uint{l1.ID, l2.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h1.ID, h2.ID}, LabelIDs: []uint{l1.ID, l2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(6), metrics.TotalHosts)
assert.Equal(t, uint(2), metrics.OfflineHosts)
assert.Equal(t, uint(3), metrics.OnlineHosts)
assert.Equal(t, uint(1), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h1.ID, h2.ID}, LabelIDs: []uint{l1.ID, l2.ID}, TeamIDs: []uint{team1.ID, team2.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h1.ID, h2.ID}, LabelIDs: []uint{l1.ID, l2.ID}, TeamIDs: []uint{team1.ID, team2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(6), metrics.TotalHosts)
assert.Equal(t, uint(2), metrics.OfflineHosts)
assert.Equal(t, uint(3), metrics.OnlineHosts)
assert.Equal(t, uint(1), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h1.ID, h2.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h1.ID, h2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(2), metrics.TotalHosts)
assert.Equal(t, uint(1), metrics.OnlineHosts)
assert.Equal(t, uint(1), metrics.OfflineHosts)
assert.Equal(t, uint(0), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h1.ID, h2.ID}, TeamIDs: []uint{team2.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h1.ID, h2.ID}, TeamIDs: []uint{team2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(4), metrics.TotalHosts)
assert.Equal(t, uint(2), metrics.OnlineHosts)
assert.Equal(t, uint(2), metrics.OfflineHosts)
assert.Equal(t, uint(0), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l2.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(4), metrics.TotalHosts)
assert.Equal(t, uint(3), metrics.OnlineHosts)
assert.Equal(t, uint(1), metrics.OfflineHosts)
assert.Equal(t, uint(0), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(0), metrics.TotalHosts)
assert.Equal(t, uint(0), metrics.OnlineHosts)
assert.Equal(t, uint(0), metrics.OfflineHosts)
assert.Equal(t, uint(0), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{HostIDs: []uint{}, LabelIDs: []uint{}, TeamIDs: []uint{}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{HostIDs: []uint{}, LabelIDs: []uint{}, TeamIDs: []uint{}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(0), metrics.TotalHosts)
assert.Equal(t, uint(0), metrics.OnlineHosts)
assert.Equal(t, uint(0), metrics.OfflineHosts)
assert.Equal(t, uint(0), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{TeamIDs: []uint{team1.ID, team3.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{TeamIDs: []uint{team1.ID, team3.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(1), metrics.TotalHosts)
assert.Equal(t, uint(1), metrics.OnlineHosts)
assert.Equal(t, uint(0), metrics.OfflineHosts)
assert.Equal(t, uint(0), metrics.MissingInActionHosts)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{TeamIDs: []uint{team2.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{TeamIDs: []uint{team2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(3), metrics.TotalHosts)
assert.Equal(t, uint(1), metrics.OnlineHosts)
@ -150,7 +150,7 @@ func testCountHostsInTargets(t *testing.T, ds kolide.Datastore) {
// Advance clock so all hosts are offline
mockClock.AddTime(2 * time.Minute)
metrics, err = ds.CountHostsInTargets(filter, kolide.HostTargets{LabelIDs: []uint{l1.ID, l2.ID}}, mockClock.Now())
metrics, err = ds.CountHostsInTargets(filter, fleet.HostTargets{LabelIDs: []uint{l1.ID, l2.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, uint(6), metrics.TotalHosts)
assert.Equal(t, uint(0), metrics.OnlineHosts)
@ -159,7 +159,7 @@ func testCountHostsInTargets(t *testing.T, ds kolide.Datastore) {
}
func testHostStatus(t *testing.T, ds kolide.Datastore) {
func testHostStatus(t *testing.T, ds fleet.Datastore) {
test.AddAllHostsLabel(t, ds)
if ds.Name() == "inmem" {
@ -171,21 +171,21 @@ func testHostStatus(t *testing.T, ds kolide.Datastore) {
h, err := ds.EnrollHost("1", "key1", nil, 0)
require.Nil(t, err)
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
// Make host no longer appear new
mockClock.AddTime(36 * time.Hour)
expectOnline := kolide.TargetMetrics{TotalHosts: 1, OnlineHosts: 1}
expectOffline := kolide.TargetMetrics{TotalHosts: 1, OfflineHosts: 1}
expectMIA := kolide.TargetMetrics{TotalHosts: 1, MissingInActionHosts: 1}
expectOnline := fleet.TargetMetrics{TotalHosts: 1, OnlineHosts: 1}
expectOffline := fleet.TargetMetrics{TotalHosts: 1, OfflineHosts: 1}
expectMIA := fleet.TargetMetrics{TotalHosts: 1, MissingInActionHosts: 1}
var testCases = []struct {
seenTime time.Time
distributedInterval uint
configTLSRefresh uint
metrics kolide.TargetMetrics
metrics fleet.TargetMetrics
}{
{mockClock.Now().Add(-30 * time.Second), 10, 3600, expectOnline},
{mockClock.Now().Add(-45 * time.Second), 10, 3600, expectOffline},
@ -216,25 +216,25 @@ func testHostStatus(t *testing.T, ds kolide.Datastore) {
require.Nil(t, ds.MarkHostSeen(h, tt.seenTime))
// Verify status
metrics, err := ds.CountHostsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h.ID}}, mockClock.Now())
metrics, err := ds.CountHostsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h.ID}}, mockClock.Now())
require.Nil(t, err)
assert.Equal(t, tt.metrics, metrics)
})
}
}
func testHostIDsInTargets(t *testing.T, ds kolide.Datastore) {
func testHostIDsInTargets(t *testing.T, ds fleet.Datastore) {
if ds.Name() == "inmem" {
t.Skip("inmem is being deprecated, test skipped")
}
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
hostCount := 0
initHost := func() *kolide.Host {
initHost := func() *fleet.Host {
hostCount += 1
h, err := ds.NewHost(&kolide.Host{
h, err := ds.NewHost(&fleet.Host{
OsqueryHostID: strconv.Itoa(hostCount),
NodeKey: strconv.Itoa(hostCount),
DetailUpdateTime: time.Now(),
@ -252,54 +252,54 @@ func testHostIDsInTargets(t *testing.T, ds kolide.Datastore) {
h5 := initHost()
h6 := initHost()
l1 := kolide.LabelSpec{
l1 := fleet.LabelSpec{
ID: 1,
Name: "label foo",
Query: "query foo",
}
l2 := kolide.LabelSpec{
l2 := fleet.LabelSpec{
ID: 2,
Name: "label bar",
Query: "query bar",
}
err := ds.ApplyLabelSpecs([]*kolide.LabelSpec{&l1, &l2})
err := ds.ApplyLabelSpecs([]*fleet.LabelSpec{&l1, &l2})
require.Nil(t, err)
for _, h := range []*kolide.Host{h1, h2, h3, h6} {
for _, h := range []*fleet.Host{h1, h2, h3, h6} {
err = ds.RecordLabelQueryExecutions(h, map[uint]bool{l1.ID: true}, time.Now())
assert.Nil(t, err)
}
for _, h := range []*kolide.Host{h3, h4, h5} {
for _, h := range []*fleet.Host{h3, h4, h5} {
err = ds.RecordLabelQueryExecutions(h, map[uint]bool{l2.ID: true}, time.Now())
assert.Nil(t, err)
}
ids, err := ds.HostIDsInTargets(filter, kolide.HostTargets{LabelIDs: []uint{l1.ID, l2.ID}})
ids, err := ds.HostIDsInTargets(filter, fleet.HostTargets{LabelIDs: []uint{l1.ID, l2.ID}})
require.Nil(t, err)
assert.Equal(t, []uint{1, 2, 3, 4, 5, 6}, ids)
ids, err = ds.HostIDsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h1.ID}})
ids, err = ds.HostIDsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h1.ID}})
require.Nil(t, err)
assert.Equal(t, []uint{1}, ids)
ids, err = ds.HostIDsInTargets(filter, kolide.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l1.ID}})
ids, err = ds.HostIDsInTargets(filter, fleet.HostTargets{HostIDs: []uint{h1.ID}, LabelIDs: []uint{l1.ID}})
require.Nil(t, err)
assert.Equal(t, []uint{1, 2, 3, 6}, ids)
ids, err = ds.HostIDsInTargets(filter, kolide.HostTargets{HostIDs: []uint{4}, LabelIDs: []uint{l1.ID}})
ids, err = ds.HostIDsInTargets(filter, fleet.HostTargets{HostIDs: []uint{4}, LabelIDs: []uint{l1.ID}})
require.Nil(t, err)
assert.Equal(t, []uint{1, 2, 3, 4, 6}, ids)
ids, err = ds.HostIDsInTargets(filter, kolide.HostTargets{HostIDs: []uint{4}, LabelIDs: []uint{l2.ID}})
ids, err = ds.HostIDsInTargets(filter, fleet.HostTargets{HostIDs: []uint{4}, LabelIDs: []uint{l2.ID}})
require.Nil(t, err)
assert.Equal(t, []uint{3, 4, 5}, ids)
ids, err = ds.HostIDsInTargets(filter, kolide.HostTargets{HostIDs: []uint{}, LabelIDs: []uint{l2.ID}})
ids, err = ds.HostIDsInTargets(filter, fleet.HostTargets{HostIDs: []uint{}, LabelIDs: []uint{l2.ID}})
require.Nil(t, err)
assert.Equal(t, []uint{3, 4, 5}, ids)
ids, err = ds.HostIDsInTargets(filter, kolide.HostTargets{HostIDs: []uint{1, 6}, LabelIDs: []uint{l2.ID}})
ids, err = ds.HostIDsInTargets(filter, fleet.HostTargets{HostIDs: []uint{1, 6}, LabelIDs: []uint{l2.ID}})
require.Nil(t, err)
assert.Equal(t, []uint{1, 3, 4, 5, 6}, ids)
}

View File

@ -5,14 +5,14 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testTeamGetSetDelete(t *testing.T, ds kolide.Datastore) {
func testTeamGetSetDelete(t *testing.T, ds fleet.Datastore) {
var createTests = []struct {
name, description string
}{
@ -22,7 +22,7 @@ func testTeamGetSetDelete(t *testing.T, ds kolide.Datastore) {
for _, tt := range createTests {
t.Run("", func(t *testing.T) {
team, err := ds.NewTeam(&kolide.Team{
team, err := ds.NewTeam(&fleet.Team{
Name: tt.name,
Description: tt.description,
})
@ -48,21 +48,21 @@ func testTeamGetSetDelete(t *testing.T, ds kolide.Datastore) {
}
}
func testTeamUsers(t *testing.T, ds kolide.Datastore) {
func testTeamUsers(t *testing.T, ds fleet.Datastore) {
users := createTestUsers(t, ds)
user1 := kolide.User{Name: users[0].Name, Email: users[0].Email, ID: users[0].ID}
user2 := kolide.User{Name: users[1].Name, Email: users[1].Email, ID: users[1].ID}
user1 := fleet.User{Name: users[0].Name, Email: users[0].Email, ID: users[0].ID}
user2 := fleet.User{Name: users[1].Name, Email: users[1].Email, ID: users[1].ID}
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
team2, err := ds.NewTeam(&kolide.Team{Name: "team2"})
team2, err := ds.NewTeam(&fleet.Team{Name: "team2"})
require.NoError(t, err)
team1, err = ds.Team(team1.ID)
require.NoError(t, err)
assert.Len(t, team1.Users, 0)
team1Users := []kolide.TeamUser{
team1Users := []fleet.TeamUser{
{User: user1, Role: "maintainer"},
{User: user2, Role: "observer"},
}
@ -78,7 +78,7 @@ func testTeamUsers(t *testing.T, ds kolide.Datastore) {
require.NoError(t, err)
assert.Len(t, team2.Users, 0)
team1Users = []kolide.TeamUser{
team1Users = []fleet.TeamUser{
{User: user2, Role: "maintainer"},
}
team1.Users = team1Users
@ -88,7 +88,7 @@ func testTeamUsers(t *testing.T, ds kolide.Datastore) {
require.NoError(t, err)
assert.ElementsMatch(t, team1Users, team1.Users)
team2Users := []kolide.TeamUser{
team2Users := []fleet.TeamUser{
{User: user2, Role: "observer"},
}
team2.Users = team2Users
@ -104,17 +104,17 @@ func testTeamUsers(t *testing.T, ds kolide.Datastore) {
assert.ElementsMatch(t, team2Users, team2.Users)
}
func testTeamListTeams(t *testing.T, ds kolide.Datastore) {
func testTeamListTeams(t *testing.T, ds fleet.Datastore) {
users := createTestUsers(t, ds)
user1 := kolide.User{Name: users[0].Name, Email: users[0].Email, ID: users[0].ID, GlobalRole: ptr.String(kolide.RoleAdmin)}
user2 := kolide.User{Name: users[1].Name, Email: users[1].Email, ID: users[1].ID}
user1 := fleet.User{Name: users[0].Name, Email: users[0].Email, ID: users[0].ID, GlobalRole: ptr.String(fleet.RoleAdmin)}
user2 := fleet.User{Name: users[1].Name, Email: users[1].Email, ID: users[1].ID}
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
team2, err := ds.NewTeam(&kolide.Team{Name: "team2"})
team2, err := ds.NewTeam(&fleet.Team{Name: "team2"})
require.NoError(t, err)
teams, err := ds.ListTeams(kolide.TeamFilter{User: &user1}, kolide.ListOptions{})
teams, err := ds.ListTeams(fleet.TeamFilter{User: &user1}, fleet.ListOptions{})
require.NoError(t, err)
sort.Slice(teams, func(i, j int) bool { return teams[i].Name < teams[j].Name })
@ -132,20 +132,20 @@ func testTeamListTeams(t *testing.T, ds kolide.Datastore) {
require.NoError(t, ds.AddHostsToTeam(&team1.ID, []uint{host1.ID}))
require.NoError(t, ds.AddHostsToTeam(&team2.ID, []uint{host2.ID, host3.ID}))
team1.Users = []kolide.TeamUser{
team1.Users = []fleet.TeamUser{
{User: user1, Role: "maintainer"},
{User: user2, Role: "observer"},
}
team1, err = ds.SaveTeam(team1)
require.NoError(t, err)
team2.Users = []kolide.TeamUser{
team2.Users = []fleet.TeamUser{
{User: user1, Role: "maintainer"},
}
team1, err = ds.SaveTeam(team2)
require.NoError(t, err)
teams, err = ds.ListTeams(kolide.TeamFilter{User: &user1}, kolide.ListOptions{})
teams, err = ds.ListTeams(fleet.TeamFilter{User: &user1}, fleet.ListOptions{})
require.NoError(t, err)
sort.Slice(teams, func(i, j int) bool { return teams[i].Name < teams[j].Name })
@ -158,18 +158,18 @@ func testTeamListTeams(t *testing.T, ds kolide.Datastore) {
assert.Equal(t, 1, teams[1].UserCount)
}
func testTeamSearchTeams(t *testing.T, ds kolide.Datastore) {
team1, err := ds.NewTeam(&kolide.Team{Name: "team1"})
func testTeamSearchTeams(t *testing.T, ds fleet.Datastore) {
team1, err := ds.NewTeam(&fleet.Team{Name: "team1"})
require.NoError(t, err)
team2, err := ds.NewTeam(&kolide.Team{Name: "team2"})
team2, err := ds.NewTeam(&fleet.Team{Name: "team2"})
require.NoError(t, err)
team3, err := ds.NewTeam(&kolide.Team{Name: "foobar"})
team3, err := ds.NewTeam(&fleet.Team{Name: "foobar"})
require.NoError(t, err)
team4, err := ds.NewTeam(&kolide.Team{Name: "floobar"})
team4, err := ds.NewTeam(&fleet.Team{Name: "floobar"})
require.NoError(t, err)
user := &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)}
filter := kolide.TeamFilter{User: user}
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
filter := fleet.TeamFilter{User: user}
teams, err := ds.SearchTeams(filter, "")
require.NoError(t, err)

View File

@ -4,30 +4,30 @@ import (
"testing"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testUnicode(t *testing.T, ds kolide.Datastore) {
func testUnicode(t *testing.T, ds fleet.Datastore) {
if ds.Name() == "inmem" {
t.Skip("inmem is being deprecated, test skipped")
}
l1 := kolide.LabelSpec{
l1 := fleet.LabelSpec{
ID: 1,
Name: "測試",
Query: "query foo",
}
err := ds.ApplyLabelSpecs([]*kolide.LabelSpec{&l1})
err := ds.ApplyLabelSpecs([]*fleet.LabelSpec{&l1})
require.Nil(t, err)
label, err := ds.Label(l1.ID)
require.Nil(t, err)
assert.Equal(t, "測試", label.Name)
host, err := ds.NewHost(&kolide.Host{
host, err := ds.NewHost(&fleet.Host{
HostName: "🍌",
DetailUpdateTime: time.Now(),
LabelUpdateTime: time.Now(),
@ -39,7 +39,7 @@ func testUnicode(t *testing.T, ds kolide.Datastore) {
require.Nil(t, err)
assert.Equal(t, "🍌", host.HostName)
user, err := ds.NewUser(&kolide.User{Username: "🍱", Password: []byte{}})
user, err := ds.NewUser(&fleet.User{Username: "🍱", Password: []byte{}})
require.Nil(t, err)
user, err = ds.User(user.Username)

View File

@ -4,23 +4,23 @@ import (
"fmt"
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testCreateUser(t *testing.T, ds kolide.Datastore) {
func testCreateUser(t *testing.T, ds fleet.Datastore) {
var createTests = []struct {
username, password, email string
isAdmin, passwordReset, sso bool
}{
{"marpaia", "foobar", "mike@kolide.co", true, false, true},
{"jason", "foobar", "jason@kolide.co", true, false, false},
{"marpaia", "foobar", "mike@fleet.co", true, false, true},
{"jason", "foobar", "jason@fleet.co", true, false, false},
}
for _, tt := range createTests {
u := &kolide.User{
u := &fleet.User{
Username: tt.username,
Password: []byte(tt.password),
AdminForcedPasswordReset: tt.passwordReset,
@ -41,7 +41,7 @@ func testCreateUser(t *testing.T, ds kolide.Datastore) {
}
}
func testUserByID(t *testing.T, ds kolide.Datastore) {
func testUserByID(t *testing.T, ds fleet.Datastore) {
users := createTestUsers(t, ds)
for _, tt := range users {
returned, err := ds.UserByID(tt.ID)
@ -54,18 +54,18 @@ func testUserByID(t *testing.T, ds kolide.Datastore) {
assert.NotNil(t, err)
}
func createTestUsers(t *testing.T, ds kolide.Datastore) []*kolide.User {
func createTestUsers(t *testing.T, ds fleet.Datastore) []*fleet.User {
var createTests = []struct {
username, password, email string
isAdmin, passwordReset bool
}{
{"marpaia", "foobar", "mike@kolide.co", true, false},
{"jason", "foobar", "jason@kolide.co", false, false},
{"marpaia", "foobar", "mike@fleet.co", true, false},
{"jason", "foobar", "jason@fleet.co", false, false},
}
var users []*kolide.User
var users []*fleet.User
for _, tt := range createTests {
u := &kolide.User{
u := &fleet.User{
Username: tt.username,
Name: tt.username,
Password: []byte(tt.password),
@ -82,16 +82,16 @@ func createTestUsers(t *testing.T, ds kolide.Datastore) []*kolide.User {
return users
}
func testSaveUser(t *testing.T, ds kolide.Datastore) {
func testSaveUser(t *testing.T, ds fleet.Datastore) {
users := createTestUsers(t, ds)
testUserGlobalRole(t, ds, users)
testEmailAttribute(t, ds, users)
testPasswordAttribute(t, ds, users)
}
func testPasswordAttribute(t *testing.T, ds kolide.Datastore, users []*kolide.User) {
func testPasswordAttribute(t *testing.T, ds fleet.Datastore, users []*fleet.User) {
for _, user := range users {
randomText, err := kolide.RandomText(8) //GenerateRandomText(8)
randomText, err := fleet.RandomText(8) //GenerateRandomText(8)
assert.Nil(t, err)
user.Password = []byte(randomText)
err = ds.SaveUser(user)
@ -103,7 +103,7 @@ func testPasswordAttribute(t *testing.T, ds kolide.Datastore, users []*kolide.Us
}
}
func testEmailAttribute(t *testing.T, ds kolide.Datastore, users []*kolide.User) {
func testEmailAttribute(t *testing.T, ds fleet.Datastore, users []*fleet.User) {
for _, user := range users {
user.Email = fmt.Sprintf("test.%s", user.Email)
err := ds.SaveUser(user)
@ -115,7 +115,7 @@ func testEmailAttribute(t *testing.T, ds kolide.Datastore, users []*kolide.User)
}
}
func testUserGlobalRole(t *testing.T, ds kolide.Datastore, users []*kolide.User) {
func testUserGlobalRole(t *testing.T, ds fleet.Datastore, users []*fleet.User) {
for _, user := range users {
user.GlobalRole = ptr.String("admin")
err := ds.SaveUser(user)
@ -127,27 +127,27 @@ func testUserGlobalRole(t *testing.T, ds kolide.Datastore, users []*kolide.User)
}
}
func testListUsers(t *testing.T, ds kolide.Datastore) {
func testListUsers(t *testing.T, ds fleet.Datastore) {
createTestUsers(t, ds)
users, err := ds.ListUsers(kolide.UserListOptions{})
users, err := ds.ListUsers(fleet.UserListOptions{})
assert.NoError(t, err)
require.Len(t, users, 2)
users, err = ds.ListUsers(kolide.UserListOptions{ListOptions: kolide.ListOptions{MatchQuery: "jason"}})
users, err = ds.ListUsers(fleet.UserListOptions{ListOptions: fleet.ListOptions{MatchQuery: "jason"}})
assert.NoError(t, err)
require.Len(t, users, 1)
assert.Equal(t, "jason@kolide.co", users[0].Email)
assert.Equal(t, "jason@fleet.co", users[0].Email)
users, err = ds.ListUsers(kolide.UserListOptions{ListOptions: kolide.ListOptions{MatchQuery: "paia"}})
users, err = ds.ListUsers(fleet.UserListOptions{ListOptions: fleet.ListOptions{MatchQuery: "paia"}})
assert.NoError(t, err)
require.Len(t, users, 1)
assert.Equal(t, "mike@kolide.co", users[0].Email)
assert.Equal(t, "mike@fleet.co", users[0].Email)
}
func testUserTeams(t *testing.T, ds kolide.Datastore) {
func testUserTeams(t *testing.T, ds fleet.Datastore) {
for i := 0; i < 10; i++ {
_, err := ds.NewTeam(&kolide.Team{Name: fmt.Sprintf("%d", i)})
_, err := ds.NewTeam(&fleet.Team{Name: fmt.Sprintf("%d", i)})
require.NoError(t, err)
}
@ -157,9 +157,9 @@ func testUserTeams(t *testing.T, ds kolide.Datastore) {
assert.Len(t, users[1].Teams, 0)
// Add invalid team should fail
users[0].Teams = []kolide.UserTeam{
users[0].Teams = []fleet.UserTeam{
{
Team: kolide.Team{ID: 13},
Team: fleet.Team{ID: 13},
Role: "foobar",
},
}
@ -167,9 +167,9 @@ func testUserTeams(t *testing.T, ds kolide.Datastore) {
require.Error(t, err)
// Add valid team should succeed
users[0].Teams = []kolide.UserTeam{
users[0].Teams = []fleet.UserTeam{
{
Team: kolide.Team{ID: 3},
Team: fleet.Team{ID: 3},
Role: "foobar",
},
}
@ -177,8 +177,8 @@ func testUserTeams(t *testing.T, ds kolide.Datastore) {
require.NoError(t, err)
users, err = ds.ListUsers(
kolide.UserListOptions{
ListOptions: kolide.ListOptions{OrderKey: "name", OrderDirection: kolide.OrderDescending},
fleet.UserListOptions{
ListOptions: fleet.ListOptions{OrderKey: "name", OrderDirection: fleet.OrderDescending},
},
)
require.NoError(t, err)
@ -186,17 +186,17 @@ func testUserTeams(t *testing.T, ds kolide.Datastore) {
assert.Len(t, users[0].Teams, 1)
assert.Len(t, users[1].Teams, 0)
users[1].Teams = []kolide.UserTeam{
users[1].Teams = []fleet.UserTeam{
{
Team: kolide.Team{ID: 1},
Team: fleet.Team{ID: 1},
Role: "foobar",
},
{
Team: kolide.Team{ID: 2},
Team: fleet.Team{ID: 2},
Role: "foobar",
},
{
Team: kolide.Team{ID: 3},
Team: fleet.Team{ID: 3},
Role: "foobar",
},
}
@ -204,8 +204,8 @@ func testUserTeams(t *testing.T, ds kolide.Datastore) {
require.NoError(t, err)
users, err = ds.ListUsers(
kolide.UserListOptions{
ListOptions: kolide.ListOptions{OrderKey: "name", OrderDirection: kolide.OrderDescending},
fleet.UserListOptions{
ListOptions: fleet.ListOptions{OrderKey: "name", OrderDirection: fleet.OrderDescending},
},
)
require.NoError(t, err)
@ -214,13 +214,13 @@ func testUserTeams(t *testing.T, ds kolide.Datastore) {
assert.Len(t, users[1].Teams, 3)
// Clear teams
users[1].Teams = []kolide.UserTeam{}
users[1].Teams = []fleet.UserTeam{}
err = ds.SaveUser(users[1])
require.NoError(t, err)
users, err = ds.ListUsers(
kolide.UserListOptions{
ListOptions: kolide.ListOptions{OrderKey: "name", OrderDirection: kolide.OrderDescending},
fleet.UserListOptions{
ListOptions: fleet.ListOptions{OrderKey: "name", OrderDirection: fleet.OrderDescending},
},
)
require.NoError(t, err)
@ -229,26 +229,26 @@ func testUserTeams(t *testing.T, ds kolide.Datastore) {
assert.Len(t, users[1].Teams, 0)
}
func testUserCreateWithTeams(t *testing.T, ds kolide.Datastore) {
func testUserCreateWithTeams(t *testing.T, ds fleet.Datastore) {
for i := 0; i < 10; i++ {
_, err := ds.NewTeam(&kolide.Team{Name: fmt.Sprintf("%d", i)})
_, err := ds.NewTeam(&fleet.Team{Name: fmt.Sprintf("%d", i)})
require.NoError(t, err)
}
u := &kolide.User{
u := &fleet.User{
Username: "1",
Password: []byte("foo"),
Teams: []kolide.UserTeam{
Teams: []fleet.UserTeam{
{
Team: kolide.Team{ID: 6},
Team: fleet.Team{ID: 6},
Role: "admin",
},
{
Team: kolide.Team{ID: 3},
Team: fleet.Team{ID: 3},
Role: "observer",
},
{
Team: kolide.Team{ID: 9},
Team: fleet.Team{ID: 9},
Role: "maintainer",
},
},

View File

@ -1,8 +1,8 @@
package inmem
import "github.com/fleetdm/fleet/server/kolide"
import "github.com/fleetdm/fleet/server/fleet"
func (d *Datastore) NewAppConfig(info *kolide.AppConfig) (*kolide.AppConfig, error) {
func (d *Datastore) NewAppConfig(info *fleet.AppConfig) (*fleet.AppConfig, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -11,7 +11,7 @@ func (d *Datastore) NewAppConfig(info *kolide.AppConfig) (*kolide.AppConfig, err
return info, nil
}
func (d *Datastore) AppConfig() (*kolide.AppConfig, error) {
func (d *Datastore) AppConfig() (*fleet.AppConfig, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -22,7 +22,7 @@ func (d *Datastore) AppConfig() (*kolide.AppConfig, error) {
return nil, notFound("AppConfig")
}
func (d *Datastore) SaveAppConfig(info *kolide.AppConfig) error {
func (d *Datastore) SaveAppConfig(info *fleet.AppConfig) error {
d.mtx.Lock()
defer d.mtx.Unlock()

View File

@ -4,10 +4,10 @@ import (
"fmt"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func (d *Datastore) NewDistributedQueryCampaign(camp *kolide.DistributedQueryCampaign) (*kolide.DistributedQueryCampaign, error) {
func (d *Datastore) NewDistributedQueryCampaign(camp *fleet.DistributedQueryCampaign) (*fleet.DistributedQueryCampaign, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -17,7 +17,7 @@ func (d *Datastore) NewDistributedQueryCampaign(camp *kolide.DistributedQueryCam
return camp, nil
}
func (d *Datastore) DistributedQueryCampaign(id uint) (*kolide.DistributedQueryCampaign, error) {
func (d *Datastore) DistributedQueryCampaign(id uint) (*fleet.DistributedQueryCampaign, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -29,7 +29,7 @@ func (d *Datastore) DistributedQueryCampaign(id uint) (*kolide.DistributedQueryC
return &campaign, nil
}
func (d *Datastore) SaveDistributedQueryCampaign(camp *kolide.DistributedQueryCampaign) error {
func (d *Datastore) SaveDistributedQueryCampaign(camp *fleet.DistributedQueryCampaign) error {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -41,7 +41,7 @@ func (d *Datastore) SaveDistributedQueryCampaign(camp *kolide.DistributedQueryCa
return nil
}
func (d *Datastore) DistributedQueryCampaignTargetIDs(id uint) (*kolide.HostTargets, error) {
func (d *Datastore) DistributedQueryCampaignTargetIDs(id uint) (*fleet.HostTargets, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -49,9 +49,9 @@ func (d *Datastore) DistributedQueryCampaignTargetIDs(id uint) (*kolide.HostTarg
labelIDs := []uint{}
for _, target := range d.distributedQueryCampaignTargets {
if target.DistributedQueryCampaignID == id {
if target.Type == kolide.TargetHost {
if target.Type == fleet.TargetHost {
hostIDs = append(hostIDs, target.TargetID)
} else if target.Type == kolide.TargetLabel {
} else if target.Type == fleet.TargetLabel {
labelIDs = append(labelIDs, target.TargetID)
} else {
return nil, fmt.Errorf("invalid target type: %d", target.Type)
@ -59,10 +59,10 @@ func (d *Datastore) DistributedQueryCampaignTargetIDs(id uint) (*kolide.HostTarg
}
}
return &kolide.HostTargets{HostIDs: hostIDs, LabelIDs: labelIDs}, nil
return &fleet.HostTargets{HostIDs: hostIDs, LabelIDs: labelIDs}, nil
}
func (d *Datastore) NewDistributedQueryCampaignTarget(target *kolide.DistributedQueryCampaignTarget) (*kolide.DistributedQueryCampaignTarget, error) {
func (d *Datastore) NewDistributedQueryCampaignTarget(target *fleet.DistributedQueryCampaignTarget) (*fleet.DistributedQueryCampaignTarget, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -78,9 +78,9 @@ func (d *Datastore) CleanupDistributedQueryCampaigns(now time.Time) (expired uin
// First expire old waiting and running campaigns
for id, c := range d.distributedQueryCampaigns {
if (c.Status == kolide.QueryWaiting && c.CreatedAt.Before(now.Add(-1*time.Minute))) ||
(c.Status == kolide.QueryRunning && c.CreatedAt.Before(now.Add(-24*time.Hour))) {
c.Status = kolide.QueryComplete
if (c.Status == fleet.QueryWaiting && c.CreatedAt.Before(now.Add(-1*time.Minute))) ||
(c.Status == fleet.QueryRunning && c.CreatedAt.Before(now.Add(-24*time.Hour))) {
c.Status = fleet.QueryComplete
d.distributedQueryCampaigns[id] = c
expired++
}

View File

@ -7,11 +7,11 @@ import (
"strings"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/patrickmn/sortutil"
)
func (d *Datastore) NewHost(host *kolide.Host) (*kolide.Host, error) {
func (d *Datastore) NewHost(host *fleet.Host) (*fleet.Host, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -27,7 +27,7 @@ func (d *Datastore) NewHost(host *kolide.Host) (*kolide.Host, error) {
return host, nil
}
func (d *Datastore) SaveHost(host *kolide.Host) error {
func (d *Datastore) SaveHost(host *fleet.Host) error {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -48,7 +48,7 @@ func (d *Datastore) DeleteHost(hid uint) error {
return nil
}
func (d *Datastore) Host(id uint) (*kolide.Host, error) {
func (d *Datastore) Host(id uint) (*fleet.Host, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -60,7 +60,7 @@ func (d *Datastore) Host(id uint) (*kolide.Host, error) {
return host, nil
}
func (d *Datastore) ListHosts(filter kolide.TeamFilter, opt kolide.HostListOptions) ([]*kolide.Host, error) {
func (d *Datastore) ListHosts(filter fleet.TeamFilter, opt fleet.HostListOptions) ([]*fleet.Host, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -71,7 +71,7 @@ func (d *Datastore) ListHosts(filter kolide.TeamFilter, opt kolide.HostListOptio
}
sort.Ints(keys)
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
for _, k := range keys {
hosts = append(hosts, d.hosts[uint(k)])
}
@ -132,7 +132,7 @@ func (d *Datastore) ListHosts(filter kolide.TeamFilter, opt kolide.HostListOptio
return hosts, nil
}
func (d *Datastore) GenerateHostStatusStatistics(filter kolide.TeamFilter, now time.Time) (online, offline, mia, new uint, err error) {
func (d *Datastore) GenerateHostStatusStatistics(filter fleet.TeamFilter, now time.Time) (online, offline, mia, new uint, err error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -143,9 +143,9 @@ func (d *Datastore) GenerateHostStatusStatistics(filter kolide.TeamFilter, now t
status := host.Status(now)
switch status {
case kolide.StatusMIA:
case fleet.StatusMIA:
mia++
case kolide.StatusOffline:
case fleet.StatusOffline:
offline++
default:
online++
@ -155,7 +155,7 @@ func (d *Datastore) GenerateHostStatusStatistics(filter kolide.TeamFilter, now t
return online, offline, mia, new, nil
}
func (d *Datastore) EnrollHost(osQueryHostID, nodeKey string, teamID *uint, cooldown time.Duration) (*kolide.Host, error) {
func (d *Datastore) EnrollHost(osQueryHostID, nodeKey string, teamID *uint, cooldown time.Duration) (*fleet.Host, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -163,7 +163,7 @@ func (d *Datastore) EnrollHost(osQueryHostID, nodeKey string, teamID *uint, cool
return nil, errors.New("missing host identifier from osquery for host enrollment")
}
host := kolide.Host{
host := fleet.Host{
OsqueryHostID: osQueryHostID,
NodeKey: nodeKey,
DetailUpdateTime: time.Unix(0, 0).Add(24 * time.Hour),
@ -187,7 +187,7 @@ func (d *Datastore) EnrollHost(osQueryHostID, nodeKey string, teamID *uint, cool
return &host, nil
}
func (d *Datastore) AuthenticateHost(nodeKey string) (*kolide.Host, error) {
func (d *Datastore) AuthenticateHost(nodeKey string) (*fleet.Host, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -200,7 +200,7 @@ func (d *Datastore) AuthenticateHost(nodeKey string) (*kolide.Host, error) {
return nil, notFound("AuthenticateHost")
}
func (d *Datastore) MarkHostSeen(host *kolide.Host, t time.Time) error {
func (d *Datastore) MarkHostSeen(host *fleet.Host, t time.Time) error {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -214,13 +214,13 @@ func (d *Datastore) MarkHostSeen(host *kolide.Host, t time.Time) error {
return nil
}
func (d *Datastore) SearchHosts(filter kolide.TeamFilter, query string, omit ...uint) ([]*kolide.Host, error) {
func (d *Datastore) SearchHosts(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Host, error) {
omitLookup := map[uint]bool{}
for _, o := range omit {
omitLookup[o] = true
}
var results []*kolide.Host
var results []*fleet.Host
d.mtx.Lock()
defer d.mtx.Unlock()

View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/fleetdm/fleet/server/config"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/patrickmn/sortutil"
)
@ -17,28 +17,28 @@ type Datastore struct {
mtx sync.RWMutex
nextIDs map[interface{}]uint
users map[uint]*kolide.User
sessions map[uint]*kolide.Session
passwordResets map[uint]*kolide.PasswordResetRequest
invites map[uint]*kolide.Invite
labels map[uint]*kolide.Label
labelQueryExecutions map[uint]*kolide.LabelQueryExecution
queries map[uint]*kolide.Query
packs map[uint]*kolide.Pack
hosts map[uint]*kolide.Host
scheduledQueries map[uint]*kolide.ScheduledQuery
packTargets map[uint]*kolide.PackTarget
distributedQueryCampaigns map[uint]kolide.DistributedQueryCampaign
distributedQueryCampaignTargets map[uint]kolide.DistributedQueryCampaignTarget
appConfig *kolide.AppConfig
config *config.KolideConfig
users map[uint]*fleet.User
sessions map[uint]*fleet.Session
passwordResets map[uint]*fleet.PasswordResetRequest
invites map[uint]*fleet.Invite
labels map[uint]*fleet.Label
labelQueryExecutions map[uint]*fleet.LabelQueryExecution
queries map[uint]*fleet.Query
packs map[uint]*fleet.Pack
hosts map[uint]*fleet.Host
scheduledQueries map[uint]*fleet.ScheduledQuery
packTargets map[uint]*fleet.PackTarget
distributedQueryCampaigns map[uint]fleet.DistributedQueryCampaign
distributedQueryCampaignTargets map[uint]fleet.DistributedQueryCampaignTarget
appConfig *fleet.AppConfig
config *config.FleetConfig
// Embedded interface to avoid implementing new methods for (now
// deprecated) inmem.
kolide.Datastore
fleet.Datastore
}
func New(config config.KolideConfig) (*Datastore, error) {
func New(config config.FleetConfig) (*Datastore, error) {
ds := &Datastore{
Driver: "inmem",
config: &config,
@ -56,7 +56,7 @@ type imemTransactionStub struct{}
func (im *imemTransactionStub) Rollback() error { return nil }
func (im *imemTransactionStub) Commit() error { return nil }
func (d *Datastore) Begin() (kolide.Transaction, error) {
func (d *Datastore) Begin() (fleet.Transaction, error) {
return &imemTransactionStub{}, nil
}
@ -64,13 +64,13 @@ func (d *Datastore) Name() string {
return "inmem"
}
func sortResults(slice interface{}, opt kolide.ListOptions, fields map[string]string) error {
func sortResults(slice interface{}, opt fleet.ListOptions, fields map[string]string) error {
field, ok := fields[opt.OrderKey]
if !ok {
return errors.New("cannot sort on unknown key: " + opt.OrderKey)
}
if opt.OrderDirection == kolide.OrderDescending {
if opt.OrderDirection == fleet.OrderDescending {
sortutil.DescByField(slice, field)
} else {
sortutil.AscByField(slice, field)
@ -84,25 +84,25 @@ func (d *Datastore) MigrateTables() error {
defer d.mtx.Unlock()
d.nextIDs = make(map[interface{}]uint)
d.users = make(map[uint]*kolide.User)
d.sessions = make(map[uint]*kolide.Session)
d.passwordResets = make(map[uint]*kolide.PasswordResetRequest)
d.invites = make(map[uint]*kolide.Invite)
d.labels = make(map[uint]*kolide.Label)
d.labelQueryExecutions = make(map[uint]*kolide.LabelQueryExecution)
d.queries = make(map[uint]*kolide.Query)
d.packs = make(map[uint]*kolide.Pack)
d.hosts = make(map[uint]*kolide.Host)
d.scheduledQueries = make(map[uint]*kolide.ScheduledQuery)
d.packTargets = make(map[uint]*kolide.PackTarget)
d.distributedQueryCampaigns = make(map[uint]kolide.DistributedQueryCampaign)
d.distributedQueryCampaignTargets = make(map[uint]kolide.DistributedQueryCampaignTarget)
d.users = make(map[uint]*fleet.User)
d.sessions = make(map[uint]*fleet.Session)
d.passwordResets = make(map[uint]*fleet.PasswordResetRequest)
d.invites = make(map[uint]*fleet.Invite)
d.labels = make(map[uint]*fleet.Label)
d.labelQueryExecutions = make(map[uint]*fleet.LabelQueryExecution)
d.queries = make(map[uint]*fleet.Query)
d.packs = make(map[uint]*fleet.Pack)
d.hosts = make(map[uint]*fleet.Host)
d.scheduledQueries = make(map[uint]*fleet.ScheduledQuery)
d.packTargets = make(map[uint]*fleet.PackTarget)
d.distributedQueryCampaigns = make(map[uint]fleet.DistributedQueryCampaign)
d.distributedQueryCampaignTargets = make(map[uint]fleet.DistributedQueryCampaignTarget)
return nil
}
func (d *Datastore) MigrateData() error {
d.appConfig = &kolide.AppConfig{
d.appConfig = &fleet.AppConfig{
ID: 1,
SMTPEnableTLS: true,
SMTPPort: 587,
@ -113,7 +113,7 @@ func (d *Datastore) MigrateData() error {
return nil
}
func (m *Datastore) MigrationStatus() (kolide.MigrationStatus, error) {
func (m *Datastore) MigrationStatus() (fleet.MigrationStatus, error) {
return 0, nil
}
@ -148,7 +148,7 @@ func (d *Datastore) Initialize() error {
// getLimitOffsetSliceBounds returns the bounds that should be used for
// re-slicing the results to comply with the requested ListOptions. Lack of
// generics forces us to do this rather than reslicing in this method.
func (d *Datastore) getLimitOffsetSliceBounds(opt kolide.ListOptions, length int) (low uint, high uint) {
func (d *Datastore) getLimitOffsetSliceBounds(opt fleet.ListOptions, length int) (low uint, high uint) {
if opt.PerPage == 0 {
// PerPage value of 0 indicates unlimited
return 0, uint(length)
@ -174,7 +174,7 @@ func (d *Datastore) nextID(val interface{}) uint {
}
func (d *Datastore) createDevPacksAndQueries() error {
query1 := &kolide.Query{
query1 := &fleet.Query{
Name: "Osquery Info",
Query: "select * from osquery_info",
}
@ -183,7 +183,7 @@ func (d *Datastore) createDevPacksAndQueries() error {
return err
}
query2 := &kolide.Query{
query2 := &fleet.Query{
Name: "Launchd",
Query: "select * from launchd",
}
@ -192,7 +192,7 @@ func (d *Datastore) createDevPacksAndQueries() error {
return err
}
query3 := &kolide.Query{
query3 := &fleet.Query{
Name: "registry",
Query: "select * from osquery_registry",
}
@ -201,7 +201,7 @@ func (d *Datastore) createDevPacksAndQueries() error {
return err
}
pack1 := &kolide.Pack{
pack1 := &fleet.Pack{
Name: "Osquery Internal Info",
}
pack1, err = d.NewPack(pack1)
@ -209,7 +209,7 @@ func (d *Datastore) createDevPacksAndQueries() error {
return err
}
pack2 := &kolide.Pack{
pack2 := &fleet.Pack{
Name: "macOS Attacks",
}
pack2, err = d.NewPack(pack2)
@ -223,35 +223,35 @@ func (d *Datastore) createDevPacksAndQueries() error {
// Bootstrap a few users when using the in-memory database.
// Each user's default password will just be their username.
func (d *Datastore) createDevUsers() error {
users := []kolide.User{
users := []fleet.User{
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Date(2016, time.October, 27, 10, 0, 0, 0, time.UTC),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Date(2016, time.October, 27, 10, 0, 0, 0, time.UTC),
},
},
Name: "Admin User",
Username: "admin",
Email: "admin@kolide.co",
Email: "admin@fleet.co",
Position: "Director of Security",
},
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Now().Add(-3 * time.Hour),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Now().Add(-1 * time.Hour),
},
},
Name: "Normal User",
Username: "user",
Email: "user@kolide.co",
Email: "user@fleet.co",
Position: "Security Engineer",
},
}
@ -271,13 +271,13 @@ func (d *Datastore) createDevUsers() error {
}
func (d *Datastore) createDevQueries() error {
queries := []kolide.Query{
queries := []fleet.Query{
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Date(2016, time.October, 17, 7, 6, 0, 0, time.UTC),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Date(2016, time.October, 17, 7, 6, 0, 0, time.UTC),
},
},
@ -286,11 +286,11 @@ func (d *Datastore) createDevQueries() error {
Query: "select * from processes",
},
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Date(2016, time.October, 27, 4, 3, 10, 0, time.UTC),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Date(2016, time.October, 27, 4, 3, 10, 0, time.UTC),
},
},
@ -298,11 +298,11 @@ func (d *Datastore) createDevQueries() error {
Query: "select * from time",
},
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Now().Add(-24 * time.Hour),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Now().Add(-17 * time.Hour),
},
},
@ -311,11 +311,11 @@ func (d *Datastore) createDevQueries() error {
Query: "select * from cpuid",
},
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Now().Add(-1 * time.Hour),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Now().Add(-30 * time.Hour),
},
},
@ -324,11 +324,11 @@ func (d *Datastore) createDevQueries() error {
Query: "select 1 from processes where name like '%Apache%'",
},
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Now(),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Now(),
},
},
@ -350,13 +350,13 @@ func (d *Datastore) createDevQueries() error {
// Bootstrap a few hosts when using the in-memory database.
func (d *Datastore) createDevHosts() error {
hosts := []kolide.Host{
hosts := []fleet.Host{
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Date(2016, time.October, 27, 10, 0, 0, 0, time.UTC),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Now().Add(-20 * time.Minute),
},
},
@ -371,11 +371,11 @@ func (d *Datastore) createDevHosts() error {
DetailUpdateTime: time.Now().Add(-20 * time.Minute),
},
{
UpdateCreateTimestamps: kolide.UpdateCreateTimestamps{
CreateTimestamp: kolide.CreateTimestamp{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{
CreatedAt: time.Date(2016, time.October, 27, 4, 3, 10, 0, time.UTC),
},
UpdateTimestamp: kolide.UpdateTimestamp{
UpdateTimestamp: fleet.UpdateTimestamp{
UpdatedAt: time.Date(2016, time.October, 27, 4, 3, 10, 0, time.UTC),
},
},
@ -404,12 +404,12 @@ func (d *Datastore) createDevHosts() error {
}
func (d *Datastore) createDevOrgInfo() error {
devOrgInfo := &kolide.AppConfig{
devOrgInfo := &fleet.AppConfig{
KolideServerURL: "http://localhost:8080",
OrgName: "Kolide",
OrgLogoURL: fmt.Sprintf("https://%s/assets/images/fleet-logo.svg", d.config.Server.Address),
SMTPPort: 587,
SMTPAuthenticationType: kolide.AuthTypeUserNamePassword,
SMTPAuthenticationType: fleet.AuthTypeUserNamePassword,
SMTPEnableTLS: true,
SMTPVerifySSLCerts: true,
SMTPEnableStartTLS: true,

View File

@ -3,7 +3,7 @@ package inmem
import (
"testing"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/stretchr/testify/assert"
)
@ -12,10 +12,10 @@ func TestApplyLimitOffset(t *testing.T) {
data := []int{}
// should work with empty
low, high := im.getLimitOffsetSliceBounds(kolide.ListOptions{}, len(data))
low, high := im.getLimitOffsetSliceBounds(fleet.ListOptions{}, len(data))
result := data[low:high]
assert.Len(t, result, 0)
low, high = im.getLimitOffsetSliceBounds(kolide.ListOptions{Page: 1, PerPage: 20}, len(data))
low, high = im.getLimitOffsetSliceBounds(fleet.ListOptions{Page: 1, PerPage: 20}, len(data))
result = data[low:high]
assert.Len(t, result, 0)
@ -25,32 +25,32 @@ func TestApplyLimitOffset(t *testing.T) {
}
// unlimited
low, high = im.getLimitOffsetSliceBounds(kolide.ListOptions{}, len(data))
low, high = im.getLimitOffsetSliceBounds(fleet.ListOptions{}, len(data))
result = data[low:high]
assert.Len(t, result, 100)
assert.Equal(t, data, result)
// reasonable limit page 0
low, high = im.getLimitOffsetSliceBounds(kolide.ListOptions{PerPage: 20}, len(data))
low, high = im.getLimitOffsetSliceBounds(fleet.ListOptions{PerPage: 20}, len(data))
result = data[low:high]
assert.Len(t, result, 20)
assert.Equal(t, data[:20], result)
// too many per page
low, high = im.getLimitOffsetSliceBounds(kolide.ListOptions{PerPage: 200}, len(data))
low, high = im.getLimitOffsetSliceBounds(fleet.ListOptions{PerPage: 200}, len(data))
result = data[low:high]
assert.Len(t, result, 100)
assert.Equal(t, data, result)
// offset should be past end (zero results)
low, high = im.getLimitOffsetSliceBounds(kolide.ListOptions{Page: 1, PerPage: 200}, len(data))
low, high = im.getLimitOffsetSliceBounds(fleet.ListOptions{Page: 1, PerPage: 200}, len(data))
result = data[low:high]
assert.Len(t, result, 0)
// all pages appended should equal the original data
result = []int{}
for i := 0; i < 5; i++ { // 5 used intentionally
low, high = im.getLimitOffsetSliceBounds(kolide.ListOptions{Page: uint(i), PerPage: 25}, len(data))
low, high = im.getLimitOffsetSliceBounds(fleet.ListOptions{Page: uint(i), PerPage: 25}, len(data))
result = append(result, data[low:high]...)
}
assert.Len(t, result, 100)
@ -59,7 +59,7 @@ func TestApplyLimitOffset(t *testing.T) {
// again with different params
result = []int{}
for i := 0; i < 100; i++ { // 5 used intentionally
low, high = im.getLimitOffsetSliceBounds(kolide.ListOptions{Page: uint(i), PerPage: 1}, len(data))
low, high = im.getLimitOffsetSliceBounds(fleet.ListOptions{Page: uint(i), PerPage: 1}, len(data))
result = append(result, data[low:high]...)
}
assert.Len(t, result, 100)

View File

@ -5,11 +5,11 @@ import (
"sort"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
// NewInvite creates and stores a new invitation in a DB.
func (d *Datastore) NewInvite(invite *kolide.Invite) (*kolide.Invite, error) {
func (d *Datastore) NewInvite(invite *fleet.Invite) (*fleet.Invite, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -30,7 +30,7 @@ func (d *Datastore) NewInvite(invite *kolide.Invite) (*kolide.Invite, error) {
}
// Invites lists all invites in the datastore.
func (d *Datastore) ListInvites(opt kolide.ListOptions) ([]*kolide.Invite, error) {
func (d *Datastore) ListInvites(opt fleet.ListOptions) ([]*fleet.Invite, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -41,7 +41,7 @@ func (d *Datastore) ListInvites(opt kolide.ListOptions) ([]*kolide.Invite, error
}
sort.Ints(keys)
invites := []*kolide.Invite{}
invites := []*fleet.Invite{}
for _, k := range keys {
invites = append(invites, d.invites[uint(k)])
}
@ -70,7 +70,7 @@ func (d *Datastore) ListInvites(opt kolide.ListOptions) ([]*kolide.Invite, error
return invites, nil
}
func (d *Datastore) Invite(id uint) (*kolide.Invite, error) {
func (d *Datastore) Invite(id uint) (*fleet.Invite, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
if invite, ok := d.invites[id]; ok {
@ -80,7 +80,7 @@ func (d *Datastore) Invite(id uint) (*kolide.Invite, error) {
}
// InviteByEmail retrieves an invite for a specific email address.
func (d *Datastore) InviteByEmail(email string) (*kolide.Invite, error) {
func (d *Datastore) InviteByEmail(email string) (*fleet.Invite, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -94,7 +94,7 @@ func (d *Datastore) InviteByEmail(email string) (*kolide.Invite, error) {
}
// InviteByToken retrieves an invite given the invite token.
func (d *Datastore) InviteByToken(token string) (*kolide.Invite, error) {
func (d *Datastore) InviteByToken(token string) (*fleet.Invite, error) {
d.mtx.Lock()
defer d.mtx.Unlock()

View File

@ -7,11 +7,11 @@ import (
"strings"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/patrickmn/sortutil"
)
func (d *Datastore) NewLabel(label *kolide.Label, opts ...kolide.OptionalArg) (*kolide.Label, error) {
func (d *Datastore) NewLabel(label *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
newLabel := *label
@ -28,11 +28,11 @@ func (d *Datastore) NewLabel(label *kolide.Label, opts ...kolide.OptionalArg) (*
return &newLabel, nil
}
func (d *Datastore) ListLabelsForHost(hid uint) ([]*kolide.Label, error) {
func (d *Datastore) ListLabelsForHost(hid uint) ([]*fleet.Label, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
// First get IDs of label executions for the host
resLabels := []*kolide.Label{}
resLabels := []*fleet.Label{}
for _, lqe := range d.labelQueryExecutions {
if lqe.HostID == hid && lqe.Matches {
@ -45,7 +45,7 @@ func (d *Datastore) ListLabelsForHost(hid uint) ([]*kolide.Label, error) {
return resLabels, nil
}
func (d *Datastore) LabelQueriesForHost(host *kolide.Host, cutoff time.Time) (map[string]string, error) {
func (d *Datastore) LabelQueriesForHost(host *fleet.Host, cutoff time.Time) (map[string]string, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
// Get post-cutoff executions for host
@ -67,7 +67,7 @@ func (d *Datastore) LabelQueriesForHost(host *kolide.Host, cutoff time.Time) (ma
return queries, nil
}
func (d *Datastore) RecordLabelQueryExecutions(host *kolide.Host, results map[uint]bool, t time.Time) error {
func (d *Datastore) RecordLabelQueryExecutions(host *fleet.Host, results map[uint]bool, t time.Time) error {
// Record executions
for labelID, matches := range results {
label, ok := d.labels[labelID]
@ -89,7 +89,7 @@ func (d *Datastore) RecordLabelQueryExecutions(host *kolide.Host, results map[ui
if !updated {
// Create new execution
lqe := kolide.LabelQueryExecution{
lqe := fleet.LabelQueryExecution{
HostID: host.ID,
LabelID: label.ID,
UpdatedAt: t,
@ -104,7 +104,7 @@ func (d *Datastore) RecordLabelQueryExecutions(host *kolide.Host, results map[ui
return nil
}
func (d *Datastore) Label(lid uint) (*kolide.Label, error) {
func (d *Datastore) Label(lid uint) (*fleet.Label, error) {
d.mtx.Lock()
label, ok := d.labels[lid]
d.mtx.Unlock()
@ -115,7 +115,7 @@ func (d *Datastore) Label(lid uint) (*kolide.Label, error) {
return label, nil
}
func (d *Datastore) ListLabels(filter kolide.TeamFilter, opt kolide.ListOptions) ([]*kolide.Label, error) {
func (d *Datastore) ListLabels(filter fleet.TeamFilter, opt fleet.ListOptions) ([]*fleet.Label, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
// We need to sort by keys to provide reliable ordering
@ -126,7 +126,7 @@ func (d *Datastore) ListLabels(filter kolide.TeamFilter, opt kolide.ListOptions)
}
sort.Ints(keys)
labels := []*kolide.Label{}
labels := []*fleet.Label{}
for _, k := range keys {
labels = append(labels, d.labels[uint(k)])
}
@ -151,13 +151,13 @@ func (d *Datastore) ListLabels(filter kolide.TeamFilter, opt kolide.ListOptions)
return labels, nil
}
func (d *Datastore) SearchLabels(filter kolide.TeamFilter, query string, omit ...uint) ([]*kolide.Label, error) {
func (d *Datastore) SearchLabels(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Label, error) {
omitLookup := map[uint]bool{}
for _, o := range omit {
omitLookup[o] = true
}
var results []*kolide.Label
var results []*fleet.Label
d.mtx.Lock()
defer d.mtx.Unlock()
@ -177,8 +177,8 @@ func (d *Datastore) SearchLabels(filter kolide.TeamFilter, query string, omit ..
return results, nil
}
func (d *Datastore) ListHostsInLabel(filter kolide.TeamFilter, lid uint, opt kolide.HostListOptions) ([]*kolide.Host, error) {
var hosts []*kolide.Host
func (d *Datastore) ListHostsInLabel(filter fleet.TeamFilter, lid uint, opt fleet.HostListOptions) ([]*fleet.Host, error) {
var hosts []*fleet.Host
d.mtx.Lock()
defer d.mtx.Unlock()
@ -192,8 +192,8 @@ func (d *Datastore) ListHostsInLabel(filter kolide.TeamFilter, lid uint, opt kol
return hosts, nil
}
func (d *Datastore) ListUniqueHostsInLabels(filter kolide.TeamFilter, labels []uint) ([]*kolide.Host, error) {
var hosts []*kolide.Host
func (d *Datastore) ListUniqueHostsInLabels(filter fleet.TeamFilter, labels []uint) ([]*fleet.Host, error) {
var hosts []*fleet.Host
labelSet := map[uint]bool{}
hostSet := map[uint]bool{}
@ -217,6 +217,6 @@ func (d *Datastore) ListUniqueHostsInLabels(filter kolide.TeamFilter, labels []u
return hosts, nil
}
func (d *Datastore) SaveLabel(label *kolide.Label) (*kolide.Label, error) {
func (d *Datastore) SaveLabel(label *fleet.Label) (*fleet.Label, error) {
panic("inmem is being deprecated")
}

View File

@ -3,10 +3,10 @@ package inmem
import (
"sort"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func (d *Datastore) PackByName(name string, opts ...kolide.OptionalArg) (*kolide.Pack, bool, error) {
func (d *Datastore) PackByName(name string, opts ...fleet.OptionalArg) (*fleet.Pack, bool, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
for _, p := range d.packs {
@ -17,7 +17,7 @@ func (d *Datastore) PackByName(name string, opts ...kolide.OptionalArg) (*kolide
return nil, false, nil
}
func (d *Datastore) NewPack(pack *kolide.Pack, opts ...kolide.OptionalArg) (*kolide.Pack, error) {
func (d *Datastore) NewPack(pack *fleet.Pack, opts ...fleet.OptionalArg) (*fleet.Pack, error) {
newPack := *pack
for _, q := range d.packs {
@ -36,7 +36,7 @@ func (d *Datastore) NewPack(pack *kolide.Pack, opts ...kolide.OptionalArg) (*kol
return pack, nil
}
func (d *Datastore) SavePack(pack *kolide.Pack) error {
func (d *Datastore) SavePack(pack *fleet.Pack) error {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -49,7 +49,7 @@ func (d *Datastore) SavePack(pack *kolide.Pack) error {
return nil
}
func (d *Datastore) Pack(id uint) (*kolide.Pack, error) {
func (d *Datastore) Pack(id uint) (*fleet.Pack, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -61,7 +61,7 @@ func (d *Datastore) Pack(id uint) (*kolide.Pack, error) {
return pack, nil
}
func (d *Datastore) ListPacks(opt kolide.ListOptions) ([]*kolide.Pack, error) {
func (d *Datastore) ListPacks(opt fleet.ListOptions) ([]*fleet.Pack, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -72,7 +72,7 @@ func (d *Datastore) ListPacks(opt kolide.ListOptions) ([]*kolide.Pack, error) {
}
sort.Ints(keys)
packs := []*kolide.Pack{}
packs := []*fleet.Pack{}
for _, k := range keys {
packs = append(packs, d.packs[uint(k)])
}
@ -98,19 +98,19 @@ func (d *Datastore) ListPacks(opt kolide.ListOptions) ([]*kolide.Pack, error) {
return packs, nil
}
func (d *Datastore) AddLabelToPack(lid, pid uint, opts ...kolide.OptionalArg) error {
func (d *Datastore) AddLabelToPack(lid, pid uint, opts ...fleet.OptionalArg) error {
d.mtx.Lock()
defer d.mtx.Unlock()
for _, pt := range d.packTargets {
if pt.PackID == pid && pt.Target.Type == kolide.TargetLabel && pt.Target.TargetID == lid {
if pt.PackID == pid && pt.Target.Type == fleet.TargetLabel && pt.Target.TargetID == lid {
return nil
}
}
pt := &kolide.PackTarget{
pt := &fleet.PackTarget{
PackID: pid,
Target: kolide.Target{
Type: kolide.TargetLabel,
Target: fleet.Target{
Type: fleet.TargetLabel,
TargetID: lid,
},
}
@ -125,15 +125,15 @@ func (d *Datastore) AddHostToPack(hid, pid uint) error {
defer d.mtx.Unlock()
for _, pt := range d.packTargets {
if pt.PackID == pid && pt.Target.Type == kolide.TargetHost && pt.Target.TargetID == hid {
if pt.PackID == pid && pt.Target.Type == fleet.TargetHost && pt.Target.TargetID == hid {
d.mtx.Unlock()
return nil
}
}
pt := &kolide.PackTarget{
pt := &fleet.PackTarget{
PackID: pid,
Target: kolide.Target{
Type: kolide.TargetHost,
Target: fleet.Target{
Type: fleet.TargetHost,
TargetID: hid,
},
}
@ -143,12 +143,12 @@ func (d *Datastore) AddHostToPack(hid, pid uint) error {
return nil
}
func (d *Datastore) ListLabelsForPack(pid uint) ([]*kolide.Label, error) {
func (d *Datastore) ListLabelsForPack(pid uint) ([]*fleet.Label, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
var labels []*kolide.Label
var labels []*fleet.Label
for _, pt := range d.packTargets {
if pt.Type == kolide.TargetLabel && pt.PackID == pid {
if pt.Type == fleet.TargetLabel && pt.PackID == pid {
labels = append(labels, d.labels[pt.TargetID])
}
}
@ -163,7 +163,7 @@ func (d *Datastore) RemoveLabelFromPack(lid, pid uint) error {
var labelsToDelete []uint
for _, pt := range d.packTargets {
if pt.Type == kolide.TargetLabel && pt.TargetID == lid && pt.PackID == pid {
if pt.Type == fleet.TargetLabel && pt.TargetID == lid && pt.PackID == pid {
labelsToDelete = append(labelsToDelete, pt.ID)
}
}
@ -182,7 +182,7 @@ func (d *Datastore) RemoveHostFromPack(hid, pid uint) error {
var hostsToDelete []uint
for _, pt := range d.packTargets {
if pt.Type == kolide.TargetHost && pt.TargetID == hid && pt.PackID == pid {
if pt.Type == fleet.TargetHost && pt.TargetID == hid && pt.PackID == pid {
hostsToDelete = append(hostsToDelete, pt.ID)
}
}
@ -194,11 +194,11 @@ func (d *Datastore) RemoveHostFromPack(hid, pid uint) error {
return nil
}
func (d *Datastore) ListHostsInPack(pid uint, opt kolide.ListOptions) ([]uint, error) {
func (d *Datastore) ListHostsInPack(pid uint, opt fleet.ListOptions) ([]uint, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
hostLookup := map[uint]bool{}
for _, pt := range d.packTargets {
@ -207,12 +207,12 @@ func (d *Datastore) ListHostsInPack(pid uint, opt kolide.ListOptions) ([]uint, e
}
switch pt.Type {
case kolide.TargetHost:
case fleet.TargetHost:
if !hostLookup[pt.TargetID] {
hostLookup[pt.TargetID] = true
hosts = append(hosts, d.hosts[pt.TargetID])
}
case kolide.TargetLabel:
case fleet.TargetLabel:
for _, lqe := range d.labelQueryExecutions {
if lqe.LabelID == pt.TargetID && lqe.Matches && !hostLookup[lqe.HostID] {
hostLookup[lqe.HostID] = true
@ -250,11 +250,11 @@ func (d *Datastore) ListHostsInPack(pid uint, opt kolide.ListOptions) ([]uint, e
return extractHostIDs(hosts), nil
}
func (d *Datastore) ListExplicitHostsInPack(pid uint, opt kolide.ListOptions) ([]uint, error) {
func (d *Datastore) ListExplicitHostsInPack(pid uint, opt fleet.ListOptions) ([]uint, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
hostLookup := map[uint]bool{}
for _, pt := range d.packTargets {
@ -262,7 +262,7 @@ func (d *Datastore) ListExplicitHostsInPack(pid uint, opt kolide.ListOptions) ([
continue
}
if pt.Type == kolide.TargetHost {
if pt.Type == fleet.TargetHost {
if !hostLookup[pt.TargetID] {
hostLookup[pt.TargetID] = true
hosts = append(hosts, d.hosts[pt.TargetID])
@ -298,7 +298,7 @@ func (d *Datastore) ListExplicitHostsInPack(pid uint, opt kolide.ListOptions) ([
return extractHostIDs(hosts), nil
}
func extractHostIDs(hosts []*kolide.Host) []uint {
func extractHostIDs(hosts []*fleet.Host) []uint {
ids := make([]uint, len(hosts))
for i, h := range hosts {
ids[i] = h.ID

View File

@ -3,10 +3,10 @@ package inmem
import (
"fmt"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func (d *Datastore) NewPasswordResetRequest(req *kolide.PasswordResetRequest) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) NewPasswordResetRequest(req *fleet.PasswordResetRequest) (*fleet.PasswordResetRequest, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -15,7 +15,7 @@ func (d *Datastore) NewPasswordResetRequest(req *kolide.PasswordResetRequest) (*
return req, nil
}
func (d *Datastore) SavePasswordResetRequest(req *kolide.PasswordResetRequest) error {
func (d *Datastore) SavePasswordResetRequest(req *fleet.PasswordResetRequest) error {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -27,7 +27,7 @@ func (d *Datastore) SavePasswordResetRequest(req *kolide.PasswordResetRequest) e
return nil
}
func (d *Datastore) DeletePasswordResetRequest(req *kolide.PasswordResetRequest) error {
func (d *Datastore) DeletePasswordResetRequest(req *fleet.PasswordResetRequest) error {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -51,7 +51,7 @@ func (d *Datastore) DeletePasswordResetRequestsForUser(userID uint) error {
return nil
}
func (d *Datastore) FindPassswordResetByID(id uint) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetByID(id uint) (*fleet.PasswordResetRequest, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -62,10 +62,10 @@ func (d *Datastore) FindPassswordResetByID(id uint) (*kolide.PasswordResetReques
return nil, notFound("PasswordResetRequest").WithID(id)
}
func (d *Datastore) FindPassswordResetsByUserID(userID uint) ([]*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetsByUserID(userID uint) ([]*fleet.PasswordResetRequest, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
resets := make([]*kolide.PasswordResetRequest, 0)
resets := make([]*fleet.PasswordResetRequest, 0)
for _, pr := range d.passwordResets {
if pr.UserID == userID {
@ -81,7 +81,7 @@ func (d *Datastore) FindPassswordResetsByUserID(userID uint) ([]*kolide.Password
return resets, nil
}
func (d *Datastore) FindPassswordResetByToken(token string) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetByToken(token string) (*fleet.PasswordResetRequest, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -94,7 +94,7 @@ func (d *Datastore) FindPassswordResetByToken(token string) (*kolide.PasswordRes
return nil, notFound("PasswordResetRequest")
}
func (d *Datastore) FindPassswordResetByTokenAndUserID(token string, userID uint) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetByTokenAndUserID(token string, userID uint) (*fleet.PasswordResetRequest, error) {
d.mtx.Lock()
defer d.mtx.Unlock()

View File

@ -3,11 +3,11 @@ package inmem
import (
"sort"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
func (d *Datastore) NewQuery(query *kolide.Query, opts ...kolide.OptionalArg) (*kolide.Query, error) {
func (d *Datastore) NewQuery(query *fleet.Query, opts ...fleet.OptionalArg) (*fleet.Query, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -20,13 +20,13 @@ func (d *Datastore) NewQuery(query *kolide.Query, opts ...kolide.OptionalArg) (*
}
newQuery.ID = d.nextID(newQuery)
newQuery.Packs = []kolide.Pack{}
newQuery.Packs = []fleet.Pack{}
d.queries[newQuery.ID] = &newQuery
return &newQuery, nil
}
func (d *Datastore) SaveQuery(query *kolide.Query) error {
func (d *Datastore) SaveQuery(query *fleet.Query) error {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -62,7 +62,7 @@ func (d *Datastore) getUserNameByID(id uint) string {
return ""
}
func (d *Datastore) Query(id uint) (*kolide.Query, error) {
func (d *Datastore) Query(id uint) (*fleet.Query, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -73,14 +73,14 @@ func (d *Datastore) Query(id uint) (*kolide.Query, error) {
query.AuthorName = d.getUserNameByID(*query.AuthorID)
if err := d.loadPacksForQueries([]*kolide.Query{query}); err != nil {
if err := d.loadPacksForQueries([]*fleet.Query{query}); err != nil {
return nil, errors.Wrap(err, "error fetching query by id")
}
return query, nil
}
func (d *Datastore) ListQueries(opt kolide.ListOptions) ([]*kolide.Query, error) {
func (d *Datastore) ListQueries(opt fleet.ListOptions) ([]*fleet.Query, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -91,7 +91,7 @@ func (d *Datastore) ListQueries(opt kolide.ListOptions) ([]*kolide.Query, error)
}
sort.Ints(keys)
queries := []*kolide.Query{}
queries := []*fleet.Query{}
for _, k := range keys {
q := d.queries[uint(k)]
if q.Saved {
@ -131,9 +131,9 @@ func (d *Datastore) ListQueries(opt kolide.ListOptions) ([]*kolide.Query, error)
}
// loadPacksForQueries loads the packs associated with the provided queries
func (d *Datastore) loadPacksForQueries(queries []*kolide.Query) error {
func (d *Datastore) loadPacksForQueries(queries []*fleet.Query) error {
for _, q := range queries {
q.Packs = make([]kolide.Pack, 0)
q.Packs = make([]fleet.Pack, 0)
for _, sq := range d.scheduledQueries {
if sq.QueryName == q.Name {
q.Packs = append(q.Packs, *d.packs[sq.PackID])

View File

@ -3,10 +3,10 @@ package inmem
import (
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func (d *Datastore) SessionByKey(key string) (*kolide.Session, error) {
func (d *Datastore) SessionByKey(key string) (*fleet.Session, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -18,7 +18,7 @@ func (d *Datastore) SessionByKey(key string) (*kolide.Session, error) {
return nil, notFound("Session")
}
func (d *Datastore) SessionByID(id uint) (*kolide.Session, error) {
func (d *Datastore) SessionByID(id uint) (*fleet.Session, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -28,11 +28,11 @@ func (d *Datastore) SessionByID(id uint) (*kolide.Session, error) {
return nil, notFound("Session").WithID(id)
}
func (d *Datastore) ListSessionsForUser(id uint) ([]*kolide.Session, error) {
func (d *Datastore) ListSessionsForUser(id uint) ([]*fleet.Session, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
var sessions []*kolide.Session
var sessions []*fleet.Session
for _, session := range d.sessions {
if session.UserID == id {
sessions = append(sessions, session)
@ -42,7 +42,7 @@ func (d *Datastore) ListSessionsForUser(id uint) ([]*kolide.Session, error) {
return sessions, nil
}
func (d *Datastore) NewSession(session *kolide.Session) (*kolide.Session, error) {
func (d *Datastore) NewSession(session *fleet.Session) (*fleet.Session, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -56,7 +56,7 @@ func (d *Datastore) NewSession(session *kolide.Session) (*kolide.Session, error)
}
func (d *Datastore) DestroySession(session *kolide.Session) error {
func (d *Datastore) DestroySession(session *fleet.Session) error {
if _, ok := d.sessions[session.ID]; !ok {
return notFound("Session").WithID(session.ID)
}
@ -73,7 +73,7 @@ func (d *Datastore) DestroyAllSessionsForUser(id uint) error {
return nil
}
func (d *Datastore) MarkSessionAccessed(session *kolide.Session) error {
func (d *Datastore) MarkSessionAccessed(session *fleet.Session) error {
session.AccessedAt = time.Now().UTC()
if _, ok := d.sessions[session.ID]; !ok {
return notFound("Session").WithID(session.ID)

View File

@ -3,10 +3,10 @@ package inmem
import (
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func (d *Datastore) CountHostsInTargets(filter kolide.TeamFilter, targets kolide.HostTargets, now time.Time) (kolide.TargetMetrics, error) {
func (d *Datastore) CountHostsInTargets(filter fleet.TeamFilter, targets fleet.HostTargets, now time.Time) (fleet.TargetMetrics, error) {
// noop
return kolide.TargetMetrics{}, nil
return fleet.TargetMetrics{}, nil
}

View File

@ -4,10 +4,10 @@ import (
"fmt"
"sort"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func (d *Datastore) NewUser(user *kolide.User) (*kolide.User, error) {
func (d *Datastore) NewUser(user *fleet.User) (*fleet.User, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -23,7 +23,7 @@ func (d *Datastore) NewUser(user *kolide.User) (*kolide.User, error) {
return user, nil
}
func (d *Datastore) User(username string) (*kolide.User, error) {
func (d *Datastore) User(username string) (*fleet.User, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -37,7 +37,7 @@ func (d *Datastore) User(username string) (*kolide.User, error) {
WithMessage(fmt.Sprintf("with username %s", username))
}
func (d *Datastore) ListUsers(opt kolide.UserListOptions) ([]*kolide.User, error) {
func (d *Datastore) ListUsers(opt fleet.UserListOptions) ([]*fleet.User, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -48,7 +48,7 @@ func (d *Datastore) ListUsers(opt kolide.UserListOptions) ([]*kolide.User, error
}
sort.Ints(keys)
users := []*kolide.User{}
users := []*fleet.User{}
for _, k := range keys {
users = append(users, d.users[uint(k)])
}
@ -78,7 +78,7 @@ func (d *Datastore) ListUsers(opt kolide.UserListOptions) ([]*kolide.User, error
return users, nil
}
func (d *Datastore) UserByEmail(email string) (*kolide.User, error) {
func (d *Datastore) UserByEmail(email string) (*fleet.User, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -92,7 +92,7 @@ func (d *Datastore) UserByEmail(email string) (*kolide.User, error) {
WithMessage(fmt.Sprintf("with email address %s", email))
}
func (d *Datastore) UserByID(id uint) (*kolide.User, error) {
func (d *Datastore) UserByID(id uint) (*fleet.User, error) {
d.mtx.Lock()
defer d.mtx.Unlock()
@ -103,7 +103,7 @@ func (d *Datastore) UserByID(id uint) (*kolide.User, error) {
return nil, notFound("User").WithID(id)
}
func (d *Datastore) SaveUser(user *kolide.User) error {
func (d *Datastore) SaveUser(user *fleet.User) error {
d.mtx.Lock()
defer d.mtx.Unlock()

View File

@ -1,74 +1,74 @@
package appstate
import "github.com/fleetdm/fleet/server/kolide"
import "github.com/fleetdm/fleet/server/fleet"
// Labels is the set of builtin labels that should be populated in the
// datastore
func Labels1() []kolide.Label {
return []kolide.Label{
func Labels1() []fleet.Label {
return []fleet.Label{
{
Name: "All Hosts",
Query: "select 1;",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Platform: "darwin",
Name: "Mac OS X",
Query: "select 1 from osquery_info where build_platform = 'darwin';",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Platform: "ubuntu",
Name: "Ubuntu Linux",
Query: "select 1 from osquery_info where build_platform = 'ubuntu';",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Platform: "centos",
Name: "CentOS Linux",
Query: "select 1 from osquery_info where build_platform = 'centos';",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Platform: "windows",
Name: "MS Windows",
Query: "select 1 from osquery_info where build_platform = 'windows';",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
}
}
func Labels2() []kolide.Label {
return []kolide.Label{
func Labels2() []fleet.Label {
return []fleet.Label{
{
Name: "All Hosts",
Query: "select 1;",
Description: "All hosts which have enrolled in Fleet",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Name: "macOS",
Query: "select 1 from os_version where platform = 'darwin';",
Description: "All macOS hosts",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Name: "Ubuntu Linux",
Query: "select 1 from os_version where platform = 'ubuntu';",
Description: "All Ubuntu hosts",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Name: "CentOS Linux",
Query: "select 1 from os_version where platform = 'centos';",
Description: "All CentOS hosts",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
{
Name: "MS Windows",
Query: "select 1 from os_version where platform = 'windows';",
Description: "All Windows hosts",
LabelType: kolide.LabelTypeBuiltIn,
LabelType: fleet.LabelTypeBuiltIn,
},
}
}

View File

@ -4,13 +4,13 @@ import (
"fmt"
"github.com/VividCortex/mysqlerr"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func (d *Datastore) NewAppConfig(info *kolide.AppConfig) (*kolide.AppConfig, error) {
func (d *Datastore) NewAppConfig(info *fleet.AppConfig) (*fleet.AppConfig, error) {
if err := d.SaveAppConfig(info); err != nil {
return nil, errors.Wrap(err, "new app config")
}
@ -18,8 +18,8 @@ func (d *Datastore) NewAppConfig(info *kolide.AppConfig) (*kolide.AppConfig, err
return info, nil
}
func (d *Datastore) AppConfig() (*kolide.AppConfig, error) {
info := &kolide.AppConfig{}
func (d *Datastore) AppConfig() (*fleet.AppConfig, error) {
info := &fleet.AppConfig{}
err := d.db.Get(info, "SELECT * FROM app_configs LIMIT 1")
if err != nil {
return nil, errors.Wrap(err, "selecting app config")
@ -71,7 +71,7 @@ func (d *Datastore) ManageHostExpiryEvent(hostExpiryEnabled bool, hostExpiryWind
return nil
}
func (d *Datastore) SaveAppConfig(info *kolide.AppConfig) error {
func (d *Datastore) SaveAppConfig(info *fleet.AppConfig) error {
eventSchedulerEnabled, err := d.isEventSchedulerEnabled()
if err != nil {
return err
@ -189,8 +189,8 @@ func (d *Datastore) SaveAppConfig(info *kolide.AppConfig) error {
return err
}
func (d *Datastore) VerifyEnrollSecret(secret string) (*kolide.EnrollSecret, error) {
var s kolide.EnrollSecret
func (d *Datastore) VerifyEnrollSecret(secret string) (*fleet.EnrollSecret, error) {
var s fleet.EnrollSecret
err := d.db.Get(&s, "SELECT team_id FROM enroll_secrets WHERE secret = ?", secret)
if err != nil {
return nil, errors.New("no matching secret found")
@ -199,7 +199,7 @@ func (d *Datastore) VerifyEnrollSecret(secret string) (*kolide.EnrollSecret, err
return &s, nil
}
func (d *Datastore) ApplyEnrollSecrets(teamID *uint, secrets []*kolide.EnrollSecret) error {
func (d *Datastore) ApplyEnrollSecrets(teamID *uint, secrets []*fleet.EnrollSecret) error {
err := d.withRetryTxx(func(tx *sqlx.Tx) error {
if teamID != nil {
sql := `DELETE FROM enroll_secrets WHERE team_id = ?`
@ -228,7 +228,7 @@ func (d *Datastore) ApplyEnrollSecrets(teamID *uint, secrets []*kolide.EnrollSec
return err
}
func (d *Datastore) GetEnrollSecrets(teamID *uint) ([]*kolide.EnrollSecret, error) {
func (d *Datastore) GetEnrollSecrets(teamID *uint) ([]*fleet.EnrollSecret, error) {
var args []interface{}
sql := "SELECT * FROM enroll_secrets WHERE "
// MySQL requires comparing NULL with IS. NULL = NULL evaluates to FALSE.
@ -238,7 +238,7 @@ func (d *Datastore) GetEnrollSecrets(teamID *uint) ([]*kolide.EnrollSecret, erro
sql += "team_id = ?"
args = append(args, teamID)
}
var secrets []*kolide.EnrollSecret
var secrets []*fleet.EnrollSecret
if err := d.db.Select(&secrets, sql, args...); err != nil {
return nil, errors.Wrap(err, "get secrets")
}

View File

@ -3,11 +3,11 @@ package mysql
import (
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
func (d *Datastore) NewDistributedQueryCampaign(camp *kolide.DistributedQueryCampaign) (*kolide.DistributedQueryCampaign, error) {
func (d *Datastore) NewDistributedQueryCampaign(camp *fleet.DistributedQueryCampaign) (*fleet.DistributedQueryCampaign, error) {
sqlStatement := `
INSERT INTO distributed_query_campaigns (
@ -27,11 +27,11 @@ func (d *Datastore) NewDistributedQueryCampaign(camp *kolide.DistributedQueryCam
return camp, nil
}
func (d *Datastore) DistributedQueryCampaign(id uint) (*kolide.DistributedQueryCampaign, error) {
func (d *Datastore) DistributedQueryCampaign(id uint) (*fleet.DistributedQueryCampaign, error) {
sql := `
SELECT * FROM distributed_query_campaigns WHERE id = ?
`
campaign := &kolide.DistributedQueryCampaign{}
campaign := &fleet.DistributedQueryCampaign{}
if err := d.db.Get(campaign, sql, id); err != nil {
return nil, errors.Wrap(err, "selecting distributed query campaign")
}
@ -39,7 +39,7 @@ func (d *Datastore) DistributedQueryCampaign(id uint) (*kolide.DistributedQueryC
return campaign, nil
}
func (d *Datastore) SaveDistributedQueryCampaign(camp *kolide.DistributedQueryCampaign) error {
func (d *Datastore) SaveDistributedQueryCampaign(camp *fleet.DistributedQueryCampaign) error {
sqlStatement := `
UPDATE distributed_query_campaigns SET
query_id = ?,
@ -62,11 +62,11 @@ func (d *Datastore) SaveDistributedQueryCampaign(camp *kolide.DistributedQueryCa
return nil
}
func (d *Datastore) DistributedQueryCampaignTargetIDs(id uint) (*kolide.HostTargets, error) {
func (d *Datastore) DistributedQueryCampaignTargetIDs(id uint) (*fleet.HostTargets, error) {
sqlStatement := `
SELECT * FROM distributed_query_campaign_targets WHERE distributed_query_campaign_id = ?
`
targets := []kolide.DistributedQueryCampaignTarget{}
targets := []fleet.DistributedQueryCampaignTarget{}
if err := d.db.Select(&targets, sqlStatement, id); err != nil {
return nil, errors.Wrap(err, "select distributed campaign target")
@ -76,19 +76,19 @@ func (d *Datastore) DistributedQueryCampaignTargetIDs(id uint) (*kolide.HostTarg
labelIDs := []uint{}
teamIDs := []uint{}
for _, target := range targets {
if target.Type == kolide.TargetHost {
if target.Type == fleet.TargetHost {
hostIDs = append(hostIDs, target.TargetID)
} else if target.Type == kolide.TargetLabel {
} else if target.Type == fleet.TargetLabel {
labelIDs = append(labelIDs, target.TargetID)
} else {
return nil, errors.Errorf("invalid target type: %d", target.Type)
}
}
return &kolide.HostTargets{HostIDs: hostIDs, LabelIDs: labelIDs, TeamIDs: teamIDs}, nil
return &fleet.HostTargets{HostIDs: hostIDs, LabelIDs: labelIDs, TeamIDs: teamIDs}, nil
}
func (d *Datastore) NewDistributedQueryCampaignTarget(target *kolide.DistributedQueryCampaignTarget) (*kolide.DistributedQueryCampaignTarget, error) {
func (d *Datastore) NewDistributedQueryCampaignTarget(target *fleet.DistributedQueryCampaignTarget) (*fleet.DistributedQueryCampaignTarget, error) {
sqlStatement := `
INSERT into distributed_query_campaign_targets (
type,
@ -115,9 +115,9 @@ func (d *Datastore) CleanupDistributedQueryCampaigns(now time.Time) (expired uin
WHERE (status = ? AND created_at < ?)
OR (status = ? AND created_at < ?)
`
result, err := d.db.Exec(sqlStatement, kolide.QueryComplete,
kolide.QueryWaiting, now.Add(-1*time.Minute),
kolide.QueryRunning, now.Add(-24*time.Hour))
result, err := d.db.Exec(sqlStatement, fleet.QueryComplete,
fleet.QueryWaiting, now.Add(-1*time.Minute),
fleet.QueryRunning, now.Add(-24*time.Hour))
if err != nil {
return 0, errors.Wrap(err, "updating distributed query campaign")
}

View File

@ -5,12 +5,12 @@ import (
"fmt"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func (d *Datastore) NewCarve(metadata *kolide.CarveMetadata) (*kolide.CarveMetadata, error) {
func (d *Datastore) NewCarve(metadata *fleet.CarveMetadata) (*fleet.CarveMetadata, error) {
stmt := `INSERT INTO carve_metadata (
host_id,
created_at,
@ -57,7 +57,7 @@ func (d *Datastore) NewCarve(metadata *kolide.CarveMetadata) (*kolide.CarveMetad
// UpdateCarve updates the carve metadata in database
// Only max_block and expired are updatable
func (d *Datastore) UpdateCarve(metadata *kolide.CarveMetadata) error {
func (d *Datastore) UpdateCarve(metadata *fleet.CarveMetadata) error {
stmt := `
UPDATE carve_metadata SET
max_block = ?,
@ -154,7 +154,7 @@ const carveSelectFields = `
max_block
`
func (d *Datastore) Carve(carveId int64) (*kolide.CarveMetadata, error) {
func (d *Datastore) Carve(carveId int64) (*fleet.CarveMetadata, error) {
stmt := fmt.Sprintf(`
SELECT %s
FROM carve_metadata
@ -162,7 +162,7 @@ func (d *Datastore) Carve(carveId int64) (*kolide.CarveMetadata, error) {
carveSelectFields,
)
var metadata kolide.CarveMetadata
var metadata fleet.CarveMetadata
if err := d.db.Get(&metadata, stmt, carveId); err != nil {
return nil, errors.Wrap(err, "get carve by ID")
}
@ -170,7 +170,7 @@ func (d *Datastore) Carve(carveId int64) (*kolide.CarveMetadata, error) {
return &metadata, nil
}
func (d *Datastore) CarveBySessionId(sessionId string) (*kolide.CarveMetadata, error) {
func (d *Datastore) CarveBySessionId(sessionId string) (*fleet.CarveMetadata, error) {
stmt := fmt.Sprintf(`
SELECT %s
FROM carve_metadata
@ -178,7 +178,7 @@ func (d *Datastore) CarveBySessionId(sessionId string) (*kolide.CarveMetadata, e
carveSelectFields,
)
var metadata kolide.CarveMetadata
var metadata fleet.CarveMetadata
if err := d.db.Get(&metadata, stmt, sessionId); err != nil {
return nil, errors.Wrap(err, "get carve by session ID")
}
@ -186,7 +186,7 @@ func (d *Datastore) CarveBySessionId(sessionId string) (*kolide.CarveMetadata, e
return &metadata, nil
}
func (d *Datastore) CarveByName(name string) (*kolide.CarveMetadata, error) {
func (d *Datastore) CarveByName(name string) (*fleet.CarveMetadata, error) {
stmt := fmt.Sprintf(`
SELECT %s
FROM carve_metadata
@ -194,7 +194,7 @@ func (d *Datastore) CarveByName(name string) (*kolide.CarveMetadata, error) {
carveSelectFields,
)
var metadata kolide.CarveMetadata
var metadata fleet.CarveMetadata
if err := d.db.Get(&metadata, stmt, name); err != nil {
return nil, errors.Wrap(err, "get carve by name")
}
@ -202,7 +202,7 @@ func (d *Datastore) CarveByName(name string) (*kolide.CarveMetadata, error) {
return &metadata, nil
}
func (d *Datastore) ListCarves(opt kolide.CarveListOptions) ([]*kolide.CarveMetadata, error) {
func (d *Datastore) ListCarves(opt fleet.CarveListOptions) ([]*fleet.CarveMetadata, error) {
stmt := fmt.Sprintf(`
SELECT %s
FROM carve_metadata`,
@ -212,7 +212,7 @@ func (d *Datastore) ListCarves(opt kolide.CarveListOptions) ([]*kolide.CarveMeta
stmt += ` WHERE NOT expired `
}
stmt = appendListOptionsToSQL(stmt, opt.ListOptions)
carves := []*kolide.CarveMetadata{}
carves := []*fleet.CarveMetadata{}
if err := d.db.Select(&carves, stmt); err != nil && err != sql.ErrNoRows {
return nil, errors.Wrap(err, "list carves")
}
@ -220,7 +220,7 @@ func (d *Datastore) ListCarves(opt kolide.CarveListOptions) ([]*kolide.CarveMeta
return carves, nil
}
func (d *Datastore) NewBlock(metadata *kolide.CarveMetadata, blockId int64, data []byte) error {
func (d *Datastore) NewBlock(metadata *fleet.CarveMetadata, blockId int64, data []byte) error {
stmt := `
INSERT INTO carve_blocks (
metadata_id,
@ -246,7 +246,7 @@ func (d *Datastore) NewBlock(metadata *kolide.CarveMetadata, blockId int64, data
return nil
}
func (d *Datastore) GetBlock(metadata *kolide.CarveMetadata, blockId int64) ([]byte, error) {
func (d *Datastore) GetBlock(metadata *fleet.CarveMetadata, blockId int64) ([]byte, error) {
stmt := `
SELECT data
FROM carve_blocks

View File

@ -10,9 +10,10 @@ import (
"github.com/WatchBeam/clock"
"github.com/fleetdm/fleet/server/config"
"github.com/fleetdm/fleet/server/datastore"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/test"
"github.com/go-kit/kit/log"
_ "github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/require"
)
@ -104,7 +105,7 @@ func initializeDatabase(t *testing.T, dbName string) {
}
func runTest(t *testing.T, testFunc func(*testing.T, kolide.Datastore)) {
func runTest(t *testing.T, testFunc func(*testing.T, fleet.Datastore)) {
t.Run(test.FunctionName(testFunc), func(t *testing.T) {
t.Parallel()

View File

@ -7,14 +7,14 @@ import (
"time"
"github.com/cenkalti/backoff/v4"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
var hostSearchColumns = []string{"host_name", "uuid", "hardware_serial", "primary_ip"}
func (d *Datastore) NewHost(host *kolide.Host) (*kolide.Host, error) {
func (d *Datastore) NewHost(host *fleet.Host) (*fleet.Host, error) {
sqlStatement := `
INSERT INTO hosts (
osquery_host_id,
@ -58,7 +58,7 @@ func (d *Datastore) NewHost(host *kolide.Host) (*kolide.Host, error) {
}
// TODO needs test
func (d *Datastore) SaveHost(host *kolide.Host) error {
func (d *Datastore) SaveHost(host *fleet.Host) error {
sqlStatement := `
UPDATE hosts SET
detail_update_time = ?,
@ -143,7 +143,7 @@ func (d *Datastore) SaveHost(host *kolide.Host) error {
return nil
}
func (d *Datastore) saveHostPackStats(host *kolide.Host) error {
func (d *Datastore) saveHostPackStats(host *fleet.Host) error {
if err := d.withRetryTxx(func(tx *sqlx.Tx) error {
sql := `
DELETE FROM scheduled_query_stats
@ -209,7 +209,7 @@ func (d *Datastore) saveHostPackStats(host *kolide.Host) error {
return nil
}
func (d *Datastore) loadHostPackStats(host *kolide.Host) error {
func (d *Datastore) loadHostPackStats(host *fleet.Host) error {
sql := `
SELECT
sqs.scheduled_query_id,
@ -234,12 +234,12 @@ FROM scheduled_query_stats sqs
JOIN queries q ON (sq.query_name = q.name)
WHERE host_id = ?
`
var stats []kolide.ScheduledQueryStats
var stats []fleet.ScheduledQueryStats
if err := d.db.Select(&stats, sql, host.ID); err != nil {
return errors.Wrap(err, "load pack stats")
}
packs := map[uint]kolide.PackStats{}
packs := map[uint]fleet.PackStats{}
for _, query := range stats {
pack := packs[query.PackID]
pack.PackName = query.PackName
@ -263,14 +263,14 @@ func (d *Datastore) DeleteHost(hid uint) error {
return nil
}
func (d *Datastore) Host(id uint) (*kolide.Host, error) {
func (d *Datastore) Host(id uint) (*fleet.Host, error) {
sqlStatement := `
SELECT h.*, t.name AS team_name, (SELECT additional FROM host_additional WHERE host_id = h.id) AS additional
FROM hosts h LEFT JOIN teams t ON (h.team_id = t.id)
WHERE h.id = ?
LIMIT 1
`
host := &kolide.Host{}
host := &fleet.Host{}
err := d.db.Get(host, sqlStatement, id)
if err != nil {
return nil, errors.Wrap(err, "get host by id")
@ -282,7 +282,7 @@ func (d *Datastore) Host(id uint) (*kolide.Host, error) {
return host, nil
}
func (d *Datastore) ListHosts(filter kolide.TeamFilter, opt kolide.HostListOptions) ([]*kolide.Host, error) {
func (d *Datastore) ListHosts(filter fleet.TeamFilter, opt fleet.HostListOptions) ([]*fleet.Host, error) {
sql := `SELECT
h.id,
h.osquery_host_id,
@ -354,10 +354,10 @@ func (d *Datastore) ListHosts(filter kolide.TeamFilter, opt kolide.HostListOptio
sql += "AND DATE_ADD(h.created_at, INTERVAL 1 DAY) >= ?"
params = append(params, time.Now())
case "online":
sql += fmt.Sprintf("AND DATE_ADD(h.seen_time, INTERVAL LEAST(h.distributed_interval, h.config_tls_refresh) + %d SECOND) > ?", kolide.OnlineIntervalBuffer)
sql += fmt.Sprintf("AND DATE_ADD(h.seen_time, INTERVAL LEAST(h.distributed_interval, h.config_tls_refresh) + %d SECOND) > ?", fleet.OnlineIntervalBuffer)
params = append(params, time.Now())
case "offline":
sql += fmt.Sprintf("AND DATE_ADD(h.seen_time, INTERVAL LEAST(h.distributed_interval, h.config_tls_refresh) + %d SECOND) <= ? AND DATE_ADD(h.seen_time, INTERVAL 30 DAY) >= ?", kolide.OnlineIntervalBuffer)
sql += fmt.Sprintf("AND DATE_ADD(h.seen_time, INTERVAL LEAST(h.distributed_interval, h.config_tls_refresh) + %d SECOND) <= ? AND DATE_ADD(h.seen_time, INTERVAL 30 DAY) >= ?", fleet.OnlineIntervalBuffer)
params = append(params, time.Now(), time.Now())
case "mia":
sql += "AND DATE_ADD(h.seen_time, INTERVAL 30 DAY) <= ?"
@ -368,7 +368,7 @@ func (d *Datastore) ListHosts(filter kolide.TeamFilter, opt kolide.HostListOptio
sql = appendListOptionsToSQL(sql, opt.ListOptions)
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
if err := d.db.Select(&hosts, sql, params...); err != nil {
return nil, errors.Wrap(err, "list hosts")
}
@ -389,7 +389,7 @@ func (d *Datastore) CleanupIncomingHosts(now time.Time) error {
return nil
}
func (d *Datastore) GenerateHostStatusStatistics(filter kolide.TeamFilter, now time.Time) (online, offline, mia, new uint, e error) {
func (d *Datastore) GenerateHostStatusStatistics(filter fleet.TeamFilter, now time.Time) (online, offline, mia, new uint, e error) {
// The logic in this function should remain synchronized with
// host.Status and CountHostsInTargets
@ -401,7 +401,7 @@ func (d *Datastore) GenerateHostStatusStatistics(filter kolide.TeamFilter, now t
COALESCE(SUM(CASE WHEN DATE_ADD(created_at, INTERVAL 1 DAY) >= ? THEN 1 ELSE 0 END), 0) new
FROM hosts WHERE %s
LIMIT 1;
`, kolide.OnlineIntervalBuffer, kolide.OnlineIntervalBuffer,
`, fleet.OnlineIntervalBuffer, fleet.OnlineIntervalBuffer,
d.whereFilterHostsByTeams(filter, "hosts"),
)
@ -425,12 +425,12 @@ func (d *Datastore) GenerateHostStatusStatistics(filter kolide.TeamFilter, now t
}
// EnrollHost enrolls a host
func (d *Datastore) EnrollHost(osqueryHostID, nodeKey string, teamID *uint, cooldown time.Duration) (*kolide.Host, error) {
func (d *Datastore) EnrollHost(osqueryHostID, nodeKey string, teamID *uint, cooldown time.Duration) (*fleet.Host, error) {
if osqueryHostID == "" {
return nil, fmt.Errorf("missing osquery host identifier")
}
var host kolide.Host
var host fleet.Host
err := d.withRetryTxx(func(tx *sqlx.Tx) error {
zeroTime := time.Unix(0, 0).Add(24 * time.Hour)
@ -505,7 +505,7 @@ func (d *Datastore) EnrollHost(osqueryHostID, nodeKey string, teamID *uint, cool
return &host, nil
}
func (d *Datastore) AuthenticateHost(nodeKey string) (*kolide.Host, error) {
func (d *Datastore) AuthenticateHost(nodeKey string) (*fleet.Host, error) {
// Select everything besides `additional`
sqlStatement := `
SELECT
@ -550,7 +550,7 @@ func (d *Datastore) AuthenticateHost(nodeKey string) (*kolide.Host, error) {
LIMIT 1
`
host := &kolide.Host{}
host := &fleet.Host{}
if err := d.db.Get(host, sqlStatement, nodeKey); err != nil {
switch err {
case sql.ErrNoRows:
@ -563,7 +563,7 @@ func (d *Datastore) AuthenticateHost(nodeKey string) (*kolide.Host, error) {
return host, nil
}
func (d *Datastore) MarkHostSeen(host *kolide.Host, t time.Time) error {
func (d *Datastore) MarkHostSeen(host *fleet.Host, t time.Time) error {
sqlStatement := `
UPDATE hosts SET
seen_time = ?
@ -607,7 +607,7 @@ func (d *Datastore) MarkHostsSeen(hostIDs []uint, t time.Time) error {
return nil
}
func (d *Datastore) searchHostsWithOmits(filter kolide.TeamFilter, query string, omit ...uint) ([]*kolide.Host, error) {
func (d *Datastore) searchHostsWithOmits(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Host, error) {
hostQuery := transformQuery(query)
ipQuery := `"` + query + `"`
@ -630,7 +630,7 @@ func (d *Datastore) searchHostsWithOmits(filter kolide.TeamFilter, query string,
}
sql = d.db.Rebind(sql)
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
err = d.db.Select(&hosts, sql, args...)
if err != nil {
@ -640,7 +640,7 @@ func (d *Datastore) searchHostsWithOmits(filter kolide.TeamFilter, query string,
return hosts, nil
}
func (d *Datastore) searchHostsDefault(filter kolide.TeamFilter, omit ...uint) ([]*kolide.Host, error) {
func (d *Datastore) searchHostsDefault(filter fleet.TeamFilter, omit ...uint) ([]*fleet.Host, error) {
sql := fmt.Sprintf(`
SELECT * FROM hosts
WHERE id NOT in (?) AND %s
@ -659,7 +659,7 @@ func (d *Datastore) searchHostsDefault(filter kolide.TeamFilter, omit ...uint) (
}
}
var hosts []*kolide.Host
var hosts []*fleet.Host
sql, args, err := sqlx.In(sql, in)
if err != nil {
return nil, errors.Wrap(err, "searching default hosts")
@ -674,7 +674,7 @@ func (d *Datastore) searchHostsDefault(filter kolide.TeamFilter, omit ...uint) (
// SearchHosts find hosts by query containing an IP address, a host name or UUID.
// Optionally pass a list of IDs to omit from the search
func (d *Datastore) SearchHosts(filter kolide.TeamFilter, query string, omit ...uint) ([]*kolide.Host, error) {
func (d *Datastore) SearchHosts(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Host, error) {
hostQuery := transformQuery(query)
if !queryMinLength(hostQuery) {
return d.searchHostsDefault(filter, omit...)
@ -698,7 +698,7 @@ func (d *Datastore) SearchHosts(filter kolide.TeamFilter, query string, omit ...
`, d.whereFilterHostsByTeams(filter, "hosts"),
)
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
if err := d.db.Select(&hosts, sql, hostQuery, ipQuery); err != nil {
return nil, errors.Wrap(err, "searching hosts")
}
@ -707,7 +707,7 @@ func (d *Datastore) SearchHosts(filter kolide.TeamFilter, query string, omit ...
}
func (d *Datastore) HostIDsByName(filter kolide.TeamFilter, hostnames []string) ([]uint, error) {
func (d *Datastore) HostIDsByName(filter fleet.TeamFilter, hostnames []string) ([]uint, error) {
if len(hostnames) == 0 {
return []uint{}, nil
}
@ -732,13 +732,13 @@ func (d *Datastore) HostIDsByName(filter kolide.TeamFilter, hostnames []string)
}
func (d *Datastore) HostByIdentifier(identifier string) (*kolide.Host, error) {
func (d *Datastore) HostByIdentifier(identifier string) (*fleet.Host, error) {
sql := `
SELECT * FROM hosts
WHERE ? IN (host_name, osquery_host_id, node_key, uuid)
LIMIT 1
`
host := &kolide.Host{}
host := &fleet.Host{}
err := d.db.Get(host, sql, identifier)
if err != nil {
return nil, errors.Wrap(err, "get host by identifier")
@ -772,7 +772,7 @@ func (d *Datastore) AddHostsToTeam(teamID *uint, hostIDs []uint) error {
return nil
}
func (d *Datastore) SaveHostAdditional(host *kolide.Host) error {
func (d *Datastore) SaveHostAdditional(host *fleet.Host) error {
sql := `
INSERT INTO host_additional (host_id, additional)
VALUES (?, ?)

View File

@ -5,7 +5,7 @@ import (
"fmt"
"strings"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
@ -13,7 +13,7 @@ import (
var inviteSearchColumns = []string{"name", "email"}
// NewInvite generates a new invitation.
func (d *Datastore) NewInvite(i *kolide.Invite) (*kolide.Invite, error) {
func (d *Datastore) NewInvite(i *fleet.Invite) (*fleet.Invite, error) {
sqlStmt := `
INSERT INTO invites ( invited_by, email, name, position, token, sso_enabled, global_role )
VALUES ( ?, ?, ?, ?, ?, ?, ?)
@ -31,7 +31,7 @@ func (d *Datastore) NewInvite(i *kolide.Invite) (*kolide.Invite, error) {
i.ID = uint(id)
if len(i.Teams) == 0 {
i.Teams = []kolide.UserTeam{}
i.Teams = []fleet.UserTeam{}
return i, nil
}
@ -52,9 +52,9 @@ func (d *Datastore) NewInvite(i *kolide.Invite) (*kolide.Invite, error) {
}
// ListInvites lists all invites in the Fleet database. Supply query options
// using the opt parameter. See kolide.ListOptions
func (d *Datastore) ListInvites(opt kolide.ListOptions) ([]*kolide.Invite, error) {
invites := []*kolide.Invite{}
// using the opt parameter. See fleet.ListOptions
func (d *Datastore) ListInvites(opt fleet.ListOptions) ([]*fleet.Invite, error) {
invites := []*fleet.Invite{}
query := "SELECT * FROM invites WHERE true"
query, params := searchLike(query, nil, opt.MatchQuery, inviteSearchColumns...)
query = appendListOptionsToSQL(query, opt)
@ -74,8 +74,8 @@ func (d *Datastore) ListInvites(opt kolide.ListOptions) ([]*kolide.Invite, error
}
// Invite returns Invite identified by id.
func (d *Datastore) Invite(id uint) (*kolide.Invite, error) {
var invite kolide.Invite
func (d *Datastore) Invite(id uint) (*fleet.Invite, error) {
var invite fleet.Invite
err := d.db.Get(&invite, "SELECT * FROM invites WHERE id = ?", id)
if err == sql.ErrNoRows {
return nil, notFound("Invite").WithID(id)
@ -83,7 +83,7 @@ func (d *Datastore) Invite(id uint) (*kolide.Invite, error) {
return nil, errors.Wrap(err, "select invite by ID")
}
if err := d.loadTeamsForInvites([]*kolide.Invite{&invite}); err != nil {
if err := d.loadTeamsForInvites([]*fleet.Invite{&invite}); err != nil {
return nil, errors.Wrap(err, "load teams")
}
@ -91,8 +91,8 @@ func (d *Datastore) Invite(id uint) (*kolide.Invite, error) {
}
// InviteByEmail finds an Invite with a particular email, if one exists.
func (d *Datastore) InviteByEmail(email string) (*kolide.Invite, error) {
var invite kolide.Invite
func (d *Datastore) InviteByEmail(email string) (*fleet.Invite, error) {
var invite fleet.Invite
err := d.db.Get(&invite, "SELECT * FROM invites WHERE email = ?", email)
if err == sql.ErrNoRows {
return nil, notFound("Invite").
@ -101,7 +101,7 @@ func (d *Datastore) InviteByEmail(email string) (*kolide.Invite, error) {
return nil, errors.Wrap(err, "sqlx get invite by email")
}
if err := d.loadTeamsForInvites([]*kolide.Invite{&invite}); err != nil {
if err := d.loadTeamsForInvites([]*fleet.Invite{&invite}); err != nil {
return nil, errors.Wrap(err, "load teams")
}
@ -109,8 +109,8 @@ func (d *Datastore) InviteByEmail(email string) (*kolide.Invite, error) {
}
// InviteByToken finds an Invite with a particular token, if one exists.
func (d *Datastore) InviteByToken(token string) (*kolide.Invite, error) {
var invite kolide.Invite
func (d *Datastore) InviteByToken(token string) (*fleet.Invite, error) {
var invite fleet.Invite
err := d.db.Get(&invite, "SELECT * FROM invites WHERE token = ?", token)
if err == sql.ErrNoRows {
return nil, notFound("Invite").
@ -119,7 +119,7 @@ func (d *Datastore) InviteByToken(token string) (*kolide.Invite, error) {
return nil, errors.Wrap(err, "sqlx get invite by token")
}
if err := d.loadTeamsForInvites([]*kolide.Invite{&invite}); err != nil {
if err := d.loadTeamsForInvites([]*fleet.Invite{&invite}); err != nil {
return nil, errors.Wrap(err, "load teams")
}
@ -130,15 +130,15 @@ func (d *Datastore) DeleteInvite(id uint) error {
return d.deleteEntity("invites", id)
}
func (d *Datastore) loadTeamsForInvites(invites []*kolide.Invite) error {
func (d *Datastore) loadTeamsForInvites(invites []*fleet.Invite) error {
inviteIDs := make([]uint, 0, len(invites)+1)
// Make sure the slice is never empty for IN by filling a nonexistent ID
inviteIDs = append(inviteIDs, 0)
idToInvite := make(map[uint]*kolide.Invite, len(invites))
idToInvite := make(map[uint]*fleet.Invite, len(invites))
for _, u := range invites {
// Initialize empty slice so we get an array in JSON responses instead
// of null if it is empty
u.Teams = []kolide.UserTeam{}
u.Teams = []fleet.UserTeam{}
// Track IDs for queries and matching
inviteIDs = append(inviteIDs, u.ID)
idToInvite[u.ID] = u
@ -156,7 +156,7 @@ func (d *Datastore) loadTeamsForInvites(invites []*kolide.Invite) error {
}
var rows []struct {
kolide.UserTeam
fleet.UserTeam
InviteID uint `db:"invite_id"`
}
if err := d.db.Select(&rows, sql, args...); err != nil {

View File

@ -6,12 +6,12 @@ import (
"strings"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func (d *Datastore) ApplyLabelSpecs(specs []*kolide.LabelSpec) (err error) {
func (d *Datastore) ApplyLabelSpecs(specs []*fleet.LabelSpec) (err error) {
err = d.withRetryTxx(func(tx *sqlx.Tx) error {
sql := `
INSERT INTO labels (
@ -44,8 +44,8 @@ func (d *Datastore) ApplyLabelSpecs(specs []*kolide.LabelSpec) (err error) {
return errors.Wrap(err, "exec ApplyLabelSpecs insert")
}
if s.LabelType == kolide.LabelTypeBuiltIn ||
s.LabelMembershipType != kolide.LabelMembershipTypeManual {
if s.LabelType == fleet.LabelTypeBuiltIn ||
s.LabelMembershipType != fleet.LabelMembershipTypeManual {
// No need to update membership
continue
}
@ -109,8 +109,8 @@ func batchHostnames(hostnames []string) [][]string {
return batches
}
func (d *Datastore) GetLabelSpecs() ([]*kolide.LabelSpec, error) {
var specs []*kolide.LabelSpec
func (d *Datastore) GetLabelSpecs() ([]*fleet.LabelSpec, error) {
var specs []*fleet.LabelSpec
// Get basic specs
query := "SELECT name, description, query, platform, label_type, label_membership_type FROM labels"
if err := d.db.Select(&specs, query); err != nil {
@ -118,8 +118,8 @@ func (d *Datastore) GetLabelSpecs() ([]*kolide.LabelSpec, error) {
}
for _, spec := range specs {
if spec.LabelType != kolide.LabelTypeBuiltIn &&
spec.LabelMembershipType == kolide.LabelMembershipTypeManual {
if spec.LabelType != fleet.LabelTypeBuiltIn &&
spec.LabelMembershipType == fleet.LabelMembershipTypeManual {
if err := d.getLabelHostnames(spec); err != nil {
return nil, err
}
@ -129,8 +129,8 @@ func (d *Datastore) GetLabelSpecs() ([]*kolide.LabelSpec, error) {
return specs, nil
}
func (d *Datastore) GetLabelSpec(name string) (*kolide.LabelSpec, error) {
var specs []*kolide.LabelSpec
func (d *Datastore) GetLabelSpec(name string) (*fleet.LabelSpec, error) {
var specs []*fleet.LabelSpec
query := `
SELECT name, description, query, platform, label_type, label_membership_type
FROM labels
@ -147,8 +147,8 @@ WHERE name = ?
}
spec := specs[0]
if spec.LabelType != kolide.LabelTypeBuiltIn &&
spec.LabelMembershipType == kolide.LabelMembershipTypeManual {
if spec.LabelType != fleet.LabelTypeBuiltIn &&
spec.LabelMembershipType == fleet.LabelMembershipTypeManual {
err := d.getLabelHostnames(spec)
if err != nil {
return nil, err
@ -158,7 +158,7 @@ WHERE name = ?
return spec, nil
}
func (d *Datastore) getLabelHostnames(label *kolide.LabelSpec) error {
func (d *Datastore) getLabelHostnames(label *fleet.LabelSpec) error {
sql := `
SELECT host_name
FROM hosts
@ -176,8 +176,8 @@ func (d *Datastore) getLabelHostnames(label *kolide.LabelSpec) error {
return nil
}
// NewLabel creates a new kolide.Label
func (d *Datastore) NewLabel(label *kolide.Label, opts ...kolide.OptionalArg) (*kolide.Label, error) {
// NewLabel creates a new fleet.Label
func (d *Datastore) NewLabel(label *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
db := d.getTransaction(opts)
query := `
INSERT INTO labels (
@ -208,7 +208,7 @@ func (d *Datastore) NewLabel(label *kolide.Label, opts ...kolide.OptionalArg) (*
}
func (d *Datastore) SaveLabel(label *kolide.Label) (*kolide.Label, error) {
func (d *Datastore) SaveLabel(label *fleet.Label) (*fleet.Label, error) {
query := `
UPDATE labels SET
name = ?,
@ -222,18 +222,18 @@ func (d *Datastore) SaveLabel(label *kolide.Label) (*kolide.Label, error) {
return label, nil
}
// DeleteLabel deletes a kolide.Label
// DeleteLabel deletes a fleet.Label
func (d *Datastore) DeleteLabel(name string) error {
return d.deleteEntityByName("labels", name)
}
// Label returns a kolide.Label identified by lid if one exists.
func (d *Datastore) Label(lid uint) (*kolide.Label, error) {
// Label returns a fleet.Label identified by lid if one exists.
func (d *Datastore) Label(lid uint) (*fleet.Label, error) {
sql := `
SELECT * FROM labels
WHERE id = ?
`
label := &kolide.Label{}
label := &fleet.Label{}
if err := d.db.Get(label, sql, lid); err != nil {
return nil, errors.Wrap(err, "selecting label")
@ -242,8 +242,8 @@ func (d *Datastore) Label(lid uint) (*kolide.Label, error) {
return label, nil
}
// ListLabels returns all labels limited or sorted by kolide.ListOptions.
func (d *Datastore) ListLabels(filter kolide.TeamFilter, opt kolide.ListOptions) ([]*kolide.Label, error) {
// ListLabels returns all labels limited or sorted by fleet.ListOptions.
func (d *Datastore) ListLabels(filter fleet.TeamFilter, opt fleet.ListOptions) ([]*fleet.Label, error) {
query := fmt.Sprintf(`
SELECT *,
(SELECT COUNT(1) FROM label_membership lm JOIN hosts h ON (lm.host_id = h.id) WHERE label_id = l.id AND %s) AS host_count
@ -252,7 +252,7 @@ func (d *Datastore) ListLabels(filter kolide.TeamFilter, opt kolide.ListOptions)
)
query = appendListOptionsToSQL(query, opt)
labels := []*kolide.Label{}
labels := []*fleet.Label{}
if err := d.db.Select(&labels, query); err != nil {
// it's ok if no labels exist
@ -265,7 +265,7 @@ func (d *Datastore) ListLabels(filter kolide.TeamFilter, opt kolide.ListOptions)
return labels, nil
}
func (d *Datastore) LabelQueriesForHost(host *kolide.Host, cutoff time.Time) (map[string]string, error) {
func (d *Datastore) LabelQueriesForHost(host *fleet.Host, cutoff time.Time) (map[string]string, error) {
var rows *sql.Rows
var err error
if host.LabelUpdateTime.Before(cutoff) {
@ -276,7 +276,7 @@ func (d *Datastore) LabelQueriesForHost(host *kolide.Host, cutoff time.Time) (ma
WHERE platform = ? OR platform = ''
AND label_membership_type = ?
`
rows, err = d.db.Query(sql, host.Platform, kolide.LabelMembershipTypeDynamic)
rows, err = d.db.Query(sql, host.Platform, fleet.LabelMembershipTypeDynamic)
} else {
// Retrieve all labels (with matching platform) iff there is a label
// that has been created since this host last reported label query
@ -293,7 +293,7 @@ func (d *Datastore) LabelQueriesForHost(host *kolide.Host, cutoff time.Time) (ma
host.Platform,
host.LabelUpdateTime,
host.Platform,
kolide.LabelMembershipTypeDynamic,
fleet.LabelMembershipTypeDynamic,
)
}
@ -318,7 +318,7 @@ func (d *Datastore) LabelQueriesForHost(host *kolide.Host, cutoff time.Time) (ma
}
func (d *Datastore) RecordLabelQueryExecutions(host *kolide.Host, results map[uint]bool, updated time.Time) error {
func (d *Datastore) RecordLabelQueryExecutions(host *fleet.Host, results map[uint]bool, updated time.Time) error {
// Loop through results, collecting which labels we need to insert/update,
// and which we need to delete
vals := []interface{}{}
@ -372,15 +372,15 @@ func (d *Datastore) RecordLabelQueryExecutions(host *kolide.Host, results map[ui
return nil
}
// ListLabelsForHost returns a list of kolide.Label for a given host id.
func (d *Datastore) ListLabelsForHost(hid uint) ([]*kolide.Label, error) {
// ListLabelsForHost returns a list of fleet.Label for a given host id.
func (d *Datastore) ListLabelsForHost(hid uint) ([]*fleet.Label, error) {
sqlStatement := `
SELECT labels.* from labels JOIN label_membership lm
WHERE lm.host_id = ?
AND lm.label_id = labels.id
`
labels := []*kolide.Label{}
labels := []*fleet.Label{}
err := d.db.Select(&labels, sqlStatement, hid)
if err != nil {
return nil, errors.Wrap(err, "selecting host labels")
@ -390,9 +390,9 @@ func (d *Datastore) ListLabelsForHost(hid uint) ([]*kolide.Label, error) {
}
// ListHostsInLabel returns a list of kolide.Host that are associated
// with kolide.Label referened by Label ID
func (d *Datastore) ListHostsInLabel(filter kolide.TeamFilter, lid uint, opt kolide.HostListOptions) ([]*kolide.Host, error) {
// ListHostsInLabel returns a list of fleet.Host that are associated
// with fleet.Label referened by Label ID
func (d *Datastore) ListHostsInLabel(filter fleet.TeamFilter, lid uint, opt fleet.HostListOptions) ([]*fleet.Host, error) {
sql := fmt.Sprintf(`
SELECT h.*
FROM label_membership lm
@ -407,7 +407,7 @@ func (d *Datastore) ListHostsInLabel(filter kolide.TeamFilter, lid uint, opt kol
sql, params = searchLike(sql, params, opt.MatchQuery, hostSearchColumns...)
sql = appendListOptionsToSQL(sql, opt.ListOptions)
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
err := d.db.Select(&hosts, sql, params...)
if err != nil {
return nil, errors.Wrap(err, "selecting label query executions")
@ -415,9 +415,9 @@ func (d *Datastore) ListHostsInLabel(filter kolide.TeamFilter, lid uint, opt kol
return hosts, nil
}
func (d *Datastore) ListUniqueHostsInLabels(filter kolide.TeamFilter, labels []uint) ([]*kolide.Host, error) {
func (d *Datastore) ListUniqueHostsInLabels(filter fleet.TeamFilter, labels []uint) ([]*fleet.Host, error) {
if len(labels) == 0 {
return []*kolide.Host{}, nil
return []*fleet.Host{}, nil
}
sqlStatement := fmt.Sprintf(`
@ -435,7 +435,7 @@ func (d *Datastore) ListUniqueHostsInLabels(filter kolide.TeamFilter, labels []u
}
query = d.db.Rebind(query)
hosts := []*kolide.Host{}
hosts := []*fleet.Host{}
err = d.db.Select(&hosts, query, args...)
if err != nil {
return nil, errors.Wrap(err, "listing unique hosts in labels")
@ -445,7 +445,7 @@ func (d *Datastore) ListUniqueHostsInLabels(filter kolide.TeamFilter, labels []u
}
func (d *Datastore) searchLabelsWithOmits(filter kolide.TeamFilter, query string, omit ...uint) ([]*kolide.Label, error) {
func (d *Datastore) searchLabelsWithOmits(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Label, error) {
transformedQuery := transformQuery(query)
sqlStatement := fmt.Sprintf(`
@ -471,7 +471,7 @@ func (d *Datastore) searchLabelsWithOmits(filter kolide.TeamFilter, query string
sql = d.db.Rebind(sql)
matches := []*kolide.Label{}
matches := []*fleet.Label{}
err = d.db.Select(&matches, sql, args...)
if err != nil {
return nil, errors.Wrap(err, "selecting labels with omits")
@ -488,7 +488,7 @@ func (d *Datastore) searchLabelsWithOmits(filter kolide.TeamFilter, query string
// When we search labels, we always want to make sure that the All Hosts label
// is included in the results set. Sometimes it already is and we don't need to
// add it, sometimes it's not so we explicitly add it.
func (d *Datastore) addAllHostsLabelToList(filter kolide.TeamFilter, labels []*kolide.Label, omit ...uint) ([]*kolide.Label, error) {
func (d *Datastore) addAllHostsLabelToList(filter fleet.TeamFilter, labels []*fleet.Label, omit ...uint) ([]*fleet.Label, error) {
sql := fmt.Sprintf(`
SELECT *,
(SELECT COUNT(1)
@ -503,8 +503,8 @@ func (d *Datastore) addAllHostsLabelToList(filter kolide.TeamFilter, labels []*k
`, d.whereFilterHostsByTeams(filter, "h"),
)
var allHosts kolide.Label
if err := d.db.Get(&allHosts, sql, kolide.LabelTypeBuiltIn); err != nil {
var allHosts fleet.Label
if err := d.db.Get(&allHosts, sql, fleet.LabelTypeBuiltIn); err != nil {
return nil, errors.Wrap(err, "get all hosts label")
}
@ -523,7 +523,7 @@ func (d *Datastore) addAllHostsLabelToList(filter kolide.TeamFilter, labels []*k
return append(labels, &allHosts), nil
}
func (d *Datastore) searchLabelsDefault(filter kolide.TeamFilter, omit ...uint) ([]*kolide.Label, error) {
func (d *Datastore) searchLabelsDefault(filter fleet.TeamFilter, omit ...uint) ([]*fleet.Label, error) {
sql := fmt.Sprintf(`
SELECT *,
(SELECT COUNT(1)
@ -548,7 +548,7 @@ func (d *Datastore) searchLabelsDefault(filter kolide.TeamFilter, omit ...uint)
}
}
var labels []*kolide.Label
var labels []*fleet.Label
sql, args, err := sqlx.In(sql, in)
if err != nil {
return nil, errors.Wrap(err, "searching default labels")
@ -566,8 +566,8 @@ func (d *Datastore) searchLabelsDefault(filter kolide.TeamFilter, omit ...uint)
return labels, nil
}
// SearchLabels performs wildcard searches on kolide.Label name
func (d *Datastore) SearchLabels(filter kolide.TeamFilter, query string, omit ...uint) ([]*kolide.Label, error) {
// SearchLabels performs wildcard searches on fleet.Label name
func (d *Datastore) SearchLabels(filter fleet.TeamFilter, query string, omit ...uint) ([]*fleet.Label, error) {
transformedQuery := transformQuery(query)
if !queryMinLength(transformedQuery) {
return d.searchLabelsDefault(filter, omit...)
@ -595,7 +595,7 @@ func (d *Datastore) SearchLabels(filter kolide.TeamFilter, query string, omit ..
`, d.whereFilterHostsByTeams(filter, "h"),
)
matches := []*kolide.Label{}
matches := []*fleet.Label{}
if err := d.db.Select(&matches, sql, transformedQuery); err != nil {
return nil, errors.Wrap(err, "selecting labels for search")
}

View File

@ -3,7 +3,7 @@ package data
import (
"database/sql"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
@ -22,7 +22,7 @@ func Up_20170301093653(tx *sql.Tx) error {
(SELECT id as label_id FROM labels WHERE name = 'All Hosts' AND label_type = ?)
FROM hosts
`,
kolide.LabelTypeBuiltIn)
fleet.LabelTypeBuiltIn)
if err != nil {
return errors.Wrap(err, "adding hosts to 'All Hosts'")
}

View File

@ -3,7 +3,7 @@ package data
import (
"database/sql"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func init() {
@ -19,7 +19,7 @@ func Up_20170314151620(tx *sql.Tx) error {
WHERE name = 'CentOS Linux' AND label_type = ?
`
_, err := tx.Exec(sql, label_query, kolide.LabelTypeBuiltIn)
_, err := tx.Exec(sql, label_query, fleet.LabelTypeBuiltIn)
if err != nil {
return err
}

View File

@ -3,7 +3,7 @@ package data
import (
"database/sql"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
@ -17,7 +17,7 @@ func Up_20210330130314(tx *sql.Tx) error {
// having the same hardware UUID) the old label query would never run again
// and a host could show up in multiple of the built-in platform labels.
sql := "UPDATE labels SET platform = '' WHERE label_type = ?"
if _, err := tx.Exec(sql, kolide.LabelTypeBuiltIn); err != nil {
if _, err := tx.Exec(sql, fleet.LabelTypeBuiltIn); err != nil {
return errors.Wrap(err, "update labels")
}
@ -38,8 +38,8 @@ func Up_20210330130314(tx *sql.Tx) error {
"All Red Hat Enterprise Linux hosts",
"SELECT 1 FROM os_version WHERE name LIKE '%red hat%'",
"",
kolide.LabelTypeBuiltIn,
kolide.LabelMembershipTypeDynamic,
fleet.LabelTypeBuiltIn,
fleet.LabelMembershipTypeDynamic,
); err != nil {
return errors.Wrap(err, "add red hat label")
}

View File

@ -4,7 +4,7 @@ import (
"database/sql"
"fmt"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
)
func init() {
@ -23,7 +23,7 @@ func Up_20161118212557(tx *sql.Tx) error {
"`description` varchar(255) DEFAULT NULL," +
"`query` varchar(255) NOT NULL," +
"`platform` varchar(255) DEFAULT NULL," +
fmt.Sprintf("`label_type` INT UNSIGNED NOT NULL DEFAULT %d,", kolide.LabelTypeBuiltIn) +
fmt.Sprintf("`label_type` INT UNSIGNED NOT NULL DEFAULT %d,", fleet.LabelTypeBuiltIn) +
"PRIMARY KEY (`id`)," +
"UNIQUE KEY `idx_label_unique_name` (`name`)," +
"FULLTEXT KEY `labels_search` (`name`)" +

View File

@ -4,7 +4,7 @@ import (
"database/sql"
"encoding/json"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/jmoiron/sqlx/reflectx"
"github.com/pkg/errors"
@ -47,17 +47,17 @@ func copyOptions(tx *sql.Tx) (json.RawMessage, error) {
return nil, errors.Wrap(err, "selecting options")
}
opt := &kolide.AgentOptions{
Overrides: kolide.AgentOptionsOverrides{
opt := &fleet.AgentOptions{
Overrides: fleet.AgentOptionsOverrides{
Platforms: make(map[string]json.RawMessage),
},
}
for _, row := range rows {
switch row.OverrideType {
case 0: // was kolide.OptionOverrideTypeDefault
case 0: // was fleet.OptionOverrideTypeDefault
opt.Config = json.RawMessage(row.Options)
case 1: // was kolide.OptionOverrideTypePlatform
case 1: // was fleet.OptionOverrideTypePlatform
opt.Overrides.Platforms[row.OverrideIdentifier] = json.RawMessage(row.Options)
default:

View File

@ -19,7 +19,7 @@ import (
"github.com/fleetdm/fleet/server/config"
"github.com/fleetdm/fleet/server/datastore/mysql/migrations/data"
"github.com/fleetdm/fleet/server/datastore/mysql/migrations/tables"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/go-sql-driver/mysql"
@ -37,7 +37,7 @@ var (
columnCharsRegexp = regexp.MustCompile(`[^\w-]`)
)
// Datastore is an implementation of kolide.Datastore interface backed by
// Datastore is an implementation of fleet.Datastore interface backed by
// MySQL
type Datastore struct {
db *sqlx.DB
@ -52,7 +52,7 @@ type dbfunctions interface {
Select(dest interface{}, query string, args ...interface{}) error
}
func (d *Datastore) getTransaction(opts []kolide.OptionalArg) dbfunctions {
func (d *Datastore) getTransaction(opts []fleet.OptionalArg) dbfunctions {
var result dbfunctions = d.db
for _, opt := range opts {
switch t := opt().(type) {
@ -203,7 +203,7 @@ func New(config config.MysqlConfig, c clock.Clock, opts ...DBOption) (*Datastore
}
func (d *Datastore) Begin() (kolide.Transaction, error) {
func (d *Datastore) Begin() (fleet.Transaction, error) {
return d.db.Beginx()
}
@ -219,7 +219,7 @@ func (d *Datastore) MigrateData() error {
return data.MigrationClient.Up(d.db.DB, "")
}
func (d *Datastore) MigrationStatus() (kolide.MigrationStatus, error) {
func (d *Datastore) MigrationStatus() (fleet.MigrationStatus, error) {
if tables.MigrationClient.Migrations == nil || data.MigrationClient.Migrations == nil {
return 0, errors.New("unexpected nil migrations list")
}
@ -246,14 +246,14 @@ func (d *Datastore) MigrationStatus() (kolide.MigrationStatus, error) {
switch {
case currentDataVersion == 0 && currentTablesVersion == 0:
return kolide.NoMigrationsCompleted, nil
return fleet.NoMigrationsCompleted, nil
case currentTablesVersion != lastTablesMigration.Version ||
currentDataVersion != lastDataMigration.Version:
return kolide.SomeMigrationsCompleted, nil
return fleet.SomeMigrationsCompleted, nil
default:
return kolide.AllMigrationsCompleted, nil
return fleet.AllMigrationsCompleted, nil
}
}
@ -311,10 +311,10 @@ func sanitizeColumn(col string) string {
return columnCharsRegexp.ReplaceAllString(col, "")
}
func appendListOptionsToSQL(sql string, opts kolide.ListOptions) string {
func appendListOptionsToSQL(sql string, opts fleet.ListOptions) string {
if opts.OrderKey != "" {
direction := "ASC"
if opts.OrderDirection == kolide.OrderDescending {
if opts.OrderDirection == fleet.OrderDescending {
direction = "DESC"
}
orderKey := sanitizeColumn(opts.OrderKey)
@ -344,7 +344,7 @@ func appendListOptionsToSQL(sql string, opts kolide.ListOptions) string {
//
// filter provides the filtering parameters that should be used. hostKey is the
// name/alias of the hosts table to use in generating the SQL.
func (d *Datastore) whereFilterHostsByTeams(filter kolide.TeamFilter, hostKey string) string {
func (d *Datastore) whereFilterHostsByTeams(filter fleet.TeamFilter, hostKey string) string {
if filter.User == nil {
// This is likely unintentional, however we would like to return no
// results rather than panicking or returning some other error. At least
@ -356,10 +356,10 @@ func (d *Datastore) whereFilterHostsByTeams(filter kolide.TeamFilter, hostKey st
if filter.User.GlobalRole != nil {
switch *filter.User.GlobalRole {
case kolide.RoleAdmin, kolide.RoleMaintainer:
case fleet.RoleAdmin, fleet.RoleMaintainer:
return "TRUE"
case kolide.RoleObserver:
case fleet.RoleObserver:
if filter.IncludeObserver {
return "TRUE"
} else {
@ -374,8 +374,8 @@ func (d *Datastore) whereFilterHostsByTeams(filter kolide.TeamFilter, hostKey st
// Collect matching teams
var idStrs []string
for _, team := range filter.User.Teams {
if team.Role == kolide.RoleAdmin || team.Role == kolide.RoleMaintainer ||
(team.Role == kolide.RoleObserver && filter.IncludeObserver) {
if team.Role == fleet.RoleAdmin || team.Role == fleet.RoleMaintainer ||
(team.Role == fleet.RoleObserver && filter.IncludeObserver) {
idStrs = append(idStrs, strconv.Itoa(int(team.ID)))
}
}
@ -393,7 +393,7 @@ func (d *Datastore) whereFilterHostsByTeams(filter kolide.TeamFilter, hostKey st
//
// filter provides the filtering parameters that should be used. hostKey is the
// name/alias of the teams table to use in generating the SQL.
func (d *Datastore) whereFilterTeams(filter kolide.TeamFilter, teamKey string) string {
func (d *Datastore) whereFilterTeams(filter fleet.TeamFilter, teamKey string) string {
if filter.User == nil {
// This is likely unintentional, however we would like to return no
// results rather than panicking or returning some other error. At least
@ -405,10 +405,10 @@ func (d *Datastore) whereFilterTeams(filter kolide.TeamFilter, teamKey string) s
if filter.User.GlobalRole != nil {
switch *filter.User.GlobalRole {
case kolide.RoleAdmin, kolide.RoleMaintainer:
case fleet.RoleAdmin, fleet.RoleMaintainer:
return "TRUE"
case kolide.RoleObserver:
case fleet.RoleObserver:
if filter.IncludeObserver {
return "TRUE"
} else {
@ -423,8 +423,8 @@ func (d *Datastore) whereFilterTeams(filter kolide.TeamFilter, teamKey string) s
// Collect matching teams
var idStrs []string
for _, team := range filter.User.Teams {
if team.Role == kolide.RoleAdmin || team.Role == kolide.RoleMaintainer ||
(team.Role == kolide.RoleObserver && filter.IncludeObserver) {
if team.Role == fleet.RoleAdmin || team.Role == fleet.RoleMaintainer ||
(team.Role == fleet.RoleObserver && filter.IncludeObserver) {
idStrs = append(idStrs, strconv.Itoa(int(team.ID)))
}
}

View File

@ -5,7 +5,7 @@ import (
"github.com/DATA-DOG/go-sqlmock"
"github.com/VividCortex/mysqlerr"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/fleetdm/fleet/server/ptr"
"github.com/go-kit/kit/log"
"github.com/go-sql-driver/mysql"
@ -236,7 +236,7 @@ func TestWithRetryTxxCommitError(t *testing.T) {
func TestAppendListOptionsToSQL(t *testing.T) {
sql := "SELECT * FROM app_configs"
opts := kolide.ListOptions{
opts := fleet.ListOptions{
OrderKey: "name",
}
@ -247,14 +247,14 @@ func TestAppendListOptionsToSQL(t *testing.T) {
}
sql = "SELECT * FROM app_configs"
opts.OrderDirection = kolide.OrderDescending
opts.OrderDirection = fleet.OrderDescending
actual = appendListOptionsToSQL(sql, opts)
expected = "SELECT * FROM app_configs ORDER BY name DESC LIMIT 1000000"
if actual != expected {
t.Error("Expected", expected, "Actual", actual)
}
opts = kolide.ListOptions{
opts = fleet.ListOptions{
PerPage: 10,
}
@ -273,7 +273,7 @@ func TestAppendListOptionsToSQL(t *testing.T) {
t.Error("Expected", expected, "Actual", actual)
}
opts = kolide.ListOptions{}
opts = fleet.ListOptions{}
sql = "SELECT * FROM app_configs"
actual = appendListOptionsToSQL(sql, opts)
expected = "SELECT * FROM app_configs LIMIT 1000000"
@ -288,45 +288,45 @@ func TestWhereFilterHostsByTeams(t *testing.T) {
t.Parallel()
testCases := []struct {
filter kolide.TeamFilter
filter fleet.TeamFilter
expected string
}{
// No teams or global role
{
filter: kolide.TeamFilter{
User: &kolide.User{},
filter: fleet.TeamFilter{
User: &fleet.User{},
},
expected: "FALSE",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{Teams: []kolide.UserTeam{}},
filter: fleet.TeamFilter{
User: &fleet.User{Teams: []fleet.UserTeam{}},
},
expected: "FALSE",
},
// Global role
{
filter: kolide.TeamFilter{
User: &kolide.User{GlobalRole: ptr.String(kolide.RoleAdmin)},
filter: fleet.TeamFilter{
User: &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)},
},
expected: "TRUE",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{GlobalRole: ptr.String(kolide.RoleMaintainer)},
filter: fleet.TeamFilter{
User: &fleet.User{GlobalRole: ptr.String(fleet.RoleMaintainer)},
},
expected: "TRUE",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{GlobalRole: ptr.String(kolide.RoleObserver)},
filter: fleet.TeamFilter{
User: &fleet.User{GlobalRole: ptr.String(fleet.RoleObserver)},
},
expected: "FALSE",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{GlobalRole: ptr.String(kolide.RoleObserver)},
filter: fleet.TeamFilter{
User: &fleet.User{GlobalRole: ptr.String(fleet.RoleObserver)},
IncludeObserver: true,
},
expected: "TRUE",
@ -334,20 +334,20 @@ func TestWhereFilterHostsByTeams(t *testing.T) {
// Team roles
{
filter: kolide.TeamFilter{
User: &kolide.User{
Teams: []kolide.UserTeam{
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 1}},
filter: fleet.TeamFilter{
User: &fleet.User{
Teams: []fleet.UserTeam{
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 1}},
},
},
},
expected: "FALSE",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{
Teams: []kolide.UserTeam{
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 1}},
filter: fleet.TeamFilter{
User: &fleet.User{
Teams: []fleet.UserTeam{
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 1}},
},
},
IncludeObserver: true,
@ -355,33 +355,33 @@ func TestWhereFilterHostsByTeams(t *testing.T) {
expected: "hosts.team_id IN (1)",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{
Teams: []kolide.UserTeam{
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 1}},
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 2}},
filter: fleet.TeamFilter{
User: &fleet.User{
Teams: []fleet.UserTeam{
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 1}},
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 2}},
},
},
},
expected: "FALSE",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{
Teams: []kolide.UserTeam{
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 1}},
{Role: kolide.RoleMaintainer, Team: kolide.Team{ID: 2}},
filter: fleet.TeamFilter{
User: &fleet.User{
Teams: []fleet.UserTeam{
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 1}},
{Role: fleet.RoleMaintainer, Team: fleet.Team{ID: 2}},
},
},
},
expected: "hosts.team_id IN (2)",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{
Teams: []kolide.UserTeam{
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 1}},
{Role: kolide.RoleMaintainer, Team: kolide.Team{ID: 2}},
filter: fleet.TeamFilter{
User: &fleet.User{
Teams: []fleet.UserTeam{
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 1}},
{Role: fleet.RoleMaintainer, Team: fleet.Team{ID: 2}},
},
},
IncludeObserver: true,
@ -389,25 +389,25 @@ func TestWhereFilterHostsByTeams(t *testing.T) {
expected: "hosts.team_id IN (1,2)",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{
Teams: []kolide.UserTeam{
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 1}},
{Role: kolide.RoleMaintainer, Team: kolide.Team{ID: 2}},
filter: fleet.TeamFilter{
User: &fleet.User{
Teams: []fleet.UserTeam{
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 1}},
{Role: fleet.RoleMaintainer, Team: fleet.Team{ID: 2}},
// Invalid role should be ignored
{Role: "bad", Team: kolide.Team{ID: 37}},
{Role: "bad", Team: fleet.Team{ID: 37}},
},
},
},
expected: "hosts.team_id IN (2)",
},
{
filter: kolide.TeamFilter{
User: &kolide.User{
Teams: []kolide.UserTeam{
{Role: kolide.RoleObserver, Team: kolide.Team{ID: 1}},
{Role: kolide.RoleMaintainer, Team: kolide.Team{ID: 2}},
{Role: kolide.RoleAdmin, Team: kolide.Team{ID: 3}},
filter: fleet.TeamFilter{
User: &fleet.User{
Teams: []fleet.UserTeam{
{Role: fleet.RoleObserver, Team: fleet.Team{ID: 1}},
{Role: fleet.RoleMaintainer, Team: fleet.Team{ID: 2}},
{Role: fleet.RoleAdmin, Team: fleet.Team{ID: 3}},
// Invalid role should be ignored
},
},

View File

@ -4,12 +4,12 @@ import (
"database/sql"
"fmt"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func (d *Datastore) ApplyPackSpecs(specs []*kolide.PackSpec) (err error) {
func (d *Datastore) ApplyPackSpecs(specs []*fleet.PackSpec) (err error) {
err = d.withRetryTxx(func(tx *sqlx.Tx) error {
for _, spec := range specs {
if err := applyPackSpec(tx, spec); err != nil {
@ -23,7 +23,7 @@ func (d *Datastore) ApplyPackSpecs(specs []*kolide.PackSpec) (err error) {
return err
}
func applyPackSpec(tx *sqlx.Tx, spec *kolide.PackSpec) error {
func applyPackSpec(tx *sqlx.Tx, spec *fleet.PackSpec) error {
if spec.Name == "" {
return errors.New("pack name must not be empty")
}
@ -96,7 +96,7 @@ func applyPackSpec(tx *sqlx.Tx, spec *kolide.PackSpec) error {
INSERT INTO pack_targets (pack_id, type, target_id)
VALUES (?, ?, (SELECT id FROM labels WHERE name = ?))
`
if _, err := tx.Exec(query, packID, kolide.TargetLabel, l); err != nil {
if _, err := tx.Exec(query, packID, fleet.TargetLabel, l); err != nil {
return errors.Wrap(err, "adding label to pack")
}
}
@ -104,7 +104,7 @@ func applyPackSpec(tx *sqlx.Tx, spec *kolide.PackSpec) error {
return nil
}
func (d *Datastore) GetPackSpecs() (specs []*kolide.PackSpec, err error) {
func (d *Datastore) GetPackSpecs() (specs []*fleet.PackSpec, err error) {
err = d.withRetryTxx(func(tx *sqlx.Tx) error {
// Get basic specs
query := "SELECT id, name, description, platform, disabled FROM packs"
@ -119,7 +119,7 @@ SELECT l.name
FROM labels l JOIN pack_targets pt
WHERE pack_id = ? AND pt.type = ? AND pt.target_id = l.id
`
if err := tx.Select(&spec.Targets.Labels, query, spec.ID, kolide.TargetLabel); err != nil {
if err := tx.Select(&spec.Targets.Labels, query, spec.ID, fleet.TargetLabel); err != nil {
return errors.Wrap(err, "get pack targets")
}
}
@ -148,10 +148,10 @@ WHERE pack_id = ?
return specs, nil
}
func (d *Datastore) GetPackSpec(name string) (spec *kolide.PackSpec, err error) {
func (d *Datastore) GetPackSpec(name string) (spec *fleet.PackSpec, err error) {
err = d.withRetryTxx(func(tx *sqlx.Tx) error {
// Get basic spec
var specs []*kolide.PackSpec
var specs []*fleet.PackSpec
query := "SELECT id, name, description, platform, disabled FROM packs WHERE name = ?"
if err := tx.Select(&specs, query, name); err != nil {
return errors.Wrap(err, "get packs")
@ -171,7 +171,7 @@ SELECT l.name
FROM labels l JOIN pack_targets pt
WHERE pack_id = ? AND pt.type = ? AND pt.target_id = l.id
`
if err := tx.Select(&spec.Targets.Labels, query, spec.ID, kolide.TargetLabel); err != nil {
if err := tx.Select(&spec.Targets.Labels, query, spec.ID, fleet.TargetLabel); err != nil {
return errors.Wrap(err, "get pack targets")
}
@ -197,14 +197,14 @@ WHERE pack_id = ?
return spec, nil
}
func (d *Datastore) PackByName(name string, opts ...kolide.OptionalArg) (*kolide.Pack, bool, error) {
func (d *Datastore) PackByName(name string, opts ...fleet.OptionalArg) (*fleet.Pack, bool, error) {
db := d.getTransaction(opts)
sqlStatement := `
SELECT *
FROM packs
WHERE name = ?
`
var pack kolide.Pack
var pack fleet.Pack
err := db.Get(&pack, sqlStatement, name)
if err != nil {
if err == sql.ErrNoRows {
@ -217,7 +217,7 @@ func (d *Datastore) PackByName(name string, opts ...kolide.OptionalArg) (*kolide
}
// NewPack creates a new Pack
func (d *Datastore) NewPack(pack *kolide.Pack, opts ...kolide.OptionalArg) (*kolide.Pack, error) {
func (d *Datastore) NewPack(pack *fleet.Pack, opts ...fleet.OptionalArg) (*fleet.Pack, error) {
db := d.getTransaction(opts)
query := `
@ -237,7 +237,7 @@ func (d *Datastore) NewPack(pack *kolide.Pack, opts ...kolide.OptionalArg) (*kol
}
// SavePack stores changes to pack
func (d *Datastore) SavePack(pack *kolide.Pack) error {
func (d *Datastore) SavePack(pack *fleet.Pack) error {
query := `
UPDATE packs
SET name = ?, platform = ?, disabled = ?, description = ?
@ -258,15 +258,15 @@ func (d *Datastore) SavePack(pack *kolide.Pack) error {
return nil
}
// DeletePack deletes a kolide.Pack so that it won't show up in results.
// DeletePack deletes a fleet.Pack so that it won't show up in results.
func (d *Datastore) DeletePack(name string) error {
return d.deleteEntityByName("packs", name)
}
// Pack fetch kolide.Pack with matching ID
func (d *Datastore) Pack(pid uint) (*kolide.Pack, error) {
// Pack fetch fleet.Pack with matching ID
func (d *Datastore) Pack(pid uint) (*fleet.Pack, error) {
query := `SELECT * FROM packs WHERE id = ?`
pack := &kolide.Pack{}
pack := &fleet.Pack{}
err := d.db.Get(pack, query, pid)
if err == sql.ErrNoRows {
return nil, notFound("Pack").WithID(pid)
@ -277,10 +277,10 @@ func (d *Datastore) Pack(pid uint) (*kolide.Pack, error) {
return pack, nil
}
// ListPacks returns all kolide.Pack records limited and sorted by kolide.ListOptions
func (d *Datastore) ListPacks(opt kolide.ListOptions) ([]*kolide.Pack, error) {
// ListPacks returns all fleet.Pack records limited and sorted by fleet.ListOptions
func (d *Datastore) ListPacks(opt fleet.ListOptions) ([]*fleet.Pack, error) {
query := `SELECT * FROM packs`
packs := []*kolide.Pack{}
packs := []*fleet.Pack{}
err := d.db.Select(&packs, appendListOptionsToSQL(query, opt))
if err != nil && err != sql.ErrNoRows {
return nil, errors.Wrap(err, "listing packs")
@ -288,8 +288,8 @@ func (d *Datastore) ListPacks(opt kolide.ListOptions) ([]*kolide.Pack, error) {
return packs, nil
}
// AddLabelToPack associates a kolide.Label with a kolide.Pack
func (d *Datastore) AddLabelToPack(lid uint, pid uint, opts ...kolide.OptionalArg) error {
// AddLabelToPack associates a fleet.Label with a fleet.Pack
func (d *Datastore) AddLabelToPack(lid uint, pid uint, opts ...fleet.OptionalArg) error {
db := d.getTransaction(opts)
query := `
@ -297,7 +297,7 @@ func (d *Datastore) AddLabelToPack(lid uint, pid uint, opts ...kolide.OptionalAr
VALUES ( ?, ?, ? )
ON DUPLICATE KEY UPDATE id=id
`
_, err := db.Exec(query, pid, kolide.TargetLabel, lid)
_, err := db.Exec(query, pid, fleet.TargetLabel, lid)
if err != nil {
return errors.Wrap(err, "adding label to pack")
}
@ -305,14 +305,14 @@ func (d *Datastore) AddLabelToPack(lid uint, pid uint, opts ...kolide.OptionalAr
return nil
}
// AddHostToPack associates a kolide.Host with a kolide.Pack
// AddHostToPack associates a fleet.Host with a fleet.Pack
func (d *Datastore) AddHostToPack(hid, pid uint) error {
query := `
INSERT INTO pack_targets ( pack_id, type, target_id )
VALUES ( ?, ?, ? )
ON DUPLICATE KEY UPDATE id=id
`
_, err := d.db.Exec(query, pid, kolide.TargetHost, hid)
_, err := d.db.Exec(query, pid, fleet.TargetHost, hid)
if err != nil {
return errors.Wrap(err, "adding host to pack")
}
@ -320,14 +320,14 @@ func (d *Datastore) AddHostToPack(hid, pid uint) error {
return nil
}
// RemoreLabelFromPack will remove the association between a kolide.Label and
// a kolide.Pack
// RemoreLabelFromPack will remove the association between a fleet.Label and
// a fleet.Pack
func (d *Datastore) RemoveLabelFromPack(lid, pid uint) error {
query := `
DELETE FROM pack_targets
WHERE target_id = ? AND pack_id = ? AND type = ?
`
_, err := d.db.Exec(query, lid, pid, kolide.TargetLabel)
_, err := d.db.Exec(query, lid, pid, fleet.TargetLabel)
if err == sql.ErrNoRows {
return notFound("PackTarget").WithMessage(fmt.Sprintf("label ID: %d, pack ID: %d", lid, pid))
} else if err != nil {
@ -336,14 +336,14 @@ func (d *Datastore) RemoveLabelFromPack(lid, pid uint) error {
return nil
}
// RemoveHostFromPack will remove the association between a kolide.Host and a
// kolide.Pack
// RemoveHostFromPack will remove the association between a fleet.Host and a
// fleet.Pack
func (d *Datastore) RemoveHostFromPack(hid, pid uint) error {
query := `
DELETE FROM pack_targets
WHERE target_id = ? AND pack_id = ? AND type = ?
`
_, err := d.db.Exec(query, hid, pid, kolide.TargetHost)
_, err := d.db.Exec(query, hid, pid, fleet.TargetHost)
if err == sql.ErrNoRows {
return notFound("PackTarget").WithMessage(fmt.Sprintf("host ID: %d, pack ID: %d", hid, pid))
} else if err != nil {
@ -352,8 +352,8 @@ func (d *Datastore) RemoveHostFromPack(hid, pid uint) error {
return nil
}
// ListLabelsForPack will return a list of kolide.Label records associated with kolide.Pack
func (d *Datastore) ListLabelsForPack(pid uint) ([]*kolide.Label, error) {
// ListLabelsForPack will return a list of fleet.Label records associated with fleet.Pack
func (d *Datastore) ListLabelsForPack(pid uint) ([]*fleet.Label, error) {
query := `
SELECT
l.id,
@ -372,16 +372,16 @@ func (d *Datastore) ListLabelsForPack(pid uint) ([]*kolide.Label, error) {
pt.pack_id = ?
`
labels := []*kolide.Label{}
labels := []*fleet.Label{}
if err := d.db.Select(&labels, query, kolide.TargetLabel, pid); err != nil && err != sql.ErrNoRows {
if err := d.db.Select(&labels, query, fleet.TargetLabel, pid); err != nil && err != sql.ErrNoRows {
return nil, errors.Wrap(err, "listing labels for pack")
}
return labels, nil
}
func (d *Datastore) ListPacksForHost(hid uint) ([]*kolide.Pack, error) {
func (d *Datastore) ListPacksForHost(hid uint) ([]*fleet.Pack, error) {
query := `
SELECT DISTINCT packs.*
FROM
@ -402,14 +402,14 @@ func (d *Datastore) ListPacksForHost(hid uint) ([]*kolide.Pack, error) {
) packs
`
packs := []*kolide.Pack{}
if err := d.db.Select(&packs, query, kolide.TargetLabel, hid, kolide.TargetHost, hid); err != nil && err != sql.ErrNoRows {
packs := []*fleet.Pack{}
if err := d.db.Select(&packs, query, fleet.TargetLabel, hid, fleet.TargetHost, hid); err != nil && err != sql.ErrNoRows {
return nil, errors.Wrap(err, "listing hosts in pack")
}
return packs, nil
}
func (d *Datastore) ListHostsInPack(pid uint, opt kolide.ListOptions) ([]uint, error) {
func (d *Datastore) ListHostsInPack(pid uint, opt fleet.ListOptions) ([]uint, error) {
query := `
SELECT DISTINCT h.id
FROM hosts h
@ -427,13 +427,13 @@ func (d *Datastore) ListHostsInPack(pid uint, opt kolide.ListOptions) ([]uint, e
`
hosts := []uint{}
if err := d.db.Select(&hosts, appendListOptionsToSQL(query, opt), kolide.TargetLabel, kolide.TargetHost, pid); err != nil && err != sql.ErrNoRows {
if err := d.db.Select(&hosts, appendListOptionsToSQL(query, opt), fleet.TargetLabel, fleet.TargetHost, pid); err != nil && err != sql.ErrNoRows {
return nil, errors.Wrap(err, "listing hosts in pack")
}
return hosts, nil
}
func (d *Datastore) ListExplicitHostsInPack(pid uint, opt kolide.ListOptions) ([]uint, error) {
func (d *Datastore) ListExplicitHostsInPack(pid uint, opt fleet.ListOptions) ([]uint, error) {
query := `
SELECT DISTINCT h.id
FROM hosts h
@ -445,7 +445,7 @@ func (d *Datastore) ListExplicitHostsInPack(pid uint, opt kolide.ListOptions) ([
WHERE pt.pack_id = ?
`
hosts := []uint{}
if err := d.db.Select(&hosts, appendListOptionsToSQL(query, opt), kolide.TargetHost, pid); err != nil && err != sql.ErrNoRows {
if err := d.db.Select(&hosts, appendListOptionsToSQL(query, opt), fleet.TargetHost, pid); err != nil && err != sql.ErrNoRows {
return nil, errors.Wrap(err, "listing explicit hosts in pack")
}
return hosts, nil

View File

@ -1,11 +1,11 @@
package mysql
import (
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
func (d *Datastore) NewPasswordResetRequest(req *kolide.PasswordResetRequest) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) NewPasswordResetRequest(req *fleet.PasswordResetRequest) (*fleet.PasswordResetRequest, error) {
sqlStatement := `
INSERT INTO password_reset_requests
( user_id, token, expires_at)
@ -22,7 +22,7 @@ func (d *Datastore) NewPasswordResetRequest(req *kolide.PasswordResetRequest) (*
}
func (d *Datastore) SavePasswordResetRequest(req *kolide.PasswordResetRequest) error {
func (d *Datastore) SavePasswordResetRequest(req *fleet.PasswordResetRequest) error {
sqlStatement := `
UPDATE password_reset_requests SET
expires_at = ?,
@ -45,7 +45,7 @@ func (d *Datastore) SavePasswordResetRequest(req *kolide.PasswordResetRequest) e
return nil
}
func (d *Datastore) DeletePasswordResetRequest(req *kolide.PasswordResetRequest) error {
func (d *Datastore) DeletePasswordResetRequest(req *fleet.PasswordResetRequest) error {
err := d.deleteEntity("password_reset_requests", req.ID)
if err != nil {
return errors.Wrap(err, "deleting from password reset request")
@ -66,12 +66,12 @@ func (d *Datastore) DeletePasswordResetRequestsForUser(userID uint) error {
return nil
}
func (d *Datastore) FindPassswordResetByID(id uint) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetByID(id uint) (*fleet.PasswordResetRequest, error) {
sqlStatement := `
SELECT * FROM password_reset_requests
WHERE id = ? LIMIT 1
`
passwordResetRequest := &kolide.PasswordResetRequest{}
passwordResetRequest := &fleet.PasswordResetRequest{}
err := d.db.Get(&passwordResetRequest, sqlStatement, id)
if err != nil {
return nil, errors.Wrap(err, "selecting password reset by id")
@ -80,13 +80,13 @@ func (d *Datastore) FindPassswordResetByID(id uint) (*kolide.PasswordResetReques
return passwordResetRequest, nil
}
func (d *Datastore) FindPassswordResetsByUserID(id uint) ([]*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetsByUserID(id uint) ([]*fleet.PasswordResetRequest, error) {
sqlStatement := `
SELECT * FROM password_reset_requests
WHERE user_id = ?
`
passwordResetRequests := []*kolide.PasswordResetRequest{}
passwordResetRequests := []*fleet.PasswordResetRequest{}
err := d.db.Select(&passwordResetRequests, sqlStatement, id)
if err != nil {
return nil, errors.Wrap(err, "finding password resets by user id")
@ -96,12 +96,12 @@ func (d *Datastore) FindPassswordResetsByUserID(id uint) ([]*kolide.PasswordRese
}
func (d *Datastore) FindPassswordResetByToken(token string) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetByToken(token string) (*fleet.PasswordResetRequest, error) {
sqlStatement := `
SELECT * FROM password_reset_requests
WHERE token = ? LIMIT 1
`
passwordResetRequest := &kolide.PasswordResetRequest{}
passwordResetRequest := &fleet.PasswordResetRequest{}
err := d.db.Get(passwordResetRequest, sqlStatement, token)
if err != nil {
return nil, errors.Wrap(err, "selecting password reset requests")
@ -111,13 +111,13 @@ func (d *Datastore) FindPassswordResetByToken(token string) (*kolide.PasswordRes
}
func (d *Datastore) FindPassswordResetByTokenAndUserID(token string, id uint) (*kolide.PasswordResetRequest, error) {
func (d *Datastore) FindPassswordResetByTokenAndUserID(token string, id uint) (*fleet.PasswordResetRequest, error) {
sqlStatement := `
SELECT * FROM password_reset_requests
WHERE user_id = ? AND token = ?
LIMIT 1
`
passwordResetRequest := &kolide.PasswordResetRequest{}
passwordResetRequest := &fleet.PasswordResetRequest{}
err := d.db.Get(passwordResetRequest, sqlStatement, id, token)
if err != nil {
return nil, errors.Wrap(err, "selecting password reset by token and user id")

View File

@ -4,12 +4,12 @@ import (
"database/sql"
"fmt"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func (d *Datastore) ApplyQueries(authorID uint, queries []*kolide.Query) (err error) {
func (d *Datastore) ApplyQueries(authorID uint, queries []*fleet.Query) (err error) {
tx, err := d.db.Begin()
if err != nil {
return errors.Wrap(err, "begin ApplyQueries transaction")
@ -64,14 +64,14 @@ func (d *Datastore) ApplyQueries(authorID uint, queries []*kolide.Query) (err er
return errors.Wrap(err, "commit ApplyQueries transaction")
}
func (d *Datastore) QueryByName(name string, opts ...kolide.OptionalArg) (*kolide.Query, error) {
func (d *Datastore) QueryByName(name string, opts ...fleet.OptionalArg) (*fleet.Query, error) {
db := d.getTransaction(opts)
sqlStatement := `
SELECT *
FROM queries
WHERE name = ?
`
var query kolide.Query
var query fleet.Query
err := db.Get(&query, sqlStatement, name)
if err != nil {
if err == sql.ErrNoRows {
@ -80,7 +80,7 @@ func (d *Datastore) QueryByName(name string, opts ...kolide.OptionalArg) (*kolid
return nil, errors.Wrap(err, "selecting query by name")
}
if err := d.loadPacksForQueries([]*kolide.Query{&query}); err != nil {
if err := d.loadPacksForQueries([]*fleet.Query{&query}); err != nil {
return nil, errors.Wrap(err, "loading packs for query")
}
@ -88,7 +88,7 @@ func (d *Datastore) QueryByName(name string, opts ...kolide.OptionalArg) (*kolid
}
// NewQuery creates a New Query.
func (d *Datastore) NewQuery(query *kolide.Query, opts ...kolide.OptionalArg) (*kolide.Query, error) {
func (d *Datastore) NewQuery(query *fleet.Query, opts ...fleet.OptionalArg) (*fleet.Query, error) {
db := d.getTransaction(opts)
sqlStatement := `
@ -111,12 +111,12 @@ func (d *Datastore) NewQuery(query *kolide.Query, opts ...kolide.OptionalArg) (*
id, _ := result.LastInsertId()
query.ID = uint(id)
query.Packs = []kolide.Pack{}
query.Packs = []fleet.Pack{}
return query, nil
}
// SaveQuery saves changes to a Query.
func (d *Datastore) SaveQuery(q *kolide.Query) error {
func (d *Datastore) SaveQuery(q *fleet.Query) error {
sql := `
UPDATE queries
SET name = ?, description = ?, query = ?, author_id = ?, saved = ?, observer_can_run = ?
@ -149,7 +149,7 @@ func (d *Datastore) DeleteQueries(ids []uint) (uint, error) {
}
// Query returns a single Query identified by id, if such exists.
func (d *Datastore) Query(id uint) (*kolide.Query, error) {
func (d *Datastore) Query(id uint) (*fleet.Query, error) {
sql := `
SELECT q.*, COALESCE(NULLIF(u.name, ''), u.username, '') AS author_name
FROM queries q
@ -157,12 +157,12 @@ func (d *Datastore) Query(id uint) (*kolide.Query, error) {
ON q.author_id = u.id
WHERE q.id = ?
`
query := &kolide.Query{}
query := &fleet.Query{}
if err := d.db.Get(query, sql, id); err != nil {
return nil, errors.Wrap(err, "selecting query")
}
if err := d.loadPacksForQueries([]*kolide.Query{query}); err != nil {
if err := d.loadPacksForQueries([]*fleet.Query{query}); err != nil {
return nil, errors.Wrap(err, "loading packs for queries")
}
@ -170,8 +170,8 @@ func (d *Datastore) Query(id uint) (*kolide.Query, error) {
}
// ListQueries returns a list of queries with sort order and results limit
// determined by passed in kolide.ListOptions
func (d *Datastore) ListQueries(opt kolide.ListOptions) ([]*kolide.Query, error) {
// determined by passed in fleet.ListOptions
func (d *Datastore) ListQueries(opt fleet.ListOptions) ([]*fleet.Query, error) {
sql := `
SELECT q.*, COALESCE(u.name, '<deleted>') AS author_name
FROM queries q
@ -180,7 +180,7 @@ func (d *Datastore) ListQueries(opt kolide.ListOptions) ([]*kolide.Query, error)
WHERE saved = true
`
sql = appendListOptionsToSQL(sql, opt)
results := []*kolide.Query{}
results := []*fleet.Query{}
if err := d.db.Select(&results, sql); err != nil {
return nil, errors.Wrap(err, "listing queries")
@ -194,7 +194,7 @@ func (d *Datastore) ListQueries(opt kolide.ListOptions) ([]*kolide.Query, error)
}
// loadPacksForQueries loads the packs associated with the provided queries
func (d *Datastore) loadPacksForQueries(queries []*kolide.Query) error {
func (d *Datastore) loadPacksForQueries(queries []*fleet.Query) error {
if len(queries) == 0 {
return nil
}
@ -208,11 +208,11 @@ func (d *Datastore) loadPacksForQueries(queries []*kolide.Query) error {
`
// Used to map the results
name_queries := map[string]*kolide.Query{}
name_queries := map[string]*fleet.Query{}
// Used for the IN clause
names := []string{}
for _, q := range queries {
q.Packs = make([]kolide.Pack, 0)
q.Packs = make([]fleet.Pack, 0)
names = append(names, q.Name)
name_queries[q.Name] = q
}
@ -224,7 +224,7 @@ func (d *Datastore) loadPacksForQueries(queries []*kolide.Query) error {
rows := []struct {
QueryName string `db:"query_name"`
kolide.Pack
fleet.Pack
}{}
err = d.db.Select(&rows, query, args...)

View File

@ -3,11 +3,11 @@ package mysql
import (
"database/sql"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
func (d *Datastore) ListScheduledQueriesInPack(id uint, opts kolide.ListOptions) ([]*kolide.ScheduledQuery, error) {
func (d *Datastore) ListScheduledQueriesInPack(id uint, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {
query := `
SELECT
sq.id,
@ -30,7 +30,7 @@ func (d *Datastore) ListScheduledQueriesInPack(id uint, opts kolide.ListOptions)
WHERE sq.pack_id = ?
`
query = appendListOptionsToSQL(query, opts)
results := []*kolide.ScheduledQuery{}
results := []*fleet.ScheduledQuery{}
if err := d.db.Select(&results, query, id); err != nil {
return nil, errors.Wrap(err, "listing scheduled queries")
@ -39,7 +39,7 @@ func (d *Datastore) ListScheduledQueriesInPack(id uint, opts kolide.ListOptions)
return results, nil
}
func (d *Datastore) NewScheduledQuery(sq *kolide.ScheduledQuery, opts ...kolide.OptionalArg) (*kolide.ScheduledQuery, error) {
func (d *Datastore) NewScheduledQuery(sq *fleet.ScheduledQuery, opts ...fleet.OptionalArg) (*fleet.ScheduledQuery, error) {
db := d.getTransaction(opts)
// This query looks up the query name using the ID (for backwards
@ -92,7 +92,7 @@ func (d *Datastore) NewScheduledQuery(sq *kolide.ScheduledQuery, opts ...kolide.
return sq, nil
}
func (d *Datastore) SaveScheduledQuery(sq *kolide.ScheduledQuery) (*kolide.ScheduledQuery, error) {
func (d *Datastore) SaveScheduledQuery(sq *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {
query := `
UPDATE scheduled_queries
SET pack_id = ?, query_id = ?, ` + "`interval`" + ` = ?, snapshot = ?, removed = ?, platform = ?, version = ?, shard = ?, denylist = ?
@ -116,7 +116,7 @@ func (d *Datastore) DeleteScheduledQuery(id uint) error {
return d.deleteEntity("scheduled_queries", id)
}
func (d *Datastore) ScheduledQuery(id uint) (*kolide.ScheduledQuery, error) {
func (d *Datastore) ScheduledQuery(id uint) (*fleet.ScheduledQuery, error) {
query := `
SELECT
sq.id,
@ -140,7 +140,7 @@ func (d *Datastore) ScheduledQuery(id uint) (*kolide.ScheduledQuery, error) {
ON sq.query_name = q.name
WHERE sq.id = ?
`
sq := &kolide.ScheduledQuery{}
sq := &fleet.ScheduledQuery{}
if err := d.db.Get(sq, query, id); err != nil {
return nil, errors.Wrap(err, "select scheduled query")
}

View File

@ -1,16 +1,16 @@
package mysql
import (
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
func (d *Datastore) SessionByKey(key string) (*kolide.Session, error) {
func (d *Datastore) SessionByKey(key string) (*fleet.Session, error) {
sqlStatement := `
SELECT * FROM sessions
WHERE ` + "`key`" + ` = ? LIMIT 1
`
session := &kolide.Session{}
session := &fleet.Session{}
err := d.db.Get(session, sqlStatement, key)
if err != nil {
return nil, errors.Wrap(err, "selecting sessions")
@ -19,13 +19,13 @@ func (d *Datastore) SessionByKey(key string) (*kolide.Session, error) {
return session, nil
}
func (d *Datastore) SessionByID(id uint) (*kolide.Session, error) {
func (d *Datastore) SessionByID(id uint) (*fleet.Session, error) {
sqlStatement := `
SELECT * FROM sessions
WHERE id = ?
LIMIT 1
`
session := &kolide.Session{}
session := &fleet.Session{}
err := d.db.Get(session, sqlStatement, id)
if err != nil {
return nil, errors.Wrap(err, "selecting session by id")
@ -34,12 +34,12 @@ func (d *Datastore) SessionByID(id uint) (*kolide.Session, error) {
return session, nil
}
func (d *Datastore) ListSessionsForUser(id uint) ([]*kolide.Session, error) {
func (d *Datastore) ListSessionsForUser(id uint) ([]*fleet.Session, error) {
sqlStatement := `
SELECT * FROM sessions
WHERE user_id = ?
`
sessions := []*kolide.Session{}
sessions := []*fleet.Session{}
err := d.db.Select(&sessions, sqlStatement, id)
if err != nil {
return nil, errors.Wrap(err, "selecting sessions for user")
@ -49,7 +49,7 @@ func (d *Datastore) ListSessionsForUser(id uint) ([]*kolide.Session, error) {
}
func (d *Datastore) NewSession(session *kolide.Session) (*kolide.Session, error) {
func (d *Datastore) NewSession(session *fleet.Session) (*fleet.Session, error) {
sqlStatement := `
INSERT INTO sessions (
user_id,
@ -67,7 +67,7 @@ func (d *Datastore) NewSession(session *kolide.Session) (*kolide.Session, error)
return session, nil
}
func (d *Datastore) DestroySession(session *kolide.Session) error {
func (d *Datastore) DestroySession(session *fleet.Session) error {
err := d.deleteEntity("sessions", session.ID)
if err != nil {
return errors.Wrap(err, "deleting session")
@ -88,7 +88,7 @@ func (d *Datastore) DestroyAllSessionsForUser(id uint) error {
return nil
}
func (d *Datastore) MarkSessionAccessed(session *kolide.Session) error {
func (d *Datastore) MarkSessionAccessed(session *fleet.Session) error {
sqlStatement := `
UPDATE sessions SET
accessed_at = ?

View File

@ -4,7 +4,7 @@ import (
"fmt"
"strings"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
@ -22,7 +22,7 @@ func truncateString(str string, length int) string {
return str
}
func (d *Datastore) SaveHostSoftware(host *kolide.Host) error {
func (d *Datastore) SaveHostSoftware(host *fleet.Host) error {
if !host.HostSoftware.Modified {
return nil
}
@ -76,8 +76,8 @@ func (d *Datastore) SaveHostSoftware(host *kolide.Host) error {
return nil
}
func (d *Datastore) LoadHostSoftware(host *kolide.Host) error {
host.HostSoftware = kolide.HostSoftware{Modified: false}
func (d *Datastore) LoadHostSoftware(host *fleet.Host) error {
host.HostSoftware = fleet.HostSoftware{Modified: false}
sql := `
SELECT * FROM software
WHERE id IN

View File

@ -4,18 +4,18 @@ import (
"fmt"
"time"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func (d *Datastore) CountHostsInTargets(filter kolide.TeamFilter, targets kolide.HostTargets, now time.Time) (kolide.TargetMetrics, error) {
func (d *Datastore) CountHostsInTargets(filter fleet.TeamFilter, targets fleet.HostTargets, now time.Time) (fleet.TargetMetrics, error) {
// The logic in this function should remain synchronized with
// host.Status and GenerateHostStatusStatistics
if len(targets.HostIDs) == 0 && len(targets.LabelIDs) == 0 && len(targets.TeamIDs) == 0 {
// No need to query if no targets selected
return kolide.TargetMetrics{}, nil
return fleet.TargetMetrics{}, nil
}
sql := fmt.Sprintf(`
@ -27,7 +27,7 @@ func (d *Datastore) CountHostsInTargets(filter kolide.TeamFilter, targets kolide
COALESCE(SUM(CASE WHEN DATE_ADD(created_at, INTERVAL 1 DAY) >= ? THEN 1 ELSE 0 END), 0) new
FROM hosts h
WHERE (id IN (?) OR (id IN (SELECT DISTINCT host_id FROM label_membership WHERE label_id IN (?))) OR team_id IN (?)) AND %s
`, kolide.OnlineIntervalBuffer, kolide.OnlineIntervalBuffer, d.whereFilterHostsByTeams(filter, "h"))
`, fleet.OnlineIntervalBuffer, fleet.OnlineIntervalBuffer, d.whereFilterHostsByTeams(filter, "h"))
// Using -1 in the ID slices for the IN clause allows us to include the
// IN clause even if we have no IDs to use. -1 will not match the
@ -48,19 +48,19 @@ func (d *Datastore) CountHostsInTargets(filter kolide.TeamFilter, targets kolide
query, args, err := sqlx.In(sql, now, now, now, now, now, queryHostIDs, queryLabelIDs, queryTeamIDs)
if err != nil {
return kolide.TargetMetrics{}, errors.Wrap(err, "sqlx.In CountHostsInTargets")
return fleet.TargetMetrics{}, errors.Wrap(err, "sqlx.In CountHostsInTargets")
}
res := kolide.TargetMetrics{}
res := fleet.TargetMetrics{}
err = d.db.Get(&res, query, args...)
if err != nil {
return kolide.TargetMetrics{}, errors.Wrap(err, "sqlx.Get CountHostsInTargets")
return fleet.TargetMetrics{}, errors.Wrap(err, "sqlx.Get CountHostsInTargets")
}
return res, nil
}
func (d *Datastore) HostIDsInTargets(filter kolide.TeamFilter, targets kolide.HostTargets) ([]uint, error) {
func (d *Datastore) HostIDsInTargets(filter fleet.TeamFilter, targets fleet.HostTargets) ([]uint, error) {
if len(targets.HostIDs) == 0 && len(targets.LabelIDs) == 0 && len(targets.TeamIDs) == 0 {
// No need to query if no targets selected
return []uint{}, nil

View File

@ -4,14 +4,14 @@ import (
"fmt"
"strings"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
var teamSearchColumns = []string{"name"}
func (d *Datastore) NewTeam(team *kolide.Team) (*kolide.Team, error) {
func (d *Datastore) NewTeam(team *fleet.Team) (*fleet.Team, error) {
query := `
INSERT INTO teams (
name,
@ -39,12 +39,12 @@ func (d *Datastore) NewTeam(team *kolide.Team) (*kolide.Team, error) {
return team, nil
}
func (d *Datastore) Team(tid uint) (*kolide.Team, error) {
func (d *Datastore) Team(tid uint) (*fleet.Team, error) {
sql := `
SELECT * FROM teams
WHERE id = ?
`
team := &kolide.Team{}
team := &fleet.Team{}
if err := d.db.Get(team, sql, tid); err != nil {
return nil, errors.Wrap(err, "select team")
@ -61,7 +61,7 @@ func (d *Datastore) Team(tid uint) (*kolide.Team, error) {
return team, nil
}
func (d *Datastore) saveTeamSecrets(team *kolide.Team) error {
func (d *Datastore) saveTeamSecrets(team *fleet.Team) error {
if team.Secrets == nil {
return nil
}
@ -76,12 +76,12 @@ func (d *Datastore) DeleteTeam(tid uint) error {
return nil
}
func (d *Datastore) TeamByName(name string) (*kolide.Team, error) {
func (d *Datastore) TeamByName(name string) (*fleet.Team, error) {
sql := `
SELECT * FROM teams
WHERE name = ?
`
team := &kolide.Team{}
team := &fleet.Team{}
if err := d.db.Get(team, sql, name); err != nil {
return nil, errors.Wrap(err, "select team")
@ -94,13 +94,13 @@ func (d *Datastore) TeamByName(name string) (*kolide.Team, error) {
return team, nil
}
func (d *Datastore) loadUsersForTeam(team *kolide.Team) error {
func (d *Datastore) loadUsersForTeam(team *fleet.Team) error {
sql := `
SELECT u.name, u.id, u.email, ut.role
FROM user_teams ut JOIN users u ON (ut.user_id = u.id)
WHERE ut.team_id = ?
`
rows := []kolide.TeamUser{}
rows := []fleet.TeamUser{}
if err := d.db.Select(&rows, sql, team.ID); err != nil {
return errors.Wrap(err, "load users for team")
}
@ -109,7 +109,7 @@ func (d *Datastore) loadUsersForTeam(team *kolide.Team) error {
return nil
}
func (d *Datastore) saveUsersForTeam(team *kolide.Team) error {
func (d *Datastore) saveUsersForTeam(team *fleet.Team) error {
// Do a full user update by deleting existing users and then inserting all
// the current users in a single transaction.
if err := d.withRetryTxx(func(tx *sqlx.Tx) error {
@ -144,7 +144,7 @@ func (d *Datastore) saveUsersForTeam(team *kolide.Team) error {
return nil
}
func (d *Datastore) SaveTeam(team *kolide.Team) (*kolide.Team, error) {
func (d *Datastore) SaveTeam(team *fleet.Team) (*fleet.Team, error) {
query := `
UPDATE teams SET
name = ?,
@ -165,8 +165,8 @@ func (d *Datastore) SaveTeam(team *kolide.Team) (*kolide.Team, error) {
}
// ListTeams lists all teams with limit, sort and offset passed in with
// kolide.ListOptions
func (d *Datastore) ListTeams(filter kolide.TeamFilter, opt kolide.ListOptions) ([]*kolide.Team, error) {
// fleet.ListOptions
func (d *Datastore) ListTeams(filter fleet.TeamFilter, opt fleet.ListOptions) ([]*fleet.Team, error) {
query := fmt.Sprintf(`
SELECT *,
(SELECT count(*) FROM user_teams WHERE team_id = t.id) AS user_count,
@ -178,7 +178,7 @@ func (d *Datastore) ListTeams(filter kolide.TeamFilter, opt kolide.ListOptions)
)
query, params := searchLike(query, nil, opt.MatchQuery, teamSearchColumns...)
query = appendListOptionsToSQL(query, opt)
teams := []*kolide.Team{}
teams := []*fleet.Team{}
if err := d.db.Select(&teams, query, params...); err != nil {
return nil, errors.Wrap(err, "list teams")
}
@ -186,7 +186,7 @@ func (d *Datastore) ListTeams(filter kolide.TeamFilter, opt kolide.ListOptions)
}
func (d *Datastore) SearchTeams(filter kolide.TeamFilter, matchQuery string, omit ...uint) ([]*kolide.Team, error) {
func (d *Datastore) SearchTeams(filter fleet.TeamFilter, matchQuery string, omit ...uint) ([]*fleet.Team, error) {
sql := fmt.Sprintf(`
SELECT *,
(SELECT count(*) FROM user_teams WHERE team_id = t.id) AS user_count,
@ -198,18 +198,18 @@ func (d *Datastore) SearchTeams(filter kolide.TeamFilter, matchQuery string, omi
)
sql, params := searchLike(sql, nil, matchQuery, teamSearchColumns...)
sql += "\nLIMIT 5"
teams := []*kolide.Team{}
teams := []*fleet.Team{}
if err := d.db.Select(&teams, sql, params...); err != nil {
return nil, errors.Wrap(err, "search teams")
}
return teams, nil
}
func (d *Datastore) TeamEnrollSecrets(teamID uint) ([]*kolide.EnrollSecret, error) {
func (d *Datastore) TeamEnrollSecrets(teamID uint) ([]*fleet.EnrollSecret, error) {
sql := `
SELECT * FROM enroll_secrets
WHERE team_id = ?
`
var secrets []*kolide.EnrollSecret
var secrets []*fleet.EnrollSecret
if err := d.db.Select(&secrets, sql, teamID); err != nil {
return nil, errors.Wrap(err, "get secrets")
}

View File

@ -5,7 +5,7 @@ import (
"fmt"
"strings"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
@ -13,7 +13,7 @@ import (
var userSearchColumns = []string{"name", "email"}
// NewUser creates a new user
func (d *Datastore) NewUser(user *kolide.User) (*kolide.User, error) {
func (d *Datastore) NewUser(user *fleet.User) (*fleet.User, error) {
sqlStatement := `
INSERT INTO users (
password,
@ -46,14 +46,14 @@ func (d *Datastore) NewUser(user *kolide.User) (*kolide.User, error) {
return user, nil
}
func (d *Datastore) findUser(searchCol string, searchVal interface{}) (*kolide.User, error) {
func (d *Datastore) findUser(searchCol string, searchVal interface{}) (*fleet.User, error) {
sqlStatement := fmt.Sprintf(
"SELECT * FROM users "+
"WHERE %s = ? LIMIT 1",
searchCol,
)
user := &kolide.User{}
user := &fleet.User{}
err := d.db.Get(user, sqlStatement, searchVal)
if err != nil && err == sql.ErrNoRows {
@ -63,7 +63,7 @@ func (d *Datastore) findUser(searchCol string, searchVal interface{}) (*kolide.U
return nil, errors.Wrap(err, "find user")
}
if err := d.loadTeamsForUsers([]*kolide.User{user}); err != nil {
if err := d.loadTeamsForUsers([]*fleet.User{user}); err != nil {
return nil, errors.Wrap(err, "load teams")
}
@ -71,13 +71,13 @@ func (d *Datastore) findUser(searchCol string, searchVal interface{}) (*kolide.U
}
// User retrieves a user by name
func (d *Datastore) User(username string) (*kolide.User, error) {
func (d *Datastore) User(username string) (*fleet.User, error) {
return d.findUser("username", username)
}
// ListUsers lists all users with team ID, limit, sort and offset passed in with
// UserListOptions.
func (d *Datastore) ListUsers(opt kolide.UserListOptions) ([]*kolide.User, error) {
func (d *Datastore) ListUsers(opt fleet.UserListOptions) ([]*fleet.User, error) {
sqlStatement := `
SELECT * FROM users
WHERE TRUE
@ -90,7 +90,7 @@ func (d *Datastore) ListUsers(opt kolide.UserListOptions) ([]*kolide.User, error
sqlStatement, params = searchLike(sqlStatement, params, opt.MatchQuery, userSearchColumns...)
sqlStatement = appendListOptionsToSQL(sqlStatement, opt.ListOptions)
users := []*kolide.User{}
users := []*fleet.User{}
if err := d.db.Select(&users, sqlStatement, params...); err != nil {
return nil, errors.Wrap(err, "list users")
@ -104,15 +104,15 @@ func (d *Datastore) ListUsers(opt kolide.UserListOptions) ([]*kolide.User, error
}
func (d *Datastore) UserByEmail(email string) (*kolide.User, error) {
func (d *Datastore) UserByEmail(email string) (*fleet.User, error) {
return d.findUser("email", email)
}
func (d *Datastore) UserByID(id uint) (*kolide.User, error) {
func (d *Datastore) UserByID(id uint) (*fleet.User, error) {
return d.findUser("id", id)
}
func (d *Datastore) SaveUser(user *kolide.User) error {
func (d *Datastore) SaveUser(user *fleet.User) error {
sqlStatement := `
UPDATE users SET
username = ?,
@ -151,15 +151,15 @@ func (d *Datastore) SaveUser(user *kolide.User) error {
}
// loadTeamsForUsers will load the teams/roles for the provided users.
func (d *Datastore) loadTeamsForUsers(users []*kolide.User) error {
func (d *Datastore) loadTeamsForUsers(users []*fleet.User) error {
userIDs := make([]uint, 0, len(users)+1)
// Make sure the slice is never empty for IN by filling a nonexistent ID
userIDs = append(userIDs, 0)
idToUser := make(map[uint]*kolide.User, len(users))
idToUser := make(map[uint]*fleet.User, len(users))
for _, u := range users {
// Initialize empty slice so we get an array in JSON responses instead
// of null if it is empty
u.Teams = []kolide.UserTeam{}
u.Teams = []fleet.UserTeam{}
// Track IDs for queries and matching
userIDs = append(userIDs, u.ID)
idToUser[u.ID] = u
@ -177,7 +177,7 @@ func (d *Datastore) loadTeamsForUsers(users []*kolide.User) error {
}
var rows []struct {
kolide.UserTeam
fleet.UserTeam
UserID uint `db:"user_id"`
}
if err := d.db.Select(&rows, sql, args...); err != nil {
@ -193,7 +193,7 @@ func (d *Datastore) loadTeamsForUsers(users []*kolide.User) error {
return nil
}
func (d *Datastore) saveTeamsForUser(user *kolide.User) error {
func (d *Datastore) saveTeamsForUser(user *fleet.User) error {
// Do a full teams update by deleting existing teams and then inserting all
// the current teams in a single transaction.
if err := d.withRetryTxx(func(tx *sqlx.Tx) error {

View File

@ -9,7 +9,7 @@ import (
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
@ -24,13 +24,13 @@ const (
// generateS3Key builds S3 key from carve metadata
// all keys are prefixed by date so that they can easily be listed chronologically
func (d *Datastore) generateS3Key(metadata *kolide.CarveMetadata) string {
func (d *Datastore) generateS3Key(metadata *fleet.CarveMetadata) string {
simpleDateHour := metadata.CreatedAt.Format(timePrefixFormat)
return fmt.Sprintf("%s%s/%s", d.prefix, simpleDateHour, metadata.Name)
}
// NewCarve initializes a new file carving session
func (d *Datastore) NewCarve(metadata *kolide.CarveMetadata) (*kolide.CarveMetadata, error) {
func (d *Datastore) NewCarve(metadata *fleet.CarveMetadata) (*fleet.CarveMetadata, error) {
objectKey := d.generateS3Key(metadata)
res, err := d.s3client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
Bucket: &d.bucket,
@ -45,7 +45,7 @@ func (d *Datastore) NewCarve(metadata *kolide.CarveMetadata) (*kolide.CarveMetad
// UpdateCarve updates carve definition in database
// Only max_block and expired are updatable
func (d *Datastore) UpdateCarve(metadata *kolide.CarveMetadata) error {
func (d *Datastore) UpdateCarve(metadata *fleet.CarveMetadata) error {
return d.metadatadb.UpdateCarve(metadata)
}
@ -91,8 +91,8 @@ func (d *Datastore) listS3Carves(lastPrefix string, maxKeys int) (map[string]boo
func (d *Datastore) CleanupCarves(now time.Time) (int, error) {
var err error
// Get the 1000 oldest carves
nonExpiredCarves, err := d.ListCarves(kolide.CarveListOptions{
ListOptions: kolide.ListOptions{PerPage: cleanupSize},
nonExpiredCarves, err := d.ListCarves(fleet.CarveListOptions{
ListOptions: fleet.ListOptions{PerPage: cleanupSize},
Expired: false,
})
if err != nil {
@ -118,22 +118,22 @@ func (d *Datastore) CleanupCarves(now time.Time) (int, error) {
}
// Carve returns carve metadata by ID
func (d *Datastore) Carve(carveID int64) (*kolide.CarveMetadata, error) {
func (d *Datastore) Carve(carveID int64) (*fleet.CarveMetadata, error) {
return d.metadatadb.Carve(carveID)
}
// CarveBySessionId returns carve metadata by session ID
func (d *Datastore) CarveBySessionId(sessionID string) (*kolide.CarveMetadata, error) {
func (d *Datastore) CarveBySessionId(sessionID string) (*fleet.CarveMetadata, error) {
return d.metadatadb.CarveBySessionId(sessionID)
}
// CarveByName returns carve metadata by name
func (d *Datastore) CarveByName(name string) (*kolide.CarveMetadata, error) {
func (d *Datastore) CarveByName(name string) (*fleet.CarveMetadata, error) {
return d.metadatadb.CarveByName(name)
}
// ListCarves returns a list of the currently available carves
func (d *Datastore) ListCarves(opt kolide.CarveListOptions) ([]*kolide.CarveMetadata, error) {
func (d *Datastore) ListCarves(opt fleet.CarveListOptions) ([]*fleet.CarveMetadata, error) {
return d.metadatadb.ListCarves(opt)
}
@ -167,7 +167,7 @@ func (d *Datastore) listCompletedParts(objectKey, uploadID string) ([]*s3.Comple
}
// NewBlock uploads a new block for a specific carve
func (d *Datastore) NewBlock(metadata *kolide.CarveMetadata, blockID int64, data []byte) error {
func (d *Datastore) NewBlock(metadata *fleet.CarveMetadata, blockID int64, data []byte) error {
objectKey := d.generateS3Key(metadata)
partNumber := blockID + 1 // PartNumber is 1-indexed
_, err := d.s3client.UploadPart(&s3.UploadPartInput{
@ -206,7 +206,7 @@ func (d *Datastore) NewBlock(metadata *kolide.CarveMetadata, blockID int64, data
}
// GetBlock returns a block of data for a carve
func (d *Datastore) GetBlock(metadata *kolide.CarveMetadata, blockID int64) ([]byte, error) {
func (d *Datastore) GetBlock(metadata *fleet.CarveMetadata, blockID int64) ([]byte, error) {
objectKey := d.generateS3Key(metadata)
// blockID is 0-indexed and sequential so can be perfectly used for evaluating ranges
// range extremes are inclusive as for RFC-2616 (section 14.35)

View File

@ -10,7 +10,7 @@ import (
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/fleetdm/fleet/server/config"
"github.com/fleetdm/fleet/server/kolide"
"github.com/fleetdm/fleet/server/fleet"
"github.com/pkg/errors"
)
@ -19,14 +19,14 @@ const awsRegionHint = "us-east-1"
// Datastore is a type implementing the CarveStore interface
// relying on AWS S3 storage
type Datastore struct {
metadatadb kolide.CarveStore
metadatadb fleet.CarveStore
s3client *s3.S3
bucket string
prefix string
}
// New initializes an S3 Datastore
func New(config config.S3Config, metadatadb kolide.CarveStore) (*Datastore, error) {
func New(config config.S3Config, metadatadb fleet.CarveStore) (*Datastore, error) {
conf := &aws.Config{}
// Use default auth provire if no static credentials were provided

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
const (
// ActionRead refers to reading an entity.

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
// Datastore combines all the interfaces in the Fleet DAL
type Datastore interface {

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"time"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"errors"

View File

@ -1,3 +1,3 @@
package kolide
package fleet
const ApiVersion = "v1"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"testing"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"bytes"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"bytes"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"encoding/json"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
// LiveQueryStore defines an interface for storing and retrieving the status of
// live queries in the Fleet system.

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
type ObjectMetadata struct {
ApiVersion string `json:"apiVersion"`

View File

@ -1,4 +1,4 @@
package kolide
package fleet
type NetworkInterface struct {
UpdateCreateTimestamps

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

View File

@ -1,4 +1,4 @@
package kolide
package fleet
import (
"context"

Some files were not shown because too many files have changed in this diff Show More