Skip to content

Commit

Permalink
all: Minor code cleanups
Browse files Browse the repository at this point in the history
Mostly getting rid of the \n in log.Print*() format strings, which
don't need it.
  • Loading branch information
justinclift committed Apr 22, 2023
1 parent ae5a000 commit f6f8382
Show file tree
Hide file tree
Showing 16 changed files with 461 additions and 470 deletions.
41 changes: 20 additions & 21 deletions api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func branchesHandler(w http.ResponseWriter, r *http.Request) {
// Return the list as JSON
jsonList, err := json.MarshalIndent(brList, "", " ")
if err != nil {
errMsg := fmt.Sprintf("Error when JSON marshalling the branch list: %v\n", err)
errMsg := fmt.Sprintf("Error when JSON marshalling the branch list: %v", err)
log.Print(errMsg)
jsonErr(w, errMsg, http.StatusBadRequest)
return
Expand Down Expand Up @@ -205,7 +205,7 @@ func columnsHandler(w http.ResponseWriter, r *http.Request) {
// Return the results
jsonData, err := json.MarshalIndent(jsonCols, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in columnsHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in columnsHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -248,7 +248,7 @@ func commitsHandler(w http.ResponseWriter, r *http.Request) {
// Return the tags as JSON
jsonData, err := json.MarshalIndent(commits, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in commitsHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in commitsHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -306,7 +306,7 @@ func databasesHandler(w http.ResponseWriter, r *http.Request) {
// Return the results
jsonData, err := json.MarshalIndent(list, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in databasesHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in databasesHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -571,7 +571,7 @@ func diffHandler(w http.ResponseWriter, r *http.Request) {
// Return the results
jsonData, err := json.MarshalIndent(diffs, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in diffHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in diffHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -687,7 +687,7 @@ func executeHandler(w http.ResponseWriter, r *http.Request) {
z := com.ExecuteResponseContainer{RowsChanged: rowsChanged, Status: "OK"}
jsonData, err := json.MarshalIndent(z, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in executeHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in executeHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -810,7 +810,7 @@ func indexesHandler(w http.ResponseWriter, r *http.Request) {
// Return the results
jsonData, err := json.MarshalIndent(indexes, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in indexesHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in indexesHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -853,7 +853,7 @@ func metadataHandler(w http.ResponseWriter, r *http.Request) {
// Return the list as JSON
jsonList, err := json.MarshalIndent(meta, "", " ")
if err != nil {
errMsg := fmt.Sprintf("Error when JSON marshalling the metadata: %v\n", err)
errMsg := fmt.Sprintf("Error when JSON marshalling the metadata: %v", err)
log.Print(errMsg)
jsonErr(w, errMsg, http.StatusBadRequest)
return
Expand Down Expand Up @@ -933,7 +933,7 @@ func queryHandler(w http.ResponseWriter, r *http.Request) {
// Send the query to the appropriate backend live node
data, err = com.LiveQueryDB(com.AmqpChan, liveNode, loggedInUser, dbOwner, dbName, query)
if err != nil {
log.Println(err) // FIXME: Debug output while developing
log.Println(err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand All @@ -942,7 +942,7 @@ func queryHandler(w http.ResponseWriter, r *http.Request) {
// Return the results
jsonData, err := json.MarshalIndent(data.Records, "", " ")
if err != nil {
jsonErr(w, fmt.Sprintf("Error when JSON marshalling the returned data: %v\n", err),
jsonErr(w, fmt.Sprintf("Error when JSON marshalling the returned data: %v", err),
http.StatusBadRequest)
return
}
Expand Down Expand Up @@ -985,7 +985,7 @@ func releasesHandler(w http.ResponseWriter, r *http.Request) {
// Return the list as JSON
jsonData, err := json.MarshalIndent(rels, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in releasesHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in releasesHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -1092,7 +1092,7 @@ func tablesHandler(w http.ResponseWriter, r *http.Request) {
sort.Strings(tables)
jsonData, err := json.MarshalIndent(tables, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in tablesHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in tablesHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -1135,7 +1135,7 @@ func tagsHandler(w http.ResponseWriter, r *http.Request) {
// Return the tags as JSON
jsonData, err := json.MarshalIndent(tags, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in tagsHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in tagsHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -1199,11 +1199,10 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
// Check whether the uploaded database is too large
if !oversizeAllowed {
if r.ContentLength > (com.MaxDatabaseSize * 1024 * 1024) {
jsonErr(w,
fmt.Sprintf("Database is too large. Maximum database upload size is %d MB, yours is %d MB",
com.MaxDatabaseSize, r.ContentLength/1024/1024), http.StatusBadRequest)
log.Println(fmt.Sprintf("'%s' attempted to upload an oversized database %d MB in size. Limit is %d MB\n",
loggedInUser, r.ContentLength/1024/1024, com.MaxDatabaseSize))
jsonErr(w, fmt.Sprintf("Database is too large. Maximum database upload size is %d MB, yours is %d MB",
com.MaxDatabaseSize, r.ContentLength/1024/1024), http.StatusBadRequest)
log.Printf("'%s' attempted to upload an oversized database %d MB in size. Limit is %d MB",
loggedInUser, r.ContentLength/1024/1024, com.MaxDatabaseSize)
return
}
}
Expand Down Expand Up @@ -1344,7 +1343,7 @@ func uploadHandler(w http.ResponseWriter, r *http.Request) {
z := com.UploadResponseContainer{CommitID: newCommit, URL: newURL}
jsonData, err := json.MarshalIndent(z, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in uploadHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in uploadHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -1426,7 +1425,7 @@ func viewsHandler(w http.ResponseWriter, r *http.Request) {
sort.Strings(views)
jsonData, err := json.MarshalIndent(views, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in viewsHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in viewsHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand All @@ -1453,7 +1452,7 @@ func webpageHandler(w http.ResponseWriter, r *http.Request) {
z.WebPage = "https://" + com.Conf.Web.ServerName + "/" + dbOwner + "/" + dbName
jsonData, err := json.MarshalIndent(z, "", " ")
if err != nil {
log.Printf("Error when JSON marshalling returned data in webpageHandler(): %v\n", err)
log.Printf("Error when JSON marshalling returned data in webpageHandler(): %v", err)
jsonErr(w, err.Error(), http.StatusInternalServerError)
return
}
Expand Down
16 changes: 8 additions & 8 deletions api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ func main() {
// Open the request log for writing
reqLog, err = os.OpenFile(com.Conf.Api.RequestLog, os.O_CREATE|os.O_APPEND|os.O_WRONLY|os.O_SYNC, 0750)
if err != nil {
log.Fatalf("Error when opening request log: %s\n", err)
log.Fatalf("Error when opening request log: %s", err)
}
defer reqLog.Close()
log.Printf("Request log opened: %s\n", com.Conf.Api.RequestLog)
log.Printf("Request log opened: %s", com.Conf.Api.RequestLog)

// Parse our template files
tmpl = template.Must(template.New("templates").Delims("[[", "]]").ParseGlob(
Expand Down Expand Up @@ -103,12 +103,12 @@ func main() {
ourCAPool = x509.NewCertPool()
certFile, err := os.ReadFile(com.Conf.DB4S.CAChain)
if err != nil {
fmt.Printf("Error opening Certificate Authority chain file: %v\n", err)
log.Printf("Error opening Certificate Authority chain file: %v", err)
return
}
ok := ourCAPool.AppendCertsFromPEM(certFile)
if !ok {
fmt.Println("Error appending certificate file")
log.Println("Error appending certificate file")
return
}

Expand Down Expand Up @@ -159,7 +159,7 @@ func main() {
server = fmt.Sprintf("https://%s", com.Conf.Api.ServerName)

// Start API server
log.Printf("API server starting on %s\n", server)
log.Printf("API server starting on %s", server)
err = srv.ListenAndServeTLS(com.Conf.Api.Certificate, com.Conf.Api.CertificateKey)

// Shut down nicely
Expand Down Expand Up @@ -283,7 +283,7 @@ func collectInfoAndOpen(w http.ResponseWriter, r *http.Request) (sdb *sqlite.Con
return
}
if err = sdb.EnableExtendedResultCodes(true); err != nil {
log.Printf("Couldn't enable extended result codes in collectInfoAndOpen(): %v\n", err.Error())
log.Printf("Couldn't enable extended result codes in collectInfoAndOpen(): %v", err.Error())
httpStatus = http.StatusInternalServerError
return
}
Expand Down Expand Up @@ -320,7 +320,7 @@ func extractUserFromClientCert(w http.ResponseWriter, r *http.Request) (userAcc
// Verify the running server matches the one in the certificate
db4sServer := com.Conf.DB4S.Server
if certServer != db4sServer {
err = fmt.Errorf("Server name in certificate '%s' doesn't match DB4S server '%s'\n", certServer,
err = fmt.Errorf("Server name in certificate '%s' doesn't match DB4S server '%s'", certServer,
db4sServer)
return
}
Expand Down Expand Up @@ -348,7 +348,7 @@ func jsonErr(w http.ResponseWriter, msg string, statusCode int) {
}
jsonData, err := json.MarshalIndent(je, "", " ")
if err != nil {
errMsg := fmt.Sprintf("A 2nd error occurred when JSON marshalling an error structure: %v\n", err)
errMsg := fmt.Sprintf("A 2nd error occurred when JSON marshalling an error structure: %v", err)
log.Print(errMsg)
http.Error(w, errMsg, http.StatusInternalServerError)
fmt.Fprintf(w, `{"error":"An error occurred when marshalling JSON inside jsonErr()"}`)
Expand Down
24 changes: 12 additions & 12 deletions common/cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,78 +38,78 @@ func GenerateClientCert(userName string) (_ []byte, err error) {
serialNumLimit := new(big.Int).Lsh(big.NewInt(1), 128)
newCert.SerialNumber, err = rand.Int(rand.Reader, serialNumLimit)
if err != nil {
log.Printf("%s: Error when generating serial number: %v\n", pageName, err)
log.Printf("%s: Error when generating serial number: %v", pageName, err)
return nil, err
}

// Load the certificate used for signing (the intermediate certificate)
certFile, err := os.ReadFile(Conf.Sign.IntermediateCert)
if err != nil {
log.Printf("%s: Error opening intermediate certificate file: %v\n", pageName, err)
log.Printf("%s: Error opening intermediate certificate file: %v", pageName, err)
return
}
certPEM, _ := pem.Decode(certFile)
if certPEM == nil {
log.Printf("%s: Error when PEM decoding the intermediate certificate file\n", pageName)
log.Printf("%s: Error when PEM decoding the intermediate certificate file", pageName)
return
}
intCert, err := x509.ParseCertificate(certPEM.Bytes)
if err != nil {
log.Printf("%s: Error when parsing decoded intermediate certificate data: %v\n", pageName, err)
log.Printf("%s: Error when parsing decoded intermediate certificate data: %v", pageName, err)
return
}

// Load the private key for the intermediate certificate
intKeyFile, err := os.ReadFile(Conf.Sign.IntermediateKey)
if err != nil {
log.Printf("%s: Error opening intermediate certificate key: %v\n", pageName, err)
log.Printf("%s: Error opening intermediate certificate key: %v", pageName, err)
return
}
intKeyPEM, _ := pem.Decode(intKeyFile)
if certPEM == nil {
log.Printf("%s: Error when PEM decoding the intermediate key file\n", pageName)
log.Printf("%s: Error when PEM decoding the intermediate key file", pageName)
return
}
intKey, err := x509.ParsePKCS1PrivateKey(intKeyPEM.Bytes)
if err != nil {
log.Printf("%s: Error when parsing intermediate certificate key: %v\n", pageName, err)
log.Printf("%s: Error when parsing intermediate certificate key: %v", pageName, err)
return
}

// Generate a public key to sign the new certificate with
clientKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Printf("%s: Failed to public key for signing: %v\n", pageName, err)
log.Printf("%s: Failed to public key for signing: %v", pageName, err)
return
}

// Generate the new certificate
clientCert, err := x509.CreateCertificate(rand.Reader, &newCert, intCert, &clientKey.PublicKey, intKey)
if err != nil {
log.Printf("%s: Failed to create certificate: %v\n", pageName, err)
log.Printf("%s: Failed to create certificate: %v", pageName, err)
return
}

// Convert the new certificate into PEM format
buf := &bytes.Buffer{}
err = pem.Encode(buf, &pem.Block{Type: "CERTIFICATE", Bytes: clientCert})
if err != nil {
log.Printf("%s: Failed to PEM encode certificate: %v\n", pageName, err)
log.Printf("%s: Failed to PEM encode certificate: %v", pageName, err)
return
}

// Convert the private key for the certificate into PEM format
buf2 := &bytes.Buffer{}
err = pem.Encode(buf2, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(clientKey)})
if err != nil {
log.Printf("%s: Failed to PEM encode private key: %v\n", pageName, err)
log.Printf("%s: Failed to PEM encode private key: %v", pageName, err)
return
}

// Concatenate the newly generated certificate and its key
_, err = buf.ReadFrom(buf2)
if err != nil {
log.Printf("%s: Failed to concatenate the PEM blocks: %v\n", pageName, err)
log.Printf("%s: Failed to concatenate the PEM blocks: %v", pageName, err)
return
}

Expand Down
10 changes: 5 additions & 5 deletions common/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func dbDiff(dbA string, dbB string, merge MergeStrategy, includeData bool) (Diff
}
defer sdb.Close()
if err = sdb.EnableExtendedResultCodes(true); err != nil {
log.Printf("Couldn't enable extended result codes in dbDiff(): %v\n", err.Error())
log.Printf("Couldn't enable extended result codes in dbDiff(): %v", err.Error())
return Diffs{}, err
}

Expand All @@ -152,7 +152,7 @@ func dbDiff(dbA string, dbB string, merge MergeStrategy, includeData bool) (Diff
"SELECT name, type FROM aux.sqlite_master WHERE name NOT LIKE 'sqlite_%' AND (type != 'table' OR (type = 'table' AND sql NOT LIKE 'CREATE VIRTUAL%%'))\n" +
" ORDER BY name")
if err != nil {
log.Printf("Error when preparing statement for object list in dbDiff(): %s\n", err)
log.Printf("Error when preparing statement for object list in dbDiff(): %s", err)
return Diffs{}, err
}
defer stmt.Finalize()
Expand All @@ -169,7 +169,7 @@ func dbDiff(dbA string, dbB string, merge MergeStrategy, includeData bool) (Diff
return nil
})
if err != nil {
log.Printf("Error when diffing single object in dbDiff: %s\n", err)
log.Printf("Error when diffing single object in dbDiff: %s", err)
return Diffs{}, err
}

Expand Down Expand Up @@ -319,7 +319,7 @@ func dataDiffForAllTableRows(sdb *sqlite.Conn, schemaName string, tableName stri
// Retrieve data and add it to the data diff object
_, _, data, err := SQLiteRunQuery(sdb, QuerySourceInternal, query, false, false)
if err != nil {
log.Printf("Error getting rows in dataDiffForAllTableRows(): %s\n", err)
log.Printf("Error getting rows in dataDiffForAllTableRows(): %s", err)
return nil, err
}
for _, row := range data.Records {
Expand Down Expand Up @@ -504,7 +504,7 @@ func dataDiffForModifiedTableRows(sdb *sqlite.Conn, tableName string, merge Merg
// Retrieve data and generate a new DataDiff object for each row
_, _, data, err := SQLiteRunQuery(sdb, QuerySourceInternal, query, false, false)
if err != nil {
log.Printf("Error getting rows in dataDiffForModifiedTableRows(): %s\n", err)
log.Printf("Error getting rows in dataDiffForModifiedTableRows(): %s", err)
return nil, err
}
for _, row := range data.Records {
Expand Down
6 changes: 3 additions & 3 deletions common/live.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,23 +55,23 @@ func ConnectMQ() (channel *amqp.Channel, err error) {
if err != nil {
return
}
log.Printf("%s connected to AMQP server using mutual TLS (mTLS): %v:%d\n", Conf.Live.Nodename, Conf.MQ.Server, Conf.MQ.Port)
log.Printf("%s connected to AMQP server using mutual TLS (mTLS): %v:%d", Conf.Live.Nodename, Conf.MQ.Server, Conf.MQ.Port)
} else {
// Fallback to just verifying the server certs for TLS. This is needed by the DB4S end point, as it
// uses certs from our own CA, so mTLS won't easily work with it.
conn, err = amqp.Dial(fmt.Sprintf("amqps://%s:%s@%s:%d/", Conf.MQ.Username, Conf.MQ.Password, Conf.MQ.Server, Conf.MQ.Port))
if err != nil {
return
}
log.Printf("%s connected to AMQP server with server-only TLS: %v:%d\n", Conf.Live.Nodename, Conf.MQ.Server, Conf.MQ.Port)
log.Printf("%s connected to AMQP server with server-only TLS: %v:%d", Conf.Live.Nodename, Conf.MQ.Server, Conf.MQ.Port)
}
} else {
// Everywhere else (eg docker container) doesn't *have* to use TLS
conn, err = amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%d/", Conf.MQ.Username, Conf.MQ.Password, Conf.MQ.Server, Conf.MQ.Port))
if err != nil {
return
}
log.Printf("%s connected to AMQP server without encryption: %v:%d\n", Conf.Live.Nodename, Conf.MQ.Server, Conf.MQ.Port)
log.Printf("%s connected to AMQP server without encryption: %v:%d", Conf.Live.Nodename, Conf.MQ.Server, Conf.MQ.Port)
}

channel, err = conn.Channel()
Expand Down
2 changes: 1 addition & 1 deletion common/memcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func ConnectCache() error {
}

// Log successful connection message for Memcached
log.Printf("Connected to Memcached: %v\n", Conf.Memcache.Server)
log.Printf("Connected to Memcached: %v", Conf.Memcache.Server)

return nil
}
Expand Down
Loading

0 comments on commit f6f8382

Please sign in to comment.