* use new logger - AdguardTeam/golibs/log

This commit is contained in:
Simon Zolin 2019-02-25 16:44:22 +03:00
parent 4476262357
commit 5cb6d97cd7
21 changed files with 157 additions and 118 deletions

30
app.go
View File

@ -3,7 +3,6 @@ package main
import ( import (
"crypto/tls" "crypto/tls"
"fmt" "fmt"
stdlog "log"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -15,9 +14,8 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/AdguardTeam/golibs/log"
"github.com/gobuffalo/packr" "github.com/gobuffalo/packr"
"github.com/hmage/golibs/log"
) )
// VersionString will be set through ldflags, contains current version // VersionString will be set through ldflags, contains current version
@ -73,9 +71,9 @@ func run(args options) {
// print the first message after logger is configured // print the first message after logger is configured
log.Printf("AdGuard Home, version %s\n", VersionString) log.Printf("AdGuard Home, version %s\n", VersionString)
log.Tracef("Current working directory is %s", config.ourWorkingDir) log.Debug("Current working directory is %s", config.ourWorkingDir)
if args.runningAsService { if args.runningAsService {
log.Printf("AdGuard Home is running as a service") log.Info("AdGuard Home is running as a service")
} }
config.firstRun = detectFirstRun() config.firstRun = detectFirstRun()
@ -110,7 +108,7 @@ func run(args options) {
err = filter.load() err = filter.load()
if err != nil { if err != nil {
// This is okay for the first start, the filter will be loaded later // This is okay for the first start, the filter will be loaded later
log.Printf("Couldn't load filter %d contents due to %s", filter.ID, err) log.Debug("Couldn't load filter %d contents due to %s", filter.ID, err)
// clear LastUpdated so it gets fetched right away // clear LastUpdated so it gets fetched right away
} }
@ -161,7 +159,7 @@ func run(args options) {
// add handlers for /install paths, we only need them when we're not configured yet // add handlers for /install paths, we only need them when we're not configured yet
if config.firstRun { if config.firstRun {
log.Printf("This is the first launch of AdGuard Home, redirecting everything to /install.html ") log.Info("This is the first launch of AdGuard Home, redirecting everything to /install.html ")
http.Handle("/install.html", preInstallHandler(http.FileServer(box))) http.Handle("/install.html", preInstallHandler(http.FileServer(box)))
registerInstallHandlers() registerInstallHandlers()
} }
@ -263,7 +261,11 @@ func configureLogger(args options) {
ls.LogFile = args.logFile ls.LogFile = args.logFile
} }
log.Verbose = ls.Verbose level := log.INFO
if ls.Verbose {
level = log.DEBUG
}
log.SetLevel(level)
if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" { if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
// When running as a Windows service, use eventlog by default if nothing else is configured // When running as a Windows service, use eventlog by default if nothing else is configured
@ -287,20 +289,20 @@ func configureLogger(args options) {
if err != nil { if err != nil {
log.Fatalf("cannot create a log file: %s", err) log.Fatalf("cannot create a log file: %s", err)
} }
stdlog.SetOutput(file) log.SetOutput(file)
} }
} }
func cleanup() { func cleanup() {
log.Printf("Stopping AdGuard Home") log.Info("Stopping AdGuard Home")
err := stopDNSServer() err := stopDNSServer()
if err != nil { if err != nil {
log.Printf("Couldn't stop DNS server: %s", err) log.Error("Couldn't stop DNS server: %s", err)
} }
err = stopDHCPServer() err = stopDHCPServer()
if err != nil { if err != nil {
log.Printf("Couldn't stop DHCP server: %s", err) log.Error("Couldn't stop DHCP server: %s", err)
} }
} }
@ -373,7 +375,7 @@ func loadOptions() options {
if v == "--"+opt.longName || (opt.shortName != "" && v == "-"+opt.shortName) { if v == "--"+opt.longName || (opt.shortName != "" && v == "-"+opt.shortName) {
if opt.callbackWithValue != nil { if opt.callbackWithValue != nil {
if i+1 >= len(os.Args) { if i+1 >= len(os.Args) {
log.Printf("ERROR: Got %s without argument\n", v) log.Error("Got %s without argument\n", v)
os.Exit(64) os.Exit(64)
} }
i++ i++
@ -386,7 +388,7 @@ func loadOptions() options {
} }
} }
if !knownParam { if !knownParam {
log.Printf("ERROR: unknown option %v\n", v) log.Error("unknown option %v\n", v)
printHelp() printHelp()
os.Exit(64) os.Exit(64)
} }

View File

@ -10,7 +10,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/dhcpd" "github.com/AdguardTeam/AdGuardHome/dhcpd"
"github.com/AdguardTeam/AdGuardHome/dnsfilter" "github.com/AdguardTeam/AdGuardHome/dnsfilter"
"github.com/AdguardTeam/AdGuardHome/dnsforward" "github.com/AdguardTeam/AdGuardHome/dnsforward"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
yaml "gopkg.in/yaml.v2" yaml "gopkg.in/yaml.v2"
) )
@ -152,7 +152,7 @@ func getLogSettings() logSettings {
} }
err = yaml.Unmarshal(yamlFile, &l) err = yaml.Unmarshal(yamlFile, &l)
if err != nil { if err != nil {
log.Printf("Couldn't get logging settings from the configuration: %s", err) log.Error("Couldn't get logging settings from the configuration: %s", err)
} }
return l return l
} }
@ -160,19 +160,19 @@ func getLogSettings() logSettings {
// parseConfig loads configuration from the YAML file // parseConfig loads configuration from the YAML file
func parseConfig() error { func parseConfig() error {
configFile := config.getConfigFilename() configFile := config.getConfigFilename()
log.Printf("Reading config file: %s", configFile) log.Debug("Reading config file: %s", configFile)
yamlFile, err := readConfigFile() yamlFile, err := readConfigFile()
if err != nil { if err != nil {
log.Printf("Couldn't read config file: %s", err) log.Error("Couldn't read config file: %s", err)
return err return err
} }
if yamlFile == nil { if yamlFile == nil {
log.Printf("YAML file doesn't exist, skipping it") log.Error("YAML file doesn't exist, skipping it")
return nil return nil
} }
err = yaml.Unmarshal(yamlFile, &config) err = yaml.Unmarshal(yamlFile, &config)
if err != nil { if err != nil {
log.Printf("Couldn't parse config file: %s", err) log.Error("Couldn't parse config file: %s", err)
return err return err
} }
@ -199,19 +199,19 @@ func (c *configuration) write() error {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
if config.firstRun { if config.firstRun {
log.Tracef("Silently refusing to write config because first run and not configured yet") log.Debug("Silently refusing to write config because first run and not configured yet")
return nil return nil
} }
configFile := config.getConfigFilename() configFile := config.getConfigFilename()
log.Tracef("Writing YAML file: %s", configFile) log.Debug("Writing YAML file: %s", configFile)
yamlText, err := yaml.Marshal(&config) yamlText, err := yaml.Marshal(&config)
if err != nil { if err != nil {
log.Printf("Couldn't generate YAML file: %s", err) log.Error("Couldn't generate YAML file: %s", err)
return err return err
} }
err = safeWriteFile(configFile, yamlText) err = safeWriteFile(configFile, yamlText)
if err != nil { if err != nil {
log.Printf("Couldn't save YAML config: %s", err) log.Error("Couldn't save YAML config: %s", err)
return err return err
} }
@ -221,14 +221,14 @@ func (c *configuration) write() error {
func writeAllConfigs() error { func writeAllConfigs() error {
err := config.write() err := config.write()
if err != nil { if err != nil {
log.Printf("Couldn't write config: %s", err) log.Error("Couldn't write config: %s", err)
return err return err
} }
userFilter := userFilter() userFilter := userFilter()
err = userFilter.save() err = userFilter.save()
if err != nil { if err != nil {
log.Printf("Couldn't save the user filter: %s", err) log.Error("Couldn't save the user filter: %s", err)
return err return err
} }

View File

@ -24,8 +24,8 @@ import (
"time" "time"
"github.com/AdguardTeam/AdGuardHome/dnsforward" "github.com/AdguardTeam/AdGuardHome/dnsforward"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/hmage/golibs/log"
"github.com/joomcode/errorx" "github.com/joomcode/errorx"
"github.com/miekg/dns" "github.com/miekg/dns"
govalidator "gopkg.in/asaskevich/govalidator.v4" govalidator "gopkg.in/asaskevich/govalidator.v4"
@ -52,14 +52,14 @@ func returnOK(w http.ResponseWriter) {
_, err := fmt.Fprintf(w, "OK\n") _, err := fmt.Fprintf(w, "OK\n")
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write body: %s", err) errorText := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
} }
func httpError(w http.ResponseWriter, code int, format string, args ...interface{}) { func httpError(w http.ResponseWriter, code int, format string, args ...interface{}) {
text := fmt.Sprintf(format, args...) text := fmt.Sprintf(format, args...)
log.Println(text) log.Info(text)
http.Error(w, text, code) http.Error(w, text, code)
} }
@ -69,7 +69,7 @@ func httpError(w http.ResponseWriter, code int, format string, args ...interface
func writeAllConfigsAndReloadDNS() error { func writeAllConfigsAndReloadDNS() error {
err := writeAllConfigs() err := writeAllConfigs()
if err != nil { if err != nil {
log.Printf("Couldn't write all configs: %s", err) log.Error("Couldn't write all configs: %s", err)
return err return err
} }
return reconfigureDNSServer() return reconfigureDNSServer()
@ -85,6 +85,7 @@ func httpUpdateConfigReloadDNSReturnOK(w http.ResponseWriter, r *http.Request) {
} }
func handleStatus(w http.ResponseWriter, r *http.Request) { func handleStatus(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data := map[string]interface{}{ data := map[string]interface{}{
"dns_address": config.DNS.BindHost, "dns_address": config.DNS.BindHost,
"http_port": config.BindPort, "http_port": config.BindPort,
@ -101,7 +102,7 @@ func handleStatus(w http.ResponseWriter, r *http.Request) {
jsonVal, err := json.Marshal(data) jsonVal, err := json.Marshal(data)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -109,18 +110,20 @@ func handleStatus(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(jsonVal) _, err = w.Write(jsonVal)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
} }
func handleProtectionEnable(w http.ResponseWriter, r *http.Request) { func handleProtectionEnable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.ProtectionEnabled = true config.DNS.ProtectionEnabled = true
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleProtectionDisable(w http.ResponseWriter, r *http.Request) { func handleProtectionDisable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.ProtectionEnabled = false config.DNS.ProtectionEnabled = false
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
@ -129,22 +132,25 @@ func handleProtectionDisable(w http.ResponseWriter, r *http.Request) {
// stats // stats
// ----- // -----
func handleQueryLogEnable(w http.ResponseWriter, r *http.Request) { func handleQueryLogEnable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.QueryLogEnabled = true config.DNS.QueryLogEnabled = true
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleQueryLogDisable(w http.ResponseWriter, r *http.Request) { func handleQueryLogDisable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.QueryLogEnabled = false config.DNS.QueryLogEnabled = false
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleQueryLog(w http.ResponseWriter, r *http.Request) { func handleQueryLog(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data := dnsServer.GetQueryLog() data := dnsServer.GetQueryLog()
jsonVal, err := json.Marshal(data) jsonVal, err := json.Marshal(data)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't marshal data into json: %s", err) errorText := fmt.Sprintf("Couldn't marshal data into json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
return return
} }
@ -153,12 +159,13 @@ func handleQueryLog(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(jsonVal) _, err = w.Write(jsonVal)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
} }
func handleStatsTop(w http.ResponseWriter, r *http.Request) { func handleStatsTop(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
s := dnsServer.GetStatsTop() s := dnsServer.GetStatsTop()
// use manual json marshalling because we want maps to be sorted by value // use manual json marshalling because we want maps to be sorted by value
@ -200,30 +207,32 @@ func handleStatsTop(w http.ResponseWriter, r *http.Request) {
_, err := w.Write(statsJSON.Bytes()) _, err := w.Write(statsJSON.Bytes())
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write body: %s", err) errorText := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
} }
// handleStatsReset resets the stats caches // handleStatsReset resets the stats caches
func handleStatsReset(w http.ResponseWriter, r *http.Request) { func handleStatsReset(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
dnsServer.PurgeStats() dnsServer.PurgeStats()
_, err := fmt.Fprintf(w, "OK\n") _, err := fmt.Fprintf(w, "OK\n")
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write body: %s", err) errorText := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
} }
// handleStats returns aggregated stats data for the 24 hours // handleStats returns aggregated stats data for the 24 hours
func handleStats(w http.ResponseWriter, r *http.Request) { func handleStats(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
summed := dnsServer.GetAggregatedStats() summed := dnsServer.GetAggregatedStats()
statsJSON, err := json.Marshal(summed) statsJSON, err := json.Marshal(summed)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -231,7 +240,7 @@ func handleStats(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(statsJSON) _, err = w.Write(statsJSON)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -239,6 +248,7 @@ func handleStats(w http.ResponseWriter, r *http.Request) {
// HandleStatsHistory returns historical stats data for the 24 hours // HandleStatsHistory returns historical stats data for the 24 hours
func handleStatsHistory(w http.ResponseWriter, r *http.Request) { func handleStatsHistory(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
// handle time unit and prepare our time window size // handle time unit and prepare our time window size
timeUnitString := r.URL.Query().Get("time_unit") timeUnitString := r.URL.Query().Get("time_unit")
var timeUnit time.Duration var timeUnit time.Duration
@ -260,14 +270,14 @@ func handleStatsHistory(w http.ResponseWriter, r *http.Request) {
startTime, err := time.Parse(time.RFC3339, r.URL.Query().Get("start_time")) startTime, err := time.Parse(time.RFC3339, r.URL.Query().Get("start_time"))
if err != nil { if err != nil {
errorText := fmt.Sprintf("Must specify valid start_time parameter: %s", err) errorText := fmt.Sprintf("Must specify valid start_time parameter: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
endTime, err := time.Parse(time.RFC3339, r.URL.Query().Get("end_time")) endTime, err := time.Parse(time.RFC3339, r.URL.Query().Get("end_time"))
if err != nil { if err != nil {
errorText := fmt.Sprintf("Must specify valid end_time parameter: %s", err) errorText := fmt.Sprintf("Must specify valid end_time parameter: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
@ -282,7 +292,7 @@ func handleStatsHistory(w http.ResponseWriter, r *http.Request) {
statsJSON, err := json.Marshal(data) statsJSON, err := json.Marshal(data)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
return return
} }
@ -291,7 +301,7 @@ func handleStatsHistory(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(statsJSON) _, err = w.Write(statsJSON)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
return return
} }
@ -323,10 +333,11 @@ func sortByValue(m map[string]int) []string {
// ----------------------- // -----------------------
func handleSetUpstreamDNS(w http.ResponseWriter, r *http.Request) { func handleSetUpstreamDNS(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Failed to read request body: %s", err) errorText := fmt.Sprintf("Failed to read request body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
@ -342,30 +353,31 @@ func handleSetUpstreamDNS(w http.ResponseWriter, r *http.Request) {
err = writeAllConfigs() err = writeAllConfigs()
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write config file: %s", err) errorText := fmt.Sprintf("Couldn't write config file: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
return return
} }
err = reconfigureDNSServer() err = reconfigureDNSServer()
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't reconfigure the DNS server: %s", err) errorText := fmt.Sprintf("Couldn't reconfigure the DNS server: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
return return
} }
_, err = fmt.Fprintf(w, "OK %d servers\n", len(hosts)) _, err = fmt.Fprintf(w, "OK %d servers\n", len(hosts))
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write body: %s", err) errorText := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
} }
func handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) { func handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Failed to read request body: %s", err) errorText := fmt.Sprintf("Failed to read request body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 400) http.Error(w, errorText, 400)
return return
} }
@ -373,7 +385,7 @@ func handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) {
if len(hosts) == 0 { if len(hosts) == 0 {
errorText := fmt.Sprintf("No servers specified") errorText := fmt.Sprintf("No servers specified")
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
@ -383,7 +395,7 @@ func handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) {
for _, host := range hosts { for _, host := range hosts {
err = checkDNS(host) err = checkDNS(host)
if err != nil { if err != nil {
log.Println(err) log.Info("%v", err)
result[host] = err.Error() result[host] = err.Error()
} else { } else {
result[host] = "OK" result[host] = "OK"
@ -393,7 +405,7 @@ func handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) {
jsonVal, err := json.Marshal(result) jsonVal, err := json.Marshal(result)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
return return
} }
@ -402,13 +414,13 @@ func handleTestUpstreamDNS(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(jsonVal) _, err = w.Write(jsonVal)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write body: %s", err) errorText := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
} }
func checkDNS(input string) error { func checkDNS(input string) error {
log.Printf("Checking if DNS %s works...", input) log.Debug("Checking if DNS %s works...", input)
u, err := upstream.AddressToUpstream(input, upstream.Options{Timeout: dnsforward.DefaultTimeout}) u, err := upstream.AddressToUpstream(input, upstream.Options{Timeout: dnsforward.DefaultTimeout})
if err != nil { if err != nil {
return fmt.Errorf("failed to choose upstream for %s: %s", input, err) return fmt.Errorf("failed to choose upstream for %s: %s", input, err)
@ -433,11 +445,12 @@ func checkDNS(input string) error {
} }
} }
log.Printf("DNS %s works OK", input) log.Debug("DNS %s works OK", input)
return nil return nil
} }
func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) { func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
now := time.Now() now := time.Now()
if now.Sub(versionCheckLastTime) <= versionCheckPeriod && len(versionCheckJSON) != 0 { if now.Sub(versionCheckLastTime) <= versionCheckPeriod && len(versionCheckJSON) != 0 {
// return cached copy // return cached copy
@ -449,7 +462,7 @@ func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) {
resp, err := client.Get(versionCheckURL) resp, err := client.Get(versionCheckURL)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't get version check json from %s: %T %s\n", versionCheckURL, err, err) errorText := fmt.Sprintf("Couldn't get version check json from %s: %T %s\n", versionCheckURL, err, err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadGateway) http.Error(w, errorText, http.StatusBadGateway)
return return
} }
@ -461,7 +474,7 @@ func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't read response body from %s: %s", versionCheckURL, err) errorText := fmt.Sprintf("Couldn't read response body from %s: %s", versionCheckURL, err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadGateway) http.Error(w, errorText, http.StatusBadGateway)
return return
} }
@ -470,7 +483,7 @@ func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(body) _, err = w.Write(body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write body: %s", err) errorText := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
@ -483,16 +496,19 @@ func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) {
// --------- // ---------
func handleFilteringEnable(w http.ResponseWriter, r *http.Request) { func handleFilteringEnable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.FilteringEnabled = true config.DNS.FilteringEnabled = true
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleFilteringDisable(w http.ResponseWriter, r *http.Request) { func handleFilteringDisable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.FilteringEnabled = false config.DNS.FilteringEnabled = false
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleFilteringStatus(w http.ResponseWriter, r *http.Request) { func handleFilteringStatus(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data := map[string]interface{}{ data := map[string]interface{}{
"enabled": config.DNS.FilteringEnabled, "enabled": config.DNS.FilteringEnabled,
} }
@ -505,7 +521,7 @@ func handleFilteringStatus(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -514,13 +530,14 @@ func handleFilteringStatus(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(jsonVal) _, err = w.Write(jsonVal)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
} }
func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) { func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
f := filter{} f := filter{}
err := json.NewDecoder(r.Body).Decode(&f) err := json.NewDecoder(r.Body).Decode(&f)
if err != nil { if err != nil {
@ -542,7 +559,7 @@ func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
for i := range config.Filters { for i := range config.Filters {
if config.Filters[i].URL == f.URL { if config.Filters[i].URL == f.URL {
errorText := fmt.Sprintf("Filter URL already added -- %s", f.URL) errorText := fmt.Sprintf("Filter URL already added -- %s", f.URL)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
@ -556,19 +573,19 @@ func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
ok, err := f.update(true) ok, err := f.update(true)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't fetch filter from url %s: %s", f.URL, err) errorText := fmt.Sprintf("Couldn't fetch filter from url %s: %s", f.URL, err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
if f.RulesCount == 0 { if f.RulesCount == 0 {
errorText := fmt.Sprintf("Filter at the url %s has no rules (maybe it points to blank page?)", f.URL) errorText := fmt.Sprintf("Filter at the url %s has no rules (maybe it points to blank page?)", f.URL)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
if !ok { if !ok {
errorText := fmt.Sprintf("Filter at the url %s is invalid (maybe it points to blank page?)", f.URL) errorText := fmt.Sprintf("Filter at the url %s is invalid (maybe it points to blank page?)", f.URL)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
@ -577,7 +594,7 @@ func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
err = f.save() err = f.save()
if err != nil { if err != nil {
errorText := fmt.Sprintf("Failed to save filter %d due to %s", f.ID, err) errorText := fmt.Sprintf("Failed to save filter %d due to %s", f.ID, err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
@ -588,7 +605,7 @@ func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
err = writeAllConfigs() err = writeAllConfigs()
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write config file: %s", err) errorText := fmt.Sprintf("Couldn't write config file: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
return return
} }
@ -596,23 +613,24 @@ func handleFilteringAddURL(w http.ResponseWriter, r *http.Request) {
err = reconfigureDNSServer() err = reconfigureDNSServer()
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't reconfigure the DNS server: %s", err) errorText := fmt.Sprintf("Couldn't reconfigure the DNS server: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
_, err = fmt.Fprintf(w, "OK %d rules\n", f.RulesCount) _, err = fmt.Fprintf(w, "OK %d rules\n", f.RulesCount)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Couldn't write body: %s", err) errorText := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusInternalServerError) http.Error(w, errorText, http.StatusInternalServerError)
} }
} }
func handleFilteringRemoveURL(w http.ResponseWriter, r *http.Request) { func handleFilteringRemoveURL(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
parameters, err := parseParametersFromBody(r.Body) parameters, err := parseParametersFromBody(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("failed to parse parameters from body: %s", err) errorText := fmt.Sprintf("failed to parse parameters from body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 400) http.Error(w, errorText, 400)
return return
} }
@ -649,10 +667,11 @@ func handleFilteringRemoveURL(w http.ResponseWriter, r *http.Request) {
} }
func handleFilteringEnableURL(w http.ResponseWriter, r *http.Request) { func handleFilteringEnableURL(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
parameters, err := parseParametersFromBody(r.Body) parameters, err := parseParametersFromBody(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("failed to parse parameters from body: %s", err) errorText := fmt.Sprintf("failed to parse parameters from body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 400) http.Error(w, errorText, 400)
return return
} }
@ -688,10 +707,11 @@ func handleFilteringEnableURL(w http.ResponseWriter, r *http.Request) {
} }
func handleFilteringDisableURL(w http.ResponseWriter, r *http.Request) { func handleFilteringDisableURL(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
parameters, err := parseParametersFromBody(r.Body) parameters, err := parseParametersFromBody(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("failed to parse parameters from body: %s", err) errorText := fmt.Sprintf("failed to parse parameters from body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 400) http.Error(w, errorText, 400)
return return
} }
@ -725,10 +745,11 @@ func handleFilteringDisableURL(w http.ResponseWriter, r *http.Request) {
} }
func handleFilteringSetRules(w http.ResponseWriter, r *http.Request) { func handleFilteringSetRules(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Failed to read request body: %s", err) errorText := fmt.Sprintf("Failed to read request body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 400) http.Error(w, errorText, 400)
return return
} }
@ -738,6 +759,7 @@ func handleFilteringSetRules(w http.ResponseWriter, r *http.Request) {
} }
func handleFilteringRefresh(w http.ResponseWriter, r *http.Request) { func handleFilteringRefresh(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
force := r.URL.Query().Get("force") force := r.URL.Query().Get("force")
updated := refreshFiltersIfNecessary(force != "") updated := refreshFiltersIfNecessary(force != "")
fmt.Fprintf(w, "OK %d filters updated\n", updated) fmt.Fprintf(w, "OK %d filters updated\n", updated)
@ -748,23 +770,26 @@ func handleFilteringRefresh(w http.ResponseWriter, r *http.Request) {
// ------------ // ------------
func handleSafeBrowsingEnable(w http.ResponseWriter, r *http.Request) { func handleSafeBrowsingEnable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.SafeBrowsingEnabled = true config.DNS.SafeBrowsingEnabled = true
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleSafeBrowsingDisable(w http.ResponseWriter, r *http.Request) { func handleSafeBrowsingDisable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.SafeBrowsingEnabled = false config.DNS.SafeBrowsingEnabled = false
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleSafeBrowsingStatus(w http.ResponseWriter, r *http.Request) { func handleSafeBrowsingStatus(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data := map[string]interface{}{ data := map[string]interface{}{
"enabled": config.DNS.SafeBrowsingEnabled, "enabled": config.DNS.SafeBrowsingEnabled,
} }
jsonVal, err := json.Marshal(data) jsonVal, err := json.Marshal(data)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
} }
@ -772,7 +797,7 @@ func handleSafeBrowsingStatus(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(jsonVal) _, err = w.Write(jsonVal)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -782,10 +807,11 @@ func handleSafeBrowsingStatus(w http.ResponseWriter, r *http.Request) {
// parental // parental
// -------- // --------
func handleParentalEnable(w http.ResponseWriter, r *http.Request) { func handleParentalEnable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
parameters, err := parseParametersFromBody(r.Body) parameters, err := parseParametersFromBody(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("failed to parse parameters from body: %s", err) errorText := fmt.Sprintf("failed to parse parameters from body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 400) http.Error(w, errorText, 400)
return return
} }
@ -828,11 +854,13 @@ func handleParentalEnable(w http.ResponseWriter, r *http.Request) {
} }
func handleParentalDisable(w http.ResponseWriter, r *http.Request) { func handleParentalDisable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.ParentalEnabled = false config.DNS.ParentalEnabled = false
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleParentalStatus(w http.ResponseWriter, r *http.Request) { func handleParentalStatus(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data := map[string]interface{}{ data := map[string]interface{}{
"enabled": config.DNS.ParentalEnabled, "enabled": config.DNS.ParentalEnabled,
} }
@ -842,7 +870,7 @@ func handleParentalStatus(w http.ResponseWriter, r *http.Request) {
jsonVal, err := json.Marshal(data) jsonVal, err := json.Marshal(data)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -851,7 +879,7 @@ func handleParentalStatus(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(jsonVal) _, err = w.Write(jsonVal)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -862,23 +890,26 @@ func handleParentalStatus(w http.ResponseWriter, r *http.Request) {
// ------------ // ------------
func handleSafeSearchEnable(w http.ResponseWriter, r *http.Request) { func handleSafeSearchEnable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.SafeSearchEnabled = true config.DNS.SafeSearchEnabled = true
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleSafeSearchDisable(w http.ResponseWriter, r *http.Request) { func handleSafeSearchDisable(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
config.DNS.SafeSearchEnabled = false config.DNS.SafeSearchEnabled = false
httpUpdateConfigReloadDNSReturnOK(w, r) httpUpdateConfigReloadDNSReturnOK(w, r)
} }
func handleSafeSearchStatus(w http.ResponseWriter, r *http.Request) { func handleSafeSearchStatus(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data := map[string]interface{}{ data := map[string]interface{}{
"enabled": config.DNS.SafeSearchEnabled, "enabled": config.DNS.SafeSearchEnabled,
} }
jsonVal, err := json.Marshal(data) jsonVal, err := json.Marshal(data)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to marshal status json: %s", err) errorText := fmt.Sprintf("Unable to marshal status json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -887,7 +918,7 @@ func handleSafeSearchStatus(w http.ResponseWriter, r *http.Request) {
_, err = w.Write(jsonVal) _, err = w.Write(jsonVal)
if err != nil { if err != nil {
errorText := fmt.Sprintf("Unable to write response json: %s", err) errorText := fmt.Sprintf("Unable to write response json: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, 500) http.Error(w, errorText, 500)
return return
} }
@ -908,6 +939,7 @@ type firstRunData struct {
} }
func handleInstallGetAddresses(w http.ResponseWriter, r *http.Request) { func handleInstallGetAddresses(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data := firstRunData{} data := firstRunData{}
// find out if port 80 is available -- if not, fall back to 3000 // find out if port 80 is available -- if not, fall back to 3000
@ -943,6 +975,7 @@ func handleInstallGetAddresses(w http.ResponseWriter, r *http.Request) {
} }
func handleInstallConfigure(w http.ResponseWriter, r *http.Request) { func handleInstallConfigure(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
newSettings := firstRunData{} newSettings := firstRunData{}
err := json.NewDecoder(r.Body).Decode(&newSettings) err := json.NewDecoder(r.Body).Decode(&newSettings)
if err != nil { if err != nil {
@ -1001,10 +1034,12 @@ func handleInstallConfigure(w http.ResponseWriter, r *http.Request) {
// TLS // TLS
// --- // ---
func handleTLSStatus(w http.ResponseWriter, r *http.Request) { func handleTLSStatus(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
marshalTLS(w, config.TLS) marshalTLS(w, config.TLS)
} }
func handleTLSValidate(w http.ResponseWriter, r *http.Request) { func handleTLSValidate(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data, err := unmarshalTLS(r) data, err := unmarshalTLS(r)
if err != nil { if err != nil {
httpError(w, http.StatusBadRequest, "Failed to unmarshal TLS config: %s", err) httpError(w, http.StatusBadRequest, "Failed to unmarshal TLS config: %s", err)
@ -1030,6 +1065,7 @@ func handleTLSValidate(w http.ResponseWriter, r *http.Request) {
} }
func handleTLSConfigure(w http.ResponseWriter, r *http.Request) { func handleTLSConfigure(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
data, err := unmarshalTLS(r) data, err := unmarshalTLS(r)
if err != nil { if err != nil {
httpError(w, http.StatusBadRequest, "Failed to unmarshal TLS config: %s", err) httpError(w, http.StatusBadRequest, "Failed to unmarshal TLS config: %s", err)
@ -1287,6 +1323,7 @@ func marshalTLS(w http.ResponseWriter, data tlsConfig) {
// DNS-over-HTTPS // DNS-over-HTTPS
// -------------- // --------------
func handleDOH(w http.ResponseWriter, r *http.Request) { func handleDOH(w http.ResponseWriter, r *http.Request) {
log.Tracef("")
if r.TLS == nil { if r.TLS == nil {
httpError(w, http.StatusNotFound, "Not Found") httpError(w, http.StatusNotFound, "Not Found")
return return

View File

@ -10,7 +10,7 @@ import (
"time" "time"
"github.com/AdguardTeam/AdGuardHome/dhcpd" "github.com/AdguardTeam/AdGuardHome/dhcpd"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/joomcode/errorx" "github.com/joomcode/errorx"
) )
@ -60,7 +60,7 @@ func handleDHCPSetConfig(w http.ResponseWriter, r *http.Request) {
if !newconfig.Enabled { if !newconfig.Enabled {
err := dhcpServer.Stop() err := dhcpServer.Stop()
if err != nil { if err != nil {
log.Printf("failed to stop the DHCP server: %s", err) log.Error("failed to stop the DHCP server: %s", err)
} }
} }
config.DHCP = newconfig config.DHCP = newconfig
@ -131,7 +131,7 @@ func handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := ioutil.ReadAll(r.Body)
if err != nil { if err != nil {
errorText := fmt.Sprintf("failed to read request body: %s", err) errorText := fmt.Sprintf("failed to read request body: %s", err)
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }
@ -139,7 +139,7 @@ func handleDHCPFindActiveServer(w http.ResponseWriter, r *http.Request) {
interfaceName := strings.TrimSpace(string(body)) interfaceName := strings.TrimSpace(string(body))
if interfaceName == "" { if interfaceName == "" {
errorText := fmt.Sprintf("empty interface name specified") errorText := fmt.Sprintf("empty interface name specified")
log.Println(errorText) log.Error(errorText)
http.Error(w, errorText, http.StatusBadRequest) http.Error(w, errorText, http.StatusBadRequest)
return return
} }

View File

@ -9,7 +9,7 @@ import (
"os" "os"
"time" "time"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/krolaw/dhcp4" "github.com/krolaw/dhcp4"
) )

View File

@ -7,7 +7,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/krolaw/dhcp4" "github.com/krolaw/dhcp4"
) )

View File

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"net" "net"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/joomcode/errorx" "github.com/joomcode/errorx"
) )

View File

@ -8,7 +8,7 @@ import (
"time" "time"
"github.com/AdguardTeam/AdGuardHome/dhcpd" "github.com/AdguardTeam/AdGuardHome/dhcpd"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/krolaw/dhcp4" "github.com/krolaw/dhcp4"
) )

2
dns.go
View File

@ -8,7 +8,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/dnsfilter" "github.com/AdguardTeam/AdGuardHome/dnsfilter"
"github.com/AdguardTeam/AdGuardHome/dnsforward" "github.com/AdguardTeam/AdGuardHome/dnsforward"
"github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/joomcode/errorx" "github.com/joomcode/errorx"
) )

View File

@ -17,7 +17,7 @@ import (
"time" "time"
"github.com/bluele/gcache" "github.com/bluele/gcache"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"golang.org/x/net/publicsuffix" "golang.org/x/net/publicsuffix"
) )

View File

@ -18,7 +18,7 @@ import (
"os" "os"
"runtime" "runtime"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/shirou/gopsutil/process" "github.com/shirou/gopsutil/process"
"go.uber.org/goleak" "go.uber.org/goleak"
) )

View File

@ -13,7 +13,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/dnsfilter" "github.com/AdguardTeam/AdGuardHome/dnsfilter"
"github.com/AdguardTeam/dnsproxy/proxy" "github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/dnsproxy/upstream" "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/joomcode/errorx" "github.com/joomcode/errorx"
"github.com/miekg/dns" "github.com/miekg/dns"
) )

View File

@ -10,7 +10,7 @@ import (
"time" "time"
"github.com/AdguardTeam/AdGuardHome/dnsfilter" "github.com/AdguardTeam/AdGuardHome/dnsfilter"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns" "github.com/miekg/dns"
) )

View File

@ -9,8 +9,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/AdguardTeam/golibs/log"
"github.com/go-test/deep" "github.com/go-test/deep"
"github.com/hmage/golibs/log"
) )
var ( var (
@ -28,7 +28,7 @@ func (l *queryLog) flushLogBuffer() error {
l.logBufferLock.Unlock() l.logBufferLock.Unlock()
err := l.flushToFile(flushBuffer) err := l.flushToFile(flushBuffer)
if err != nil { if err != nil {
log.Printf("Saving querylog to file failed: %s", err) log.Error("Saving querylog to file failed: %s", err)
return err return err
} }
return nil return nil
@ -46,17 +46,17 @@ func (l *queryLog) flushToFile(buffer []*logEntry) error {
for _, entry := range buffer { for _, entry := range buffer {
err := e.Encode(entry) err := e.Encode(entry)
if err != nil { if err != nil {
log.Printf("Failed to marshal entry: %s", err) log.Error("Failed to marshal entry: %s", err)
return err return err
} }
} }
elapsed := time.Since(start) elapsed := time.Since(start)
log.Printf("%d elements serialized via json in %v: %d kB, %v/entry, %v/entry", len(buffer), elapsed, b.Len()/1024, float64(b.Len())/float64(len(buffer)), elapsed/time.Duration(len(buffer))) log.Debug("%d elements serialized via json in %v: %d kB, %v/entry, %v/entry", len(buffer), elapsed, b.Len()/1024, float64(b.Len())/float64(len(buffer)), elapsed/time.Duration(len(buffer)))
err := checkBuffer(buffer, b) err := checkBuffer(buffer, b)
if err != nil { if err != nil {
log.Printf("failed to check buffer: %s", err) log.Error("failed to check buffer: %s", err)
return err return err
} }
@ -73,13 +73,13 @@ func (l *queryLog) flushToFile(buffer []*logEntry) error {
_, err = zw.Write(b.Bytes()) _, err = zw.Write(b.Bytes())
if err != nil { if err != nil {
log.Printf("Couldn't compress to gzip: %s", err) log.Error("Couldn't compress to gzip: %s", err)
zw.Close() zw.Close()
return err return err
} }
if err = zw.Close(); err != nil { if err = zw.Close(); err != nil {
log.Printf("Couldn't close gzip writer: %s", err) log.Error("Couldn't close gzip writer: %s", err)
return err return err
} }
} else { } else {
@ -90,18 +90,18 @@ func (l *queryLog) flushToFile(buffer []*logEntry) error {
defer fileWriteLock.Unlock() defer fileWriteLock.Unlock()
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil { if err != nil {
log.Printf("failed to create file \"%s\": %s", filename, err) log.Error("failed to create file \"%s\": %s", filename, err)
return err return err
} }
defer f.Close() defer f.Close()
n, err := f.Write(zb.Bytes()) n, err := f.Write(zb.Bytes())
if err != nil { if err != nil {
log.Printf("Couldn't write to file: %s", err) log.Error("Couldn't write to file: %s", err)
return err return err
} }
log.Printf("ok \"%s\": %v bytes written", filename, n) log.Debug("ok \"%s\": %v bytes written", filename, n)
return nil return nil
} }
@ -115,21 +115,21 @@ func checkBuffer(buffer []*logEntry, b bytes.Buffer) error {
entry := &logEntry{} entry := &logEntry{}
err := d.Decode(entry) err := d.Decode(entry)
if err != nil { if err != nil {
log.Printf("Failed to decode: %s", err) log.Error("Failed to decode: %s", err)
return err return err
} }
if diff := deep.Equal(entry, buffer[i]); diff != nil { if diff := deep.Equal(entry, buffer[i]); diff != nil {
log.Printf("decoded buffer differs: %s", diff) log.Error("decoded buffer differs: %s", diff)
return fmt.Errorf("decoded buffer differs: %s", diff) return fmt.Errorf("decoded buffer differs: %s", diff)
} }
i++ i++
} }
if i != l { if i != l {
err := fmt.Errorf("check fail: %d vs %d entries", l, i) err := fmt.Errorf("check fail: %d vs %d entries", l, i)
log.Print(err) log.Error("%v", err)
return err return err
} }
log.Printf("check ok: %d entries", i) log.Debug("check ok: %d entries", i)
return nil return nil
} }
@ -150,11 +150,11 @@ func (l *queryLog) rotateQueryLog() error {
err := os.Rename(from, to) err := os.Rename(from, to)
if err != nil { if err != nil {
log.Printf("Failed to rename querylog: %s", err) log.Error("Failed to rename querylog: %s", err)
return err return err
} }
log.Printf("Rotated from %s to %s successfully", from, to) log.Debug("Rotated from %s to %s successfully", from, to)
return nil return nil
} }
@ -163,7 +163,7 @@ func (l *queryLog) periodicQueryLogRotate() {
for range time.Tick(queryLogRotationPeriod) { for range time.Tick(queryLogRotationPeriod) {
err := l.rotateQueryLog() err := l.rotateQueryLog()
if err != nil { if err != nil {
log.Printf("Failed to rotate querylog: %s", err) log.Error("Failed to rotate querylog: %s", err)
// do nothing, continue rotating // do nothing, continue rotating
} }
} }
@ -198,7 +198,7 @@ func (l *queryLog) genericLoader(onEntry func(entry *logEntry) error, needMore f
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
log.Printf("Failed to open file \"%s\": %s", file, err) log.Error("Failed to open file \"%s\": %s", file, err)
// try next file // try next file
continue continue
} }
@ -209,7 +209,7 @@ func (l *queryLog) genericLoader(onEntry func(entry *logEntry) error, needMore f
if enableGzip { if enableGzip {
zr, err := gzip.NewReader(f) zr, err := gzip.NewReader(f)
if err != nil { if err != nil {
log.Printf("Failed to create gzip reader: %s", err) log.Error("Failed to create gzip reader: %s", err)
continue continue
} }
defer zr.Close() defer zr.Close()
@ -231,7 +231,7 @@ func (l *queryLog) genericLoader(onEntry func(entry *logEntry) error, needMore f
var entry logEntry var entry logEntry
err := d.Decode(&entry) err := d.Decode(&entry)
if err != nil { if err != nil {
log.Printf("Failed to decode: %s", err) log.Error("Failed to decode: %s", err)
// next entry can be fine, try more // next entry can be fine, try more
continue continue
} }
@ -260,7 +260,7 @@ func (l *queryLog) genericLoader(onEntry func(entry *logEntry) error, needMore f
perunit = elapsed / time.Duration(i) perunit = elapsed / time.Duration(i)
avg = sum / time.Duration(i) avg = sum / time.Duration(i)
} }
log.Printf("file \"%s\": read %d entries in %v, %v/entry, %v over %v, %v avg", file, i, elapsed, perunit, over, max, avg) log.Debug("file \"%s\": read %d entries in %v, %v/entry, %v over %v, %v avg", file, i, elapsed, perunit, over, max, avg)
} }
return nil return nil
} }

View File

@ -10,7 +10,7 @@ import (
"time" "time"
"github.com/bluele/gcache" "github.com/bluele/gcache"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns" "github.com/miekg/dns"
) )

View File

@ -12,7 +12,7 @@ import (
"time" "time"
"github.com/AdguardTeam/AdGuardHome/dnsfilter" "github.com/AdguardTeam/AdGuardHome/dnsfilter"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
) )
var ( var (

2
go.mod
View File

@ -2,12 +2,12 @@ module github.com/AdguardTeam/AdGuardHome
require ( require (
github.com/AdguardTeam/dnsproxy v0.11.1 github.com/AdguardTeam/dnsproxy v0.11.1
github.com/AdguardTeam/golibs v0.1
github.com/StackExchange/wmi v0.0.0-20180725035823-b12b22c5341f // indirect github.com/StackExchange/wmi v0.0.0-20180725035823-b12b22c5341f // indirect
github.com/bluele/gcache v0.0.0-20171010155617-472614239ac7 github.com/bluele/gcache v0.0.0-20171010155617-472614239ac7
github.com/go-ole/go-ole v1.2.1 // indirect github.com/go-ole/go-ole v1.2.1 // indirect
github.com/go-test/deep v1.0.1 github.com/go-test/deep v1.0.1
github.com/gobuffalo/packr v1.19.0 github.com/gobuffalo/packr v1.19.0
github.com/hmage/golibs v0.0.0-20190121112702-20153bd03c24
github.com/joomcode/errorx v0.1.0 github.com/joomcode/errorx v0.1.0
github.com/kardianos/osext v0.0.0-20170510131534-ae77be60afb1 // indirect github.com/kardianos/osext v0.0.0-20170510131534-ae77be60afb1 // indirect
github.com/kardianos/service v0.0.0-20181115005516-4c239ee84e7b github.com/kardianos/service v0.0.0-20181115005516-4c239ee84e7b

View File

@ -3,7 +3,7 @@ package main
import ( import (
"testing" "testing"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
) )
func TestGetValidNetInterfacesForWeb(t *testing.T) { func TestGetValidNetInterfacesForWeb(t *testing.T) {

View File

@ -6,7 +6,7 @@ import (
"net/http" "net/http"
"strings" "strings"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
) )
// -------------------- // --------------------

View File

@ -4,7 +4,7 @@ import (
"os" "os"
"runtime" "runtime"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/kardianos/service" "github.com/kardianos/service"
) )

View File

@ -6,7 +6,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/hmage/golibs/log" "github.com/AdguardTeam/golibs/log"
yaml "gopkg.in/yaml.v2" yaml "gopkg.in/yaml.v2"
) )