1
0
mirror of https://github.com/jhillyerd/inbucket.git synced 2025-12-23 12:37:07 +00:00

Logging and unit test changes

Logging methods were renamed so they don't trigger go-vet warnings for
error() and Error() formatting.

Unit tests were updated to use new github.com/stretchr repo (was renamed
from stretchrcom)

Missing methods were added to Message mock object.
This commit is contained in:
James Hillyerd
2013-09-13 14:06:57 -07:00
parent f50061ac82
commit 2e78e4e6f7
16 changed files with 180 additions and 171 deletions

View File

@@ -46,11 +46,11 @@ type FileDataStore struct {
func NewFileDataStore() DataStore {
path, err := config.Config.String("datastore", "path")
if err != nil {
log.Error("Error getting datastore path: %v", err)
log.LogError("Error getting datastore path: %v", err)
return nil
}
if path == "" {
log.Error("No value configured for datastore path")
log.LogError("No value configured for datastore path")
return nil
}
mailPath := filepath.Join(path, "mail")
@@ -66,7 +66,7 @@ func (ds *FileDataStore) MailboxFor(emailAddress string) (Mailbox, error) {
s2 := dir[0:6]
path := filepath.Join(ds.mailPath, s1, s2, dir)
if err := os.MkdirAll(path, 0770); err != nil {
log.Error("Failed to create directory %v, %v", path, err)
log.LogError("Failed to create directory %v, %v", path, err)
return nil, err
}
return &FileMailbox{store: ds, name: name, dirName: dir, path: path}, nil
@@ -132,7 +132,7 @@ func (mb *FileMailbox) GetMessages() ([]Message, error) {
if err != nil {
return nil, err
}
log.Trace("Scanning %v files for %v", len(files), mb)
log.LogTrace("Scanning %v files for %v", len(files), mb)
messages := make([]Message, 0, len(files))
for _, f := range files {
@@ -149,7 +149,7 @@ func (mb *FileMailbox) GetMessages() ([]Message, error) {
}
file.Close()
msg.mailbox = mb
log.Trace("Found: %v", msg)
log.LogTrace("Found: %v", msg)
messages = append(messages, msg)
}
}
@@ -170,7 +170,7 @@ func (mb *FileMailbox) GetMessage(id string) (Message, error) {
}
file.Close()
msg.mailbox = mb
log.Trace("Found: %v", msg)
log.LogTrace("Found: %v", msg)
return msg, nil
}
@@ -335,7 +335,7 @@ func (m *FileMessage) Close() error {
err := m.createGob()
if err != nil {
log.Error("Failed to create gob: %v", err)
log.LogError("Failed to create gob: %v", err)
return err
}
@@ -344,12 +344,12 @@ func (m *FileMessage) Close() error {
// Delete this Message from disk by removing both the gob and raw files
func (m *FileMessage) Delete() error {
log.Trace("Deleting %v", m.gobPath())
log.LogTrace("Deleting %v", m.gobPath())
err := os.Remove(m.gobPath())
if err != nil {
return err
}
log.Trace("Deleting %v", m.rawPath())
log.LogTrace("Deleting %v", m.rawPath())
return os.Remove(m.rawPath())
}

View File

@@ -1,7 +1,7 @@
package smtpd
import (
"github.com/stretchrcom/testify/assert"
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path/filepath"

View File

@@ -88,7 +88,7 @@ func (ss *Session) String() string {
* 5. Goto 2
*/
func (s *Server) startSession(id int, conn net.Conn) {
log.Info("SMTP Connection from %v, starting session <%v>", conn.RemoteAddr(), id)
log.LogInfo("SMTP Connection from %v, starting session <%v>", conn.RemoteAddr(), id)
expConnectsCurrent.Add(1)
defer func() {
conn.Close()
@@ -116,7 +116,7 @@ func (s *Server) startSession(id int, conn net.Conn) {
}
if !commands[cmd] {
ss.send(fmt.Sprintf("500 Syntax error, %v command unrecognized", cmd))
ss.warn("Unrecognized command: %v", cmd)
ss.logWarn("Unrecognized command: %v", cmd)
continue
}
@@ -125,7 +125,7 @@ func (s *Server) startSession(id int, conn net.Conn) {
case "SEND", "SOML", "SAML", "EXPN", "HELP", "TURN":
// These commands are not implemented in any state
ss.send(fmt.Sprintf("502 %v command not implemented", cmd))
ss.warn("Command %v not implemented by Inbucket", cmd)
ss.logWarn("Command %v not implemented by Inbucket", cmd)
continue
case "VRFY":
ss.send("252 Cannot VRFY user, but will accept message")
@@ -135,7 +135,7 @@ func (s *Server) startSession(id int, conn net.Conn) {
continue
case "RSET":
// Reset session
ss.trace("Resetting session state on RSET request")
ss.logTrace("Resetting session state on RSET request")
ss.reset()
ss.send("250 Session reset")
continue
@@ -157,7 +157,7 @@ func (s *Server) startSession(id int, conn net.Conn) {
ss.mailHandler(cmd, arg)
continue
}
ss.error("Session entered unexpected state %v", ss.state)
ss.logError("Session entered unexpected state %v", ss.state)
break
} else {
ss.send("500 Syntax error, command garbled")
@@ -168,14 +168,14 @@ func (s *Server) startSession(id int, conn net.Conn) {
switch ss.state {
case GREET, READY:
// EOF is common here
ss.info("Client closed connection (state %v)", ss.state)
ss.logInfo("Client closed connection (state %v)", ss.state)
default:
ss.warn("Got EOF while in state %v", ss.state)
ss.logWarn("Got EOF while in state %v", ss.state)
}
break
}
// not an EOF
ss.warn("Connection error: %v", err)
ss.logWarn("Connection error: %v", err)
if netErr, ok := err.(net.Error); ok {
if netErr.Timeout() {
ss.send("221 Idle timeout, bye bye")
@@ -187,9 +187,9 @@ func (s *Server) startSession(id int, conn net.Conn) {
}
}
if ss.sendError != nil {
ss.warn("Network send error: %v", ss.sendError)
ss.logWarn("Network send error: %v", ss.sendError)
}
ss.info("Closing connection")
ss.logInfo("Closing connection")
}
// GREET state -> waiting for HELO
@@ -216,7 +216,7 @@ func (ss *Session) readyHandler(cmd string, arg string) {
m := re.FindStringSubmatch(arg)
if m == nil {
ss.send("501 Was expecting MAIL arg syntax of FROM:<address>")
ss.warn("Bad MAIL argument: '%v'", arg)
ss.logWarn("Bad MAIL argument: '%v'", arg)
return
}
from := m[1]
@@ -226,26 +226,26 @@ func (ss *Session) readyHandler(cmd string, arg string) {
args, ok := ss.parseArgs(m[2])
if !ok {
ss.send("501 Unable to parse MAIL ESMTP parameters")
ss.warn("Bad MAIL argument: '%v'", arg)
ss.logWarn("Bad MAIL argument: '%v'", arg)
return
}
if args["SIZE"] != "" {
size, err := strconv.ParseInt(args["SIZE"], 10, 32)
if err != nil {
ss.send("501 Unable to parse SIZE as an integer")
ss.warn("Unable to parse SIZE '%v' as an integer", args["SIZE"])
ss.logWarn("Unable to parse SIZE '%v' as an integer", args["SIZE"])
return
}
if int(size) > ss.server.maxMessageBytes {
ss.send("552 Max message size exceeded")
ss.warn("Client wanted to send oversized message: %v", args["SIZE"])
ss.logWarn("Client wanted to send oversized message: %v", args["SIZE"])
return
}
}
}
ss.from = from
ss.recipients = list.New()
ss.info("Mail from: %v", from)
ss.logInfo("Mail from: %v", from)
ss.send(fmt.Sprintf("250 Roger, accepting mail from <%v>", from))
ss.enterState(MAIL)
} else {
@@ -259,24 +259,24 @@ func (ss *Session) mailHandler(cmd string, arg string) {
case "RCPT":
if (len(arg) < 4) || (strings.ToUpper(arg[0:3]) != "TO:") {
ss.send("501 Was expecting RCPT arg syntax of TO:<address>")
ss.warn("Bad RCPT argument: '%v'", arg)
ss.logWarn("Bad RCPT argument: '%v'", arg)
return
}
// This trim is probably too forgiving
recip := strings.Trim(arg[3:], "<> ")
if ss.recipients.Len() >= ss.server.maxRecips {
ss.warn("Maximum limit of %v recipients reached", ss.server.maxRecips)
ss.logWarn("Maximum limit of %v recipients reached", ss.server.maxRecips)
ss.send(fmt.Sprintf("552 Maximum limit of %v recipients reached", ss.server.maxRecips))
return
}
ss.recipients.PushBack(recip)
ss.info("Recipient: %v", recip)
ss.logInfo("Recipient: %v", recip)
ss.send(fmt.Sprintf("250 I'll make sure <%v> gets this", recip))
return
case "DATA":
if arg != "" {
ss.send("501 DATA command should not have any arguments")
ss.warn("Got unexpected args on DATA: '%v'", arg)
ss.logWarn("Got unexpected args on DATA: '%v'", arg)
return
}
if ss.recipients.Len() > 0 {
@@ -307,7 +307,7 @@ func (ss *Session) dataHandler() {
// Not our "no store" domain, so store the message
mb, err := ss.server.dataStore.MailboxFor(recip)
if err != nil {
ss.error("Failed to open mailbox for %v", recip)
ss.logError("Failed to open mailbox for %v", recip)
ss.send(fmt.Sprintf("451 Failed to open mailbox for %v", recip))
ss.reset()
return
@@ -315,7 +315,7 @@ func (ss *Session) dataHandler() {
mailboxes[i] = mb
messages[i] = mb.NewMessage()
} else {
log.Trace("Not storing message for '%v'", recip)
log.LogTrace("Not storing message for '%v'", recip)
}
i++
}
@@ -332,7 +332,7 @@ func (ss *Session) dataHandler() {
ss.send("221 Idle timeout, bye bye")
}
}
ss.warn("Error: %v while reading", err)
ss.logWarn("Error: %v while reading", err)
ss.enterState(QUIT)
return
}
@@ -350,7 +350,7 @@ func (ss *Session) dataHandler() {
expReceivedTotal.Add(1)
}
ss.send("250 Mail accepted for delivery")
ss.info("Message size %v bytes", msgSize)
ss.logInfo("Message size %v bytes", msgSize)
ss.reset()
return
}
@@ -362,7 +362,7 @@ func (ss *Session) dataHandler() {
if msgSize > ss.server.maxMessageBytes {
// Max message size exceeded
ss.send("552 Maximum message size exceeded")
ss.warn("Max message size exceeded while in DATA")
ss.logWarn("Max message size exceeded while in DATA")
ss.reset()
// TODO: Should really cleanup the crap on filesystem...
return
@@ -372,7 +372,7 @@ func (ss *Session) dataHandler() {
for i, m := range messages {
if m != nil {
if err := m.Append(line); err != nil {
ss.error("Failed to append to mailbox %v: %v", mailboxes[i], err)
ss.logError("Failed to append to mailbox %v: %v", mailboxes[i], err)
ss.send("554 Something went wrong")
ss.reset()
// TODO: Should really cleanup the crap on filesystem...
@@ -386,7 +386,7 @@ func (ss *Session) dataHandler() {
func (ss *Session) enterState(state State) {
ss.state = state
ss.trace("Entering state %v", state)
ss.logTrace("Entering state %v", state)
}
func (ss *Session) greet() {
@@ -406,10 +406,10 @@ func (ss *Session) send(msg string) {
}
if _, err := fmt.Fprint(ss.conn, msg+"\r\n"); err != nil {
ss.sendError = err
ss.warn("Failed to send: '%v'", msg)
ss.logWarn("Failed to send: '%v'", msg)
return
}
ss.trace(">> %v >>", msg)
ss.logTrace(">> %v >>", msg)
}
// readByteLine reads a line of input into the provided buffer. Does
@@ -437,7 +437,6 @@ func (ss *Session) readByteLine(buf *bytes.Buffer) error {
// Else, keep looking
}
// Should be unreachable
return nil
}
// Reads a line of input
@@ -449,7 +448,7 @@ func (ss *Session) readLine() (line string, err error) {
if err != nil {
return "", err
}
ss.trace("<< %v <<", strings.TrimRight(line, "\r\n"))
ss.logTrace("<< %v <<", strings.TrimRight(line, "\r\n"))
return line, nil
}
@@ -460,19 +459,19 @@ func (ss *Session) parseCmd(line string) (cmd string, arg string, ok bool) {
case l == 0:
return "", "", true
case l < 4:
ss.warn("Command too short: '%v'", line)
ss.logWarn("Command too short: '%v'", line)
return "", "", false
case l == 4:
return strings.ToUpper(line), "", true
case l == 5:
// Too long to be only command, too short to have args
ss.warn("Mangled command: '%v'", line)
ss.logWarn("Mangled command: '%v'", line)
return "", "", false
}
// If we made it here, command is long enough to have args
if line[4] != ' ' {
// There wasn't a space after the command?
ss.warn("Mangled command: '%v'", line)
ss.logWarn("Mangled command: '%v'", line)
return "", "", false
}
// I'm not sure if we should trim the args or not, but we will for now
@@ -489,13 +488,13 @@ func (ss *Session) parseArgs(arg string) (args map[string]string, ok bool) {
re := regexp.MustCompile(" (\\w+)=(\\w+)")
pm := re.FindAllStringSubmatch(arg, -1)
if pm == nil {
ss.warn("Failed to parse arg string: '%v'")
ss.logWarn("Failed to parse arg string: '%v'")
return nil, false
}
for _, m := range pm {
args[strings.ToUpper(m[1])] = m[2]
}
ss.trace("ESMTP params: %v", args)
ss.logTrace("ESMTP params: %v", args)
return args, true
}
@@ -507,26 +506,26 @@ func (ss *Session) reset() {
func (ss *Session) ooSeq(cmd string) {
ss.send(fmt.Sprintf("503 Command %v is out of sequence", cmd))
ss.warn("Wasn't expecting %v here", cmd)
ss.logWarn("Wasn't expecting %v here", cmd)
}
// Session specific logging methods
func (ss *Session) trace(msg string, args ...interface{}) {
log.Trace("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
func (ss *Session) logTrace(msg string, args ...interface{}) {
log.LogTrace("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
}
func (ss *Session) info(msg string, args ...interface{}) {
log.Info("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
func (ss *Session) logInfo(msg string, args ...interface{}) {
log.LogInfo("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
}
func (ss *Session) warn(msg string, args ...interface{}) {
func (ss *Session) logWarn(msg string, args ...interface{}) {
// Update metrics
expWarnsTotal.Add(1)
log.Warn("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
log.LogWarn("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
}
func (ss *Session) error(msg string, args ...interface{}) {
func (ss *Session) logError(msg string, args ...interface{}) {
// Update metrics
expErrorsTotal.Add(1)
log.Error("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
log.LogError("SMTP<%v> %v", ss.id, fmt.Sprintf(msg, args...))
}

View File

@@ -61,23 +61,23 @@ func (s *Server) Start() {
addr, err := net.ResolveTCPAddr("tcp4", fmt.Sprintf("%v:%v",
cfg.Ip4address, cfg.Ip4port))
if err != nil {
log.Error("Failed to build tcp4 address: %v", err)
log.LogError("Failed to build tcp4 address: %v", err)
// TODO More graceful early-shutdown procedure
panic(err)
}
log.Info("SMTP listening on TCP4 %v", addr)
log.LogInfo("SMTP listening on TCP4 %v", addr)
s.listener, err = net.ListenTCP("tcp4", addr)
if err != nil {
log.Error("SMTP failed to start tcp4 listener: %v", err)
log.LogError("SMTP failed to start tcp4 listener: %v", err)
// TODO More graceful early-shutdown procedure
panic(err)
}
if !s.storeMessages {
log.Info("Load test mode active, messages will not be stored")
log.LogInfo("Load test mode active, messages will not be stored")
} else if s.domainNoStore != "" {
log.Info("Messages sent to domain '%v' will be discarded", s.domainNoStore)
log.LogInfo("Messages sent to domain '%v' will be discarded", s.domainNoStore)
}
// Start retention scanner
@@ -97,12 +97,12 @@ func (s *Server) Start() {
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
log.Error("SMTP accept error: %v; retrying in %v", err, tempDelay)
log.LogError("SMTP accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay)
continue
} else {
if s.shutdown {
log.Trace("SMTP listener shutting down on request")
log.LogTrace("SMTP listener shutting down on request")
return
}
// TODO Implement a max error counter before shutdown?
@@ -120,7 +120,7 @@ func (s *Server) Start() {
// Stop requests the SMTP server closes it's listener
func (s *Server) Stop() {
log.Trace("SMTP shutdown requested, connections will be drained")
log.LogTrace("SMTP shutdown requested, connections will be drained")
s.shutdown = true
s.listener.Close()
}
@@ -128,7 +128,7 @@ func (s *Server) Stop() {
// Drain causes the caller to block until all active SMTP sessions have finished
func (s *Server) Drain() {
s.waitgroup.Wait()
log.Trace("SMTP connections drained")
log.LogTrace("SMTP connections drained")
}
// When the provided Ticker ticks, we update our metrics history

View File

@@ -26,11 +26,11 @@ func StartRetentionScanner(ds DataStore) {
expRetentionPeriod.Set(int64(cfg.RetentionMinutes * 60))
if cfg.RetentionMinutes > 0 {
// Retention scanning enabled
log.Info("Retention configured for %v minutes", cfg.RetentionMinutes)
log.LogInfo("Retention configured for %v minutes", cfg.RetentionMinutes)
go retentionScanner(ds, time.Duration(cfg.RetentionMinutes) * time.Minute,
time.Duration(cfg.RetentionSleep) * time.Millisecond)
} else {
log.Info("Retention scanner disabled")
log.LogInfo("Retention scanner disabled")
}
}
@@ -41,21 +41,21 @@ func retentionScanner(ds DataStore, maxAge time.Duration, sleep time.Duration) {
since := time.Since(start)
if since < time.Minute {
dur := time.Minute - since
log.Trace("Retention scanner sleeping for %v", dur)
log.LogTrace("Retention scanner sleeping for %v", dur)
time.Sleep(dur)
}
start = time.Now()
// Kickoff scan
if err := doRetentionScan(ds, maxAge, sleep); err != nil {
log.Error("Error during retention scan: %v", err)
log.LogError("Error during retention scan: %v", err)
}
}
}
// doRetentionScan does a single pass of all mailboxes looking for messages that can be purged
func doRetentionScan(ds DataStore, maxAge time.Duration, sleep time.Duration) error {
log.Trace("Starting retention scan")
log.LogTrace("Starting retention scan")
cutoff := time.Now().Add(-1 * maxAge)
mboxes, err := ds.AllMailboxes()
if err != nil {
@@ -69,11 +69,11 @@ func doRetentionScan(ds DataStore, maxAge time.Duration, sleep time.Duration) er
}
for _, msg := range messages {
if msg.Date().Before(cutoff) {
log.Trace("Purging expired message %v", msg.Id())
log.LogTrace("Purging expired message %v", msg.Id())
err = msg.Delete()
if err != nil {
// Log but don't abort
log.Error("Failed to purge message %v: %v", msg.Id(), err)
log.LogError("Failed to purge message %v: %v", msg.Id(), err)
} else {
expRetentionDeletesTotal.Add(1)
}

View File

@@ -3,7 +3,8 @@ package smtpd
import (
"fmt"
"github.com/jhillyerd/go.enmime"
"github.com/stretchrcom/testify/mock"
"github.com/stretchr/testify/mock"
"io"
"net/mail"
"testing"
"time"
@@ -141,6 +142,16 @@ func (m *MockMessage) ReadRaw() (raw *string, err error) {
return args.Get(0).(*string), args.Error(1)
}
func (m *MockMessage) RawReader() (reader io.ReadCloser, err error) {
args := m.Called()
return args.Get(0).(io.ReadCloser), args.Error(1)
}
func (m *MockMessage) Size() (int64) {
args := m.Called()
return int64(args.Int(0))
}
func (m *MockMessage) Append(data []byte) error {
args := m.Called(data)
return args.Error(0)

View File

@@ -1,7 +1,7 @@
package smtpd
import (
"github.com/stretchrcom/testify/assert"
"github.com/stretchr/testify/assert"
"testing"
)