Skip to content
This repository was archived by the owner on Nov 24, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib/go-tc/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package tc

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

type LogsResponse struct {
Response []Log `json:"response"`
}

type Log struct {
ID *int `json:"id"`
LastUpdated *Time `json:"lastUpdated"`
Level *string `json:"level"`
Message *string `json:"message"`
TicketNum *int `json:"ticketNum"`
User *string `json:"user"`
}

type NewLogCountResp struct {
NewLogCount uint64 `json:"newLogcount"`
}
61 changes: 61 additions & 0 deletions traffic_ops/client/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package client

import (
"encoding/json"
"fmt"
"net/http"

"github.com/apache/trafficcontrol/lib/go-tc"
)

const (
API_v14_Logs = "/api/1.4/logs"
)

// GetLogsByQueryParams gets a list of logs filtered by query params.
func (to *Session) GetLogsByQueryParams(queryParams string) ([]tc.Log, ReqInf, error) {
URI := API_v14_Logs + queryParams
resp, remoteAddr, err := to.request(http.MethodGet, URI, nil)
reqInf := ReqInf{CacheHitStatus: CacheHitStatusMiss, RemoteAddr: remoteAddr}
if err != nil {
return nil, reqInf, err
}
defer resp.Body.Close()

var data tc.LogsResponse
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, reqInf, err
}

return data.Response, reqInf, nil
}

// GetLogs gets a list of logs.
func (to *Session) GetLogs() ([]tc.Log, ReqInf, error) {
return to.GetLogsByQueryParams("")
}

// GetLogsByLimit gets a list of logs limited to a certain number of logs.
func (to *Session) GetLogsByLimit(limit int) ([]tc.Log, ReqInf, error) {
return to.GetLogsByQueryParams(fmt.Sprintf("?limit=%d", limit))
}

// GetLogsByDays gets a list of logs limited to a certain number of days.
func (to *Session) GetLogsByDays(days int) ([]tc.Log, ReqInf, error) {
return to.GetLogsByQueryParams(fmt.Sprintf("?days=%d", days))
}
44 changes: 44 additions & 0 deletions traffic_ops/testing/api/v14/logs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package v14

