Code cleanup, remove unnecessary features.

master
J. David Lee 2019-06-11 06:31:04 +02:00
parent cd332ce483
commit 2c039ffb1c
10 changed files with 30 additions and 67 deletions

View File

@ -5,20 +5,22 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"time"
) )
type Client struct { type Client struct {
addr string reportURL string
apiKey string
} }
// addr is the full address, for example: https://x.io/report. // addr is the full address, for example: https://x.io/report.
func New(addr, apiKey string) Client { func New(reportURL string) Client {
return Client{addr, apiKey} return Client{reportURL}
} }
func (cl Client) post(values url.Values) error { func (client Client) post(values url.Values) error {
resp, err := http.PostForm(cl.addr, values) cl := http.Client{Timeout: 30 * time.Second}
resp, err := cl.PostForm(client.reportURL, values)
if err != nil { if err != nil {
return err return err
} }
@ -35,14 +37,12 @@ func (cl Client) post(values url.Values) error {
func (cl Client) Ping() error { func (cl Client) Ping() error {
return cl.post(url.Values{ return cl.post(url.Values{
"key": []string{cl.apiKey},
"action": []string{"ping"}, "action": []string{"ping"},
}) })
} }
func (cl Client) Log(text string) error { func (cl Client) Log(text string) error {
return cl.post(url.Values{ return cl.post(url.Values{
"key": []string{cl.apiKey},
"action": []string{"log"}, "action": []string{"log"},
"text": []string{text}, "text": []string{text},
}) })
@ -50,7 +50,6 @@ func (cl Client) Log(text string) error {
func (cl Client) Alert(text string) error { func (cl Client) Alert(text string) error {
return cl.post(url.Values{ return cl.post(url.Values{
"key": []string{cl.apiKey},
"action": []string{"alert"}, "action": []string{"alert"},
"text": []string{text}, "text": []string{text},
}) })

View File

@ -13,23 +13,22 @@ func main() {
usage := func() { usage := func() {
fmt.Fprintf( fmt.Fprintf(
os.Stderr, os.Stderr,
"\n\n%s <URL> <api_key> <action> [text]\n\n"+ "\n\n%s <report URL> <action> [text]\n\n"+
"Action is one of `ping`, `log`, or `alert`.\n"+ "Action is one of `ping`, `log`, or `alert`.\n"+
"The `log` and `alert` actions require `text`.\n\n", "The `log` and `alert` actions require `text`.\n\n",
os.Args[0]) os.Args[0])
os.Exit(1) os.Exit(1)
} }
if len(os.Args) < 4 { if len(os.Args) < 3 {
usage() usage()
} }
url := os.Args[1] reportURL := os.Args[1]
apiKey := os.Args[2]
cl := amclient.New(url, apiKey) cl := amclient.New(reportURL)
action := os.Args[3] action := os.Args[2]
var err error var err error
@ -38,13 +37,13 @@ func main() {
err = cl.Ping() err = cl.Ping()
case "log": case "log":
if len(os.Args) < 5 { if len(os.Args) < 4 {
usage() usage()
} }
err = cl.Log(strings.Join(os.Args[4:], " ")) err = cl.Log(strings.Join(os.Args[4:], " "))
case "alert": case "alert":
if len(os.Args) < 5 { if len(os.Args) < 4 {
usage() usage()
} }
err = cl.Alert(strings.Join(os.Args[4:], " ")) err = cl.Alert(strings.Join(os.Args[4:], " "))

24
db.go
View File

@ -178,11 +178,11 @@ func (db *dbal) SourceInsert(s *Source) error {
_, err := db.Exec(`INSERT INTO sources(`+ _, err := db.Exec(`INSERT INTO sources(`+
` SourceID,Name,APIKey,Description,`+ ` SourceID,Name,APIKey,Description,`+
` LastSeenAt,AlertTimeout,AlertedAt,`+ ` LastSeenAt,AlertTimeout,AlertedAt,`+
` Ignore,LogAction,AlertAction`+ ` LogAction,AlertAction`+
`)VALUES(?,?,?,?,?,?,?,?,?,?)`, `)VALUES(?,?,?,?,?,?,?,?,?)`,
s.SourceID, s.Name, s.APIKey, s.Description, s.SourceID, s.Name, s.APIKey, s.Description,
s.LastSeenAt, s.AlertTimeout, s.AlertedAt, s.LastSeenAt, s.AlertTimeout, s.AlertedAt,
s.Ignore, s.LogAction, s.AlertAction) s.LogAction, s.AlertAction)
if err != nil { if err != nil {
db.logf("Failed to insert source: %v", err) db.logf("Failed to insert source: %v", err)
} }
@ -191,7 +191,7 @@ func (db *dbal) SourceInsert(s *Source) error {
const sourceCols = `SourceID,Name,APIKey,Description,` + const sourceCols = `SourceID,Name,APIKey,Description,` +
`LastSeenAt,AlertTimeout,AlertedAt,` + `LastSeenAt,AlertTimeout,AlertedAt,` +
`Ignore,LogAction,AlertAction` `LogAction,AlertAction`
func (db *dbal) scanSource( func (db *dbal) scanSource(
row interface{ Scan(...interface{}) error }, row interface{ Scan(...interface{}) error },
@ -199,7 +199,7 @@ func (db *dbal) scanSource(
err = row.Scan( err = row.Scan(
&s.SourceID, &s.Name, &s.APIKey, &s.Description, &s.SourceID, &s.Name, &s.APIKey, &s.Description,
&s.LastSeenAt, &s.AlertTimeout, &s.AlertedAt, &s.LastSeenAt, &s.AlertTimeout, &s.AlertedAt,
&s.Ignore, &s.LogAction, &s.AlertAction) &s.LogAction, &s.AlertAction)
if err != nil { if err != nil {
db.logf("Failed to scan source: %v", err) db.logf("Failed to scan source: %v", err)
} }
@ -251,16 +251,8 @@ func (db *dbal) SourceUpdate(s Source) error {
return err return err
} }
func (db *dbal) SourceUpdateIgnore(id string, b bool) error {
_, err := db.Exec(`UPDATE sources SET Ignore=? WHERE SourceID=?`, b, id)
if err != nil {
db.logf("Failed to update source ignore %s: %v", id, err)
}
return err
}
func (db *dbal) SourceUpdateLastSeenAt(id string) error { func (db *dbal) SourceUpdateLastSeenAt(id string) error {
t := time.Now() t := time.Now().UTC()
_, err := db.Exec(`UPDATE sources SET LastSeenAt=? WHERE SourceID=?`, t, id) _, err := db.Exec(`UPDATE sources SET LastSeenAt=? WHERE SourceID=?`, t, id)
if err != nil { if err != nil {
db.logf("Failed to update source last seen at %s: %v", id, err) db.logf("Failed to update source last seen at %s: %v", id, err)
@ -269,7 +261,7 @@ func (db *dbal) SourceUpdateLastSeenAt(id string) error {
} }
func (db *dbal) SourceUpdateAlertedAt(id string) error { func (db *dbal) SourceUpdateAlertedAt(id string) error {
t := time.Now() t := time.Now().UTC()
_, err := db.Exec(`UPDATE sources SET AlertedAt=? WHERE SourceID=?`, t, id) _, err := db.Exec(`UPDATE sources SET AlertedAt=? WHERE SourceID=?`, t, id)
if err != nil { if err != nil {
db.logf("Failed to update source alerted at %s: %v", id, err) db.logf("Failed to update source alerted at %s: %v", id, err)
@ -290,7 +282,7 @@ func (db *dbal) SourceDelete(id string) error {
*******/ *******/
func (db *dbal) LogInsert(e Entry) error { func (db *dbal) LogInsert(e Entry) error {
e.TS = time.Now() e.TS = time.Now().UTC()
_, err := db.Exec(`INSERT INTO log`+ _, err := db.Exec(`INSERT INTO log`+
`(SourceID,TS,Alert,Text)VALUES(?,?,?,?)`, `(SourceID,TS,Alert,Text)VALUES(?,?,?,?)`,
e.SourceID, e.TS, e.Alert, e.Text) e.SourceID, e.TS, e.Alert, e.Text)

View File

@ -49,7 +49,7 @@ func Main() {
http.HandleFunc("/", handleRoot) http.HandleFunc("/", handleRoot)
// API requests. // API requests.
http.HandleFunc("/report", handleReport) http.HandleFunc("/report/", handleReport)
// User routes. // User routes.
handle_admin("/user/insert", handleUserInsert) handle_admin("/user/insert", handleUserInsert)

View File

@ -15,7 +15,6 @@ CREATE TABLE IF NOT EXISTS sources(
LastSeenAt TIMESTAMP NOT NULL, LastSeenAt TIMESTAMP NOT NULL,
AlertTimeout BIGINT NOT NULL, AlertTimeout BIGINT NOT NULL,
AlertedAt TIMESTAMP NOT NULL, AlertedAt TIMESTAMP NOT NULL,
Ignore BOOLEAN NOT NULL,
LogAction TEXT NOT NULL, LogAction TEXT NOT NULL,
AlertAction TEXT NOT NULL AlertAction TEXT NOT NULL
); );

View File

@ -2,12 +2,11 @@ package am
import ( import (
"net/http" "net/http"
"path/filepath"
) )
func handleReport(w http.ResponseWriter, r *http.Request) { func handleReport(w http.ResponseWriter, r *http.Request) {
r.ParseForm() apiKey := filepath.Base(r.URL.Path)
apiKey := r.Form.Get("key")
src, err := db.SourceGetByKey(apiKey) src, err := db.SourceGetByKey(apiKey)
if err != nil { if err != nil {
@ -15,6 +14,8 @@ func handleReport(w http.ResponseWriter, r *http.Request) {
return return
} }
r.ParseForm()
action := r.Form.Get("action") action := r.Form.Get("action")
switch action { switch action {

View File

@ -62,9 +62,7 @@
{{range . -}} {{range . -}}
<li> <li>
<a href="/source/view/{{.SourceID}}"> <a href="/source/view/{{.SourceID}}">
{{.Name}} {{.Name}} {{if .TimedOut}}&#x2716;{{end}}
{{if .TimedOut}}&#x2716;{{end}}
{{if .Ignore}}&#x2225;{{end}}
</a> </a>
</li> </li>
{{- end}} {{- end}}
@ -107,9 +105,6 @@
<dt>Alerted At</dt> <dt>Alerted At</dt>
<dd>{{.AlertedAt.Format "2006-01-02 15:04"}}</dd> <dd>{{.AlertedAt.Format "2006-01-02 15:04"}}</dd>
<dt>Ignore</dt>
<dd>{{if .Ignore}}True{{else}}False{{end}}</dd>
<dt>Log Action</dt> <dt>Log Action</dt>
<dd>{{.LogAction}}</dd> <dd>{{.LogAction}}</dd>
@ -140,10 +135,6 @@
<input type="hidden" name="SourceID" value="{{.Source.SourceID}}"> <input type="hidden" name="SourceID" value="{{.Source.SourceID}}">
<ul class="form-list"> <ul class="form-list">
<li>
<input type="checkbox" name="Ignore" id="Ignore" {{if .Source.Ignore}}Checked{{end}}>
<label for="Ignore">Ignore</label>
</li>
<li> <li>
<label for="APIKey">API Key:</label> <label for="APIKey">API Key:</label>
<input type="text" id="APIKey" name="APIKey" value="{{.Source.APIKey}}"> <input type="text" id="APIKey" name="APIKey" value="{{.Source.APIKey}}">

View File

@ -158,9 +158,7 @@ var tmpls = `
{{range . -}} {{range . -}}
<li> <li>
<a href="/source/view/{{.SourceID}}"> <a href="/source/view/{{.SourceID}}">
{{.Name}} {{.Name}} {{if .TimedOut}}&#x2716;{{end}}
{{if .TimedOut}}&#x2716;{{end}}
{{if .Ignore}}&#x2225;{{end}}
</a> </a>
</li> </li>
{{- end}} {{- end}}
@ -203,9 +201,6 @@ var tmpls = `
<dt>Alerted At</dt> <dt>Alerted At</dt>
<dd>{{.AlertedAt.Format "2006-01-02 15:04"}}</dd> <dd>{{.AlertedAt.Format "2006-01-02 15:04"}}</dd>
<dt>Ignore</dt>
<dd>{{if .Ignore}}True{{else}}False{{end}}</dd>
<dt>Log Action</dt> <dt>Log Action</dt>
<dd>{{.LogAction}}</dd> <dd>{{.LogAction}}</dd>
@ -236,10 +231,6 @@ var tmpls = `
<input type="hidden" name="SourceID" value="{{.Source.SourceID}}"> <input type="hidden" name="SourceID" value="{{.Source.SourceID}}">
<ul class="form-list"> <ul class="form-list">
<li>
<input type="checkbox" name="Ignore" id="Ignore" {{if .Source.Ignore}}Checked{{end}}>
<label for="Ignore">Ignore</label>
</li>
<li> <li>
<label for="APIKey">API Key:</label> <label for="APIKey">API Key:</label>
<input type="text" id="APIKey" name="APIKey" value="{{.Source.APIKey}}"> <input type="text" id="APIKey" name="APIKey" value="{{.Source.APIKey}}">

View File

@ -15,7 +15,6 @@ type Source struct {
LastSeenAt time.Time LastSeenAt time.Time
AlertTimeout int64 // In seconds. AlertTimeout int64 // In seconds.
AlertedAt time.Time // Timeout alert time. AlertedAt time.Time // Timeout alert time.
Ignore bool // Don't trigger alerts.
LogAction string // Override log action. LogAction string // Override log action.
AlertAction string // Override alert action. AlertAction string // Override alert action.
} }

View File

@ -280,14 +280,6 @@ func handleSourceUpdate(w http.ResponseWriter, r *http.Request) {
return return
} }
ignore := r.Form.Get("Ignore") != ""
if ignore != s.Ignore {
if err := db.SourceUpdateIgnore(s.SourceID, ignore); err != nil {
execTmpl(w, "Error", err)
return
}
}
respondRedirect(w, r, "/source/view/%s", s.SourceID) respondRedirect(w, r, "/source/view/%s", s.SourceID)
} }