* 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 (
"crypto/tls"
"fmt"
stdlog "log"
"net"
"net/http"
"os"
@ -15,9 +14,8 @@ import (
"syscall"
"time"
"github.com/AdguardTeam/golibs/log"
"github.com/gobuffalo/packr"
"github.com/hmage/golibs/log"
)
// 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
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 {
log.Printf("AdGuard Home is running as a service")
log.Info("AdGuard Home is running as a service")
}
config.firstRun = detectFirstRun()
@ -110,7 +108,7 @@ func run(args options) {
err = filter.load()
if err != nil {
// 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
}
@ -161,7 +159,7 @@ func run(args options) {
// add handlers for /install paths, we only need them when we're not configured yet
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)))
registerInstallHandlers()
}
@ -263,7 +261,11 @@ func configureLogger(args options) {
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" {
// 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 {
log.Fatalf("cannot create a log file: %s", err)
}
stdlog.SetOutput(file)
log.SetOutput(file)
}
}
func cleanup() {
log.Printf("Stopping AdGuard Home")
log.Info("Stopping AdGuard Home")
err := stopDNSServer()
if err != nil {
log.Printf("Couldn't stop DNS server: %s", err)
log.Error("Couldn't stop DNS server: %s", err)
}
err = stopDHCPServer()
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 opt.callbackWithValue != nil {
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)
}
i++
@ -386,7 +388,7 @@ func loadOptions() options {
}
}
if !knownParam {
log.Printf("ERROR: unknown option %v\n", v)
log.Error("unknown option %v\n", v)
printHelp()
os.Exit(64)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

2
dns.go
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

2
go.mod
View File

@ -2,12 +2,12 @@ module github.com/AdguardTeam/AdGuardHome
require (
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/bluele/gcache v0.0.0-20171010155617-472614239ac7
github.com/go-ole/go-ole v1.2.1 // indirect
github.com/go-test/deep v1.0.1
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/kardianos/osext v0.0.0-20170510131534-ae77be60afb1 // indirect
github.com/kardianos/service v0.0.0-20181115005516-4c239ee84e7b

View File

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

View File

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

View File

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

View File

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