/*

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import (
"testing"
)

func TestLogs(t *testing.T) {
WithObjs(t, []TCObj{}, func() {
GetTestLogs(t)
GetTestLogsByLimit(t)
})
}

func GetTestLogs(t *testing.T) {
_, _, err := TOSession.GetLogs()
if err != nil {
t.Fatalf("error getting logs: " + err.Error())
}
}

func GetTestLogsByLimit(t *testing.T) {
toLogs, _, err := TOSession.GetLogsByLimit(10)
if err != nil {
t.Fatalf("error getting logs: " + err.Error())
}
if len(toLogs) != 10 {
t.Fatalf("GET logs by limit: incorrect number of logs returned\n")
}
}
132 changes: 132 additions & 0 deletions traffic_ops/traffic_ops_golang/logs/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package logs

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import (
"database/sql"
"errors"
"net/http"
"time"

"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
)

const DefaultLogLimit = 1000
const DefaultLogLimitForDays = 1000000
const DefaultLogDays = 30

func Get(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"days", "limit"})
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()

limit := DefaultLogLimit
days := DefaultLogDays
if pDays, ok := inf.IntParams["days"]; ok {
days = pDays
limit = DefaultLogLimitForDays
}
if pLimit, ok := inf.IntParams["limit"]; ok {
limit = pLimit
}

setLastSeenCookie(w)
api.RespWriter(w, r, inf.Tx.Tx)(getLog(inf.Tx.Tx, days, limit))
}

func GetNewCount(w http.ResponseWriter, r *http.Request) {
inf, userErr, sysErr, errCode := api.NewInfo(r, nil, []string{"days", "limit"})
if userErr != nil || sysErr != nil {
api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)
return
}
defer inf.Close()

lastSeen, ok := getLastSeenCookie(r)
if !ok {
setLastSeenCookie(w) // only set the cookie if it didn't exist; emulates old Perl behavior
api.WriteResp(w, r, tc.NewLogCountResp{NewLogCount: 0})
return
}
newCount, err := getLogCountSince(inf.Tx.Tx, lastSeen)
if err != nil {
api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("getting log new count: "+err.Error()))
return
}
api.WriteResp(w, r, tc.NewLogCountResp{NewLogCount: newCount})
}

const LastSeenLogCookieName = "last_seen_log"

func setLastSeenCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: LastSeenLogCookieName,
Value: time.Now().Format(time.RFC3339Nano),
Expires: time.Now().Add(time.Hour * 24 * 7),
Path: "/",
})
}

// getLastSeenCookie returns the time of the last log seen cookie, or whether the cookie didn't exist or there was an error parsing it. Errors are not logged or returned, only that the cookie could not be retrieved.
func getLastSeenCookie(r *http.Request) (time.Time, bool) {
cookie, err := r.Cookie(LastSeenLogCookieName)
if err != nil {
return time.Time{}, false
}
lastSeen, err := time.Parse(time.RFC3339Nano, cookie.Value)
if err != nil {
return time.Time{}, false
}
return lastSeen, true
}

func getLog(tx *sql.Tx, days int, limit int) ([]tc.Log, error) {
rows, err := tx.Query(`
SELECT l.id, l.level, l.message, u.username as user, l.ticketnum, l.last_updated
FROM "log" as l JOIN tm_user as u ON l.tm_user = u.id
WHERE l.last_updated > now() - ($1 || ' DAY')::INTERVAL
ORDER BY l.last_updated DESC
LIMIT $2
`, days, limit)
if err != nil {
return nil, errors.New("querying logs: " + err.Error())
}
ls := []tc.Log{}
for rows.Next() {
l := tc.Log{}
if err = rows.Scan(&l.ID, &l.Level, &l.Message, &l.User, &l.TicketNum, &l.LastUpdated); err != nil {
return nil, errors.New("scanning logs: " + err.Error())
}
ls = append(ls, l)
}
return ls, nil
}

func getLogCountSince(tx *sql.Tx, since time.Time) (uint64, error) {
count := uint64(0)
if err := tx.QueryRow(`SELECT count(*) from log where last_updated > $1`, since).Scan(&count); err != nil {
return 0, errors.New("querying log last seen count: " + err.Error())
}
return count, nil
}
5 changes: 5 additions & 0 deletions traffic_ops/traffic_ops_golang/routing/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import (
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/federations"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/hwinfo"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/login"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/logs"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/origin"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/parameter"
"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/physlocation"
Expand Down Expand Up @@ -155,6 +156,10 @@ func Routes(d ServerData) ([]Route, []RawRoute, http.Handler, error) {
{1.1, http.MethodDelete, `divisions/{id}$`, api.DeleteHandler(&division.TODivision{}), auth.PrivLevelOperations, Authenticated, nil},
{1.1, http.MethodGet, `divisions/name/{name}/?(\.json)?$`, api.ReadHandler(&division.TODivision{}), auth.PrivLevelReadOnly, Authenticated, nil},

{1.1, http.MethodGet, `logs/?(\.json)?$`, logs.Get, auth.PrivLevelReadOnly, Authenticated, nil},
{1.1, http.MethodGet, `logs/{days}/days/?(\.json)?$`, logs.Get, auth.PrivLevelReadOnly, Authenticated, nil},
{1.1, http.MethodGet, `logs/newcount/?(\.json)?$`, logs.GetNewCount, auth.PrivLevelReadOnly, Authenticated, nil},

//HWInfo
{1.1, http.MethodGet, `hwinfo-wip/?(\.json)?$`, hwinfo.Get, auth.PrivLevelReadOnly, Authenticated, nil},

Expand Down