Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop cache_mgr URI support, add squid-internal-mgr support #102

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
88 changes: 18 additions & 70 deletions collector/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package collector

import (
"bufio"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"strconv"
"strings"
Expand All @@ -17,18 +15,10 @@ import (

/*CacheObjectClient holds information about squid manager */
type CacheObjectClient struct {
ch connectionHandler
basicAuthString string
headers []string
}

type connectionHandler interface {
connect() (net.Conn, error)
}

type connectionHandlerImpl struct {
hostname string
port int
baseURL string
username string
password string
headers []string
}

/*SquidClient provides functionality to fetch squid metrics */
Expand All @@ -38,55 +28,36 @@ type SquidClient interface {
GetInfos() (types.Counters, error)
}

const (
requestProtocol = "GET cache_object://localhost/%s HTTP/1.0"
)

func buildBasicAuthString(login string, password string) string {
if len(login) == 0 {
return ""
} else {
return base64.StdEncoding.EncodeToString([]byte(login + ":" + password))
}
}

type CacheObjectRequest struct {
Hostname string
Port int
Login string
Password string
Headers []string
}

/*NewCacheObjectClient initializes a new cache client */
func NewCacheObjectClient(cor *CacheObjectRequest) *CacheObjectClient {
func NewCacheObjectClient(hostname string, port int, username, password string, headers []string) *CacheObjectClient {
return &CacheObjectClient{
&connectionHandlerImpl{
cor.Hostname,
cor.Port,
},
buildBasicAuthString(cor.Login, cor.Password),
cor.Headers,
fmt.Sprintf("http://%s:%d/squid-internal-mgr/", hostname, port),
username,
password,
headers,
}
}

func (c *CacheObjectClient) readFromSquid(endpoint string) (*bufio.Reader, error) {
conn, err := c.ch.connect()

req, err := http.NewRequest(http.MethodGet, c.baseURL+endpoint, nil)
if err != nil {
return nil, err
}
r, err := get(conn, endpoint, c.basicAuthString, c.headers)

if c.username != "" && c.password != "" {
req.SetBasicAuth(c.username, c.password)
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}

if r.StatusCode != 200 {
return nil, fmt.Errorf("Non success code %d while fetching metrics", r.StatusCode)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("non-success code %d while fetching metrics", resp.StatusCode)
}

return bufio.NewReader(r.Body), err
return bufio.NewReader(resp.Body), err
}

func readLines(reader *bufio.Reader, lines chan<- string) {
Expand Down Expand Up @@ -206,29 +177,6 @@ func (c *CacheObjectClient) GetInfos() (types.Counters, error) {
return infos, err
}

func (ch *connectionHandlerImpl) connect() (net.Conn, error) {
return net.Dial("tcp", fmt.Sprintf("%s:%d", ch.hostname, ch.port))
}

func get(conn net.Conn, path string, basicAuthString string, headers []string) (*http.Response, error) {
rBody := append(headers, []string{
fmt.Sprintf(requestProtocol, path),
"Host: localhost",
"User-Agent: squidclient/3.5.12",
}...)

if len(basicAuthString) > 0 {
rBody = append(rBody, "Proxy-Authorization: Basic "+basicAuthString)
rBody = append(rBody, "Authorization: Basic "+basicAuthString)
}
rBody = append(rBody, "Accept: */*", "\r\n")
request := strings.Join(rBody, "\r\n")

fmt.Fprint(conn, request)

return http.ReadResponse(bufio.NewReader(conn), nil)
}

func decodeCounterStrings(line string) (types.Counter, error) {
if equal := strings.Index(line, "="); equal >= 0 {
if key := strings.TrimSpace(line[:equal]); len(key) > 0 {
Expand Down
50 changes: 12 additions & 38 deletions collector/client_test.go
Original file line number Diff line number Diff line change
@@ -1,57 +1,31 @@
package collector

import (
"net"
"net/http"
"net/http/httptest"
"testing"

"github.com/boynux/squid-exporter/types"
"github.com/stretchr/testify/assert"
)

type mockConnectionHandler struct {
server net.Conn

buffer []byte
}

func (c *mockConnectionHandler) connect() (net.Conn, error) {
var client net.Conn
c.server, client = net.Pipe()

return client, nil
}

func TestBuildBasicAuth(t *testing.T) {
u := "test_username"
p := "test_password"
expectedAuthString := "dGVzdF91c2VybmFtZTp0ZXN0X3Bhc3N3b3Jk"

ba := buildBasicAuthString(u, p)

assert.Equal(t, expectedAuthString, ba, "Basic Auth format doesn't match")
}

func TestReadFromSquid(t *testing.T) {
ch := &mockConnectionHandler{}

go func() {
b := make([]byte, 256)
n, _ := ch.server.Read(b)
ch.buffer = append(ch.buffer, b[:n]...)

ch.server.Write(b[n:])
ch.server.Close()
}()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.RequestURI, "/squid-internal-mgr/test")
}))
defer ts.Close()

coc := &CacheObjectClient{
ch,
ts.URL + "/squid-internal-mgr/",
"",
"",
[]string{},
}
expected := "GET cache_object://localhost/test HTTP/1.0\r\nHost: localhost\r\nUser-Agent: squidclient/3.5.12\r\nAccept: */*\r\n\r\n"
coc.readFromSquid("test")

assert.Equal(t, expected, string(ch.buffer))
_, err := coc.readFromSquid("test")
if err != nil {
t.Fatal(err)
}
}

func TestDecodeMetricStrings(t *testing.T) {
Expand Down
8 changes: 1 addition & 7 deletions collector/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,7 @@ func New(c *CollectorConfig) *Exporter {
infos = generateSquidInfos(c.Labels.Keys)

return &Exporter{
NewCacheObjectClient(&CacheObjectRequest{
c.Hostname,
c.Port,
c.Login,
c.Password,
c.Headers,
}),
NewCacheObjectClient(c.Hostname, c.Port, c.Login, c.Password, c.Headers),

c.Hostname,
c.Port,
Expand Down