Skip to content

Commit

Permalink
control concurrent access to cached queries with mutex to avoid race …
Browse files Browse the repository at this point in the history
…conditions
  • Loading branch information
Lagovas committed Nov 30, 2021
1 parent 2a7d86f commit 382f79c
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions acra-censor/common/logging_logic.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ func NewFileQueryWriter(filePath string) (*QueryWriter, error) {

// WalkQueries walks through each query and perform some action on it
func (queryWriter *QueryWriter) WalkQueries(visitor func(query *QueryInfo) error) error {
queryWriter.mutex.Lock()
defer queryWriter.mutex.Unlock()
queryWriter.mutex.RLock()
defer queryWriter.mutex.RUnlock()
for _, query := range queryWriter.Queries {
if err := visitor(query); err != nil {
return err
Expand All @@ -102,9 +102,9 @@ func (queryWriter *QueryWriter) WalkQueries(visitor func(query *QueryInfo) error

// DumpQueries writes all queries into file
func (queryWriter *QueryWriter) DumpQueries() error {
queryWriter.mutex.Lock()
queryWriter.mutex.RLock()
rawData := queryWriter.serializeQueries(queryWriter.Queries)
queryWriter.mutex.Unlock()
queryWriter.mutex.RUnlock()
if err := queryWriter.logStorage.WriteAll(rawData); err != nil {
queryWriter.logger.WithError(err).WithField(logging.FieldKeyEventCode, logging.EventCodeErrorCensorIOError).Errorln("Can't dump queries to storage")
return err
Expand Down Expand Up @@ -181,14 +181,16 @@ func (queryWriter *QueryWriter) readStoredQueries() error {
queryWriter.logger.WithError(err).WithField(logging.FieldKeyEventCode, logging.EventCodeErrorCensorIOError).Errorln("Can't read stored queries")
return err
}
queryWriter.mutex.Lock()
queryWriter.Queries = q
queryWriter.queryIndex = len(q)
queryWriter.mutex.Unlock()
return nil
}

func (queryWriter *QueryWriter) dumpBufferedQueries() error {
queryWriter.mutex.Lock()
defer queryWriter.mutex.Unlock()
queryWriter.mutex.RLock()
defer queryWriter.mutex.RUnlock()

if len(queryWriter.Queries) != 0 {
partialRawData := queryWriter.serializeQueries(queryWriter.Queries[queryWriter.queryIndex:])
Expand Down Expand Up @@ -240,6 +242,8 @@ func (queryWriter *QueryWriter) serializeQueries(queries []*QueryInfo) []byte {
}

func (queryWriter *QueryWriter) captureQuery(query string) {
queryWriter.mutex.Lock()
defer queryWriter.mutex.Unlock()
//skip already captured queries
for _, queryInfo := range queryWriter.Queries {
if strings.EqualFold(queryInfo.RawQuery, query) {
Expand Down

0 comments on commit 382f79c

Please sign in to comment.