AdGuardHome/internal/querylog/qlog.go
Eugene Burkov 434032f8e3 Pull request: 3772 cache upstreams
Merge in DNS/adguard-home from 3772-cache-upstreams to master

Updates #3772.

Squashed commit of the following:

commit 809e874fe8847fdbd7f8a7221f18393509f41339
Merge: 5774798c 2d328ea8
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Tue Dec 7 17:15:59 2021 +0300

    Merge branch 'master' into 3772-cache-upstreams

commit 5774798ce1897bf292be49410794ce06cd084f93
Author: Ildar Kamalov <ik@adguard.com>
Date:   Tue Dec 7 16:48:38 2021 +0300

    client: fix formatting

commit 4b4bb668c762c9b4d47cf40a007f34fe47a6e260
Author: Ildar Kamalov <ik@adguard.com>
Date:   Tue Dec 7 16:47:18 2021 +0300

    client: remove comment

commit a2a9f904a6ab52194bb811a2a83967660a25f2cc
Author: Ildar Kamalov <ik@adguard.com>
Date:   Tue Dec 7 16:45:31 2021 +0300

    client: handle cached upstream

commit a56804c4910da838cb10c8ef0af2a525e9722b1c
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Fri Nov 26 15:33:43 2021 +0300

    querylog: rm todo

commit 16c0a62ad2dfc7fcb5a6adbc868b296b7840fd27
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Fri Nov 26 15:31:53 2021 +0300

    all: revise log of changes

commit 9f4b793205f17b6e85d74e83126093ed09eb24e3
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Thu Nov 25 17:23:42 2021 +0300

    WIP

commit 7fbc6d596295570d2c61c3e507160f65c9adccb8
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Thu Nov 25 17:03:42 2021 +0300

    all: imp upstream info in querylog
2021-12-07 17:43:51 +03:00

231 lines
5.2 KiB
Go

// Package querylog provides query log functions and interfaces.
package querylog
import (
"fmt"
"net"
"os"
"strings"
"sync"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/timeutil"
"github.com/miekg/dns"
)
const (
queryLogFileName = "querylog.json" // .gz added during compression
)
// queryLog is a structure that writes and reads the DNS query log
type queryLog struct {
findClient func(ids []string) (c *Client, err error)
conf *Config
lock sync.Mutex
logFile string // path to the log file
// bufferLock protects buffer.
bufferLock sync.RWMutex
// buffer contains recent log entries.
buffer []*logEntry
fileFlushLock sync.Mutex // synchronize a file-flushing goroutine and main thread
flushPending bool // don't start another goroutine while the previous one is still running
fileWriteLock sync.Mutex
anonymizer *aghnet.IPMut
}
// ClientProto values are names of the client protocols.
type ClientProto string
// Client protocol names.
const (
ClientProtoDoH ClientProto = "doh"
ClientProtoDoQ ClientProto = "doq"
ClientProtoDoT ClientProto = "dot"
ClientProtoDNSCrypt ClientProto = "dnscrypt"
ClientProtoPlain ClientProto = ""
)
// NewClientProto validates that the client protocol name is valid and returns
// the name as a ClientProto.
func NewClientProto(s string) (cp ClientProto, err error) {
switch cp = ClientProto(s); cp {
case
ClientProtoDoH,
ClientProtoDoQ,
ClientProtoDoT,
ClientProtoDNSCrypt,
ClientProtoPlain:
return cp, nil
default:
return "", fmt.Errorf("invalid client proto: %q", s)
}
}
// logEntry - represents a single log entry
type logEntry struct {
// client is the found client information, if any.
client *Client
IP net.IP `json:"IP"` // Client IP
Time time.Time `json:"T"`
QHost string `json:"QH"`
QType string `json:"QT"`
QClass string `json:"QC"`
ClientID string `json:"CID,omitempty"`
ClientProto ClientProto `json:"CP"`
Answer []byte `json:",omitempty"` // sometimes empty answers happen like binerdunt.top or rev2.globalrootservers.net
OrigAnswer []byte `json:",omitempty"`
Cached bool `json:",omitempty"`
Result filtering.Result
Elapsed time.Duration
Upstream string `json:",omitempty"`
}
func (l *queryLog) Start() {
if l.conf.HTTPRegister != nil {
l.initWeb()
}
go l.periodicRotate()
}
func (l *queryLog) Close() {
_ = l.flushLogBuffer(true)
}
func checkInterval(ivl time.Duration) (ok bool) {
// The constants for possible values of query log's rotation interval.
const (
quarterDay = timeutil.Day / 4
day = timeutil.Day
week = timeutil.Day * 7
month = timeutil.Day * 30
threeMonths = timeutil.Day * 90
)
return ivl == quarterDay || ivl == day || ivl == week || ivl == month || ivl == threeMonths
}
func (l *queryLog) WriteDiskConfig(c *Config) {
*c = *l.conf
}
// Clear memory buffer and remove log files
func (l *queryLog) clear() {
l.fileFlushLock.Lock()
defer l.fileFlushLock.Unlock()
l.bufferLock.Lock()
l.buffer = nil
l.flushPending = false
l.bufferLock.Unlock()
oldLogFile := l.logFile + ".1"
err := os.Remove(oldLogFile)
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Error("removing old log file %q: %s", oldLogFile, err)
}
err = os.Remove(l.logFile)
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Error("removing log file %q: %s", l.logFile, err)
}
log.Debug("Query log: cleared")
}
func (l *queryLog) Add(params AddParams) {
var err error
if !l.conf.Enabled {
return
}
err = params.validate()
if err != nil {
log.Error("querylog: adding record: %s, skipping", err)
return
}
if params.Result == nil {
params.Result = &filtering.Result{}
}
now := time.Now()
entry := logEntry{
IP: params.ClientIP,
Time: now,
Result: *params.Result,
Elapsed: params.Elapsed,
Upstream: params.Upstream,
Cached: params.Cached,
ClientID: params.ClientID,
ClientProto: params.ClientProto,
}
q := params.Question.Question[0]
entry.QHost = strings.ToLower(q.Name[:len(q.Name)-1]) // remove the last dot
entry.QType = dns.Type(q.Qtype).String()
entry.QClass = dns.Class(q.Qclass).String()
if params.Answer != nil {
var a []byte
a, err = params.Answer.Pack()
if err != nil {
log.Error("querylog: Answer.Pack(): %s", err)
return
}
entry.Answer = a
}
if params.OrigAnswer != nil {
var a []byte
a, err = params.OrigAnswer.Pack()
if err != nil {
log.Error("querylog: OrigAnswer.Pack(): %s", err)
return
}
entry.OrigAnswer = a
}
l.bufferLock.Lock()
l.buffer = append(l.buffer, &entry)
needFlush := false
if !l.conf.FileEnabled {
if len(l.buffer) > int(l.conf.MemSize) {
// writing to file is disabled - just remove the oldest entry from array
l.buffer = l.buffer[1:]
}
} else if !l.flushPending {
needFlush = len(l.buffer) >= int(l.conf.MemSize)
if needFlush {
l.flushPending = true
}
}
l.bufferLock.Unlock()
// if buffer needs to be flushed to disk, do it now
if needFlush {
go func() {
_ = l.flushLogBuffer(false)
}()
}
}