Skip to content

Commit

Permalink
call mtx.Lock() only once
Browse files Browse the repository at this point in the history
  • Loading branch information
santihernandezc authored and grobinson-grafana committed Apr 22, 2024
1 parent e020189 commit ee47641
Showing 1 changed file with 23 additions and 19 deletions.
42 changes: 23 additions & 19 deletions silence/silence.go
Original file line number Diff line number Diff line change
@@ -577,12 +577,35 @@ func (s *Silences) setSilence(sil *pb.Silence, now time.Time, skipValidate bool)
return nil
}

// Upsert allows creating silences with a predefined ID.
func (s *Silences) Upsert(sil *pb.Silence) (string, error) {
s.mtx.Lock()
defer s.mtx.Unlock()

id, err := s.set(sil)
if !errors.Is(err, ErrNotFound) {
return id, err
}

// If the silence was not found, create it with the given ID.
now := s.nowUTC()
if sil.StartsAt.Before(now) {
sil.StartsAt = now
}

return sil.Id, s.setSilence(sil, now, false)
}

// Set the specified silence. If a silence with the ID already exists and the modification
// modifies history, the old silence gets expired and a new one is created.
func (s *Silences) Set(sil *pb.Silence) (string, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
return s.set(sil)
}

// set assumes a lock is being held in the calling method.
func (s *Silences) set(sil *pb.Silence) (string, error) {
now := s.nowUTC()
prev, ok := s.getSilence(sil.Id)

@@ -614,25 +637,6 @@ func (s *Silences) Set(sil *pb.Silence) (string, error) {
return sil.Id, s.setSilence(sil, now, false)
}

// Upsert allows creating silences with a predefined ID.
func (s *Silences) Upsert(sil *pb.Silence) (string, error) {
id, err := s.Set(sil)
if !errors.Is(err, ErrNotFound) {
return id, err
}

// If the silence was not found, create it with the given ID.
s.mtx.Lock()
defer s.mtx.Unlock()

now := s.nowUTC()
if sil.StartsAt.Before(now) {
sil.StartsAt = now
}

return sil.Id, s.setSilence(sil, now, false)
}

// canUpdate returns true if silence a can be updated to b without
// affecting the historic view of silencing.
func canUpdate(a, b *pb.Silence, now time.Time) bool {

0 comments on commit ee47641

Please sign in to comment.