Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Ingest Manager] Thread safe sorted set #21290

Merged
merged 3 commits into from
Sep 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions x-pack/elastic-agent/CHANGELOG.next.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
- Docker container is not run as root by default. {pull}21213[21213]

==== Bugfixes
- Thread safe sorted set {pull}21290[21290]
- Copy Action store on upgrade {pull}21298[21298]
- Include inputs in action store actions {pull}21298[21298]

Expand Down
14 changes: 14 additions & 0 deletions x-pack/elastic-agent/pkg/sorted/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ package sorted

import (
"sort"
"sync"
)

// Set is a sorted set that allow to iterate on they keys in an ordered manner, when
// items are added or removed from the Set the keys are sorted.
type Set struct {
mapped map[string]interface{}
keys []string
rwlock sync.RWMutex
}

// NewSet returns an ordered set.
Expand All @@ -24,6 +26,9 @@ func NewSet() *Set {

// Add adds an items to the set.
func (s *Set) Add(k string, v interface{}) {
s.rwlock.Lock()
defer s.rwlock.Unlock()

_, ok := s.mapped[k]
if !ok {
s.keys = append(s.keys, k)
Expand All @@ -35,6 +40,9 @@ func (s *Set) Add(k string, v interface{}) {

// Remove removes an items from the Set.
func (s *Set) Remove(k string) {
s.rwlock.Lock()
defer s.rwlock.Unlock()

_, ok := s.mapped[k]
if !ok {
return
Expand All @@ -50,11 +58,17 @@ func (s *Set) Remove(k string) {

// Get retrieves a specific values from the map and will return false if the key is not found.
func (s *Set) Get(k string) (interface{}, bool) {
s.rwlock.RLock()
defer s.rwlock.RUnlock()

v, ok := s.mapped[k]
return v, ok
}

// Keys returns slice of keys where the keys are ordered alphabetically.
func (s *Set) Keys() []string {
s.rwlock.RLock()
defer s.rwlock.RUnlock()

return append(s.keys[:0:0], s.keys...)
}