Detect centos as a host platform more accurately (#1664)

* Detect centos as a host platform more accurately

* Add test for centos host labels
This commit is contained in:
Tomas Touceda 2021-08-13 13:22:09 -03:00 committed by GitHub
parent a1a1b8c5da
commit 512f5defce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 47 additions and 3 deletions

View file

@ -0,0 +1 @@
* Improve detection of CentOS in label membership.

View file

@ -265,9 +265,20 @@ func (d *Datastore) ListLabels(filter fleet.TeamFilter, opt fleet.ListOptions) (
return labels, nil
}
func platformForHost(host *fleet.Host) string {
if host.Platform != "rhel" {
return host.Platform
}
if strings.Contains(strings.ToLower(host.OSVersion), "centos") {
return "centos"
}
return host.Platform
}
func (d *Datastore) LabelQueriesForHost(host *fleet.Host, cutoff time.Time) (map[string]string, error) {
var rows *sql.Rows
var err error
platform := platformForHost(host)
if host.LabelUpdatedAt.Before(cutoff) {
// Retrieve all labels (with matching platform) for this host
sql := `
@ -276,7 +287,7 @@ func (d *Datastore) LabelQueriesForHost(host *fleet.Host, cutoff time.Time) (map
WHERE platform = ? OR platform = ''
AND label_membership_type = ?
`
rows, err = d.db.Query(sql, host.Platform, fleet.LabelMembershipTypeDynamic)
rows, err = d.db.Query(sql, 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
@ -290,9 +301,9 @@ func (d *Datastore) LabelQueriesForHost(host *fleet.Host, cutoff time.Time) (map
`
rows, err = d.db.Query(
sql,
host.Platform,
platform,
host.LabelUpdatedAt,
host.Platform,
platform,
fleet.LabelMembershipTypeDynamic,
)
}

View file

@ -677,3 +677,35 @@ func TestSaveLabel(t *testing.T) {
assert.Equal(t, label.Name, saved.Name)
assert.Equal(t, label.Description, saved.Description)
}
func TestLabelQueriesForCentOSHost(t *testing.T) {
db := CreateMySQLDS(t)
defer db.Close()
host, err := db.EnrollHost("0", "0", nil, 0)
require.Nil(t, err, "enrollment should succeed")
host.Platform = "rhel"
host.OSVersion = "CentOS 6"
require.NoError(t, db.SaveHost(host))
label, err := db.NewLabel(&fleet.Label{
UpdateCreateTimestamps: fleet.UpdateCreateTimestamps{
CreateTimestamp: fleet.CreateTimestamp{CreatedAt: time.Now()},
UpdateTimestamp: fleet.UpdateTimestamp{UpdatedAt: time.Now()},
},
ID: 42,
Name: "centos labe",
Query: "select 1;",
Platform: "centos",
LabelType: fleet.LabelTypeRegular,
LabelMembershipType: fleet.LabelMembershipTypeDynamic,
})
require.NoError(t, err)
baseTime := time.Now().Add(-5 * time.Minute)
queries, err := db.LabelQueriesForHost(host, baseTime)
require.NoError(t, err)
require.Len(t, queries, 1)
assert.Equal(t, "select 1;", queries[fmt.Sprint(label.ID)])
}