mirror of
https://github.com/kubeshark/kubeshark.git
synced 2026-06-06 08:23:19 +00:00
Compare commits
17 Commits
36.0-dev7
...
36.0-dev24
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3e79ff244 | ||
|
|
d4b9fea5a7 | ||
|
|
d11770681b | ||
|
|
e9719cba3a | ||
|
|
15f7b889e2 | ||
|
|
d98ac0e8f7 | ||
|
|
a3c236ff0a | ||
|
|
4b280ecd6d | ||
|
|
de554f5fb6 | ||
|
|
7c159fffc0 | ||
|
|
1f2f63d11b | ||
|
|
e2544aea12 | ||
|
|
57e60073f5 | ||
|
|
f220ad2f1a | ||
|
|
5875ba0eb3 | ||
|
|
9aaf3f1423 | ||
|
|
a2463b739a |
4
.github/workflows/static_code_analysis.yml
vendored
4
.github/workflows/static_code_analysis.yml
vendored
@@ -32,6 +32,10 @@ jobs:
|
|||||||
id: agent_modified_files
|
id: agent_modified_files
|
||||||
run: devops/check_modified_files.sh agent/
|
run: devops/check_modified_files.sh agent/
|
||||||
|
|
||||||
|
- name: Generate eBPF object files and go bindings
|
||||||
|
id: generate_ebpf
|
||||||
|
run: make bpf
|
||||||
|
|
||||||
- name: Go lint - agent
|
- name: Go lint - agent
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v2
|
||||||
if: steps.agent_modified_files.outputs.matched == 'true'
|
if: steps.agent_modified_files.outputs.matched == 'true'
|
||||||
|
|||||||
4
.github/workflows/test.yml
vendored
4
.github/workflows/test.yml
vendored
@@ -40,6 +40,10 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
./devops/install-capstone.sh
|
./devops/install-capstone.sh
|
||||||
|
|
||||||
|
- name: Generate eBPF object files and go bindings
|
||||||
|
id: generate_ebpf
|
||||||
|
run: make bpf
|
||||||
|
|
||||||
- name: Check CLI modified files
|
- name: Check CLI modified files
|
||||||
id: cli_modified_files
|
id: cli_modified_files
|
||||||
run: devops/check_modified_files.sh cli/
|
run: devops/check_modified_files.sh cli/
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -56,3 +56,6 @@ tap/extensions/*/expect
|
|||||||
|
|
||||||
# Ignore *.log files
|
# Ignore *.log files
|
||||||
*.log
|
*.log
|
||||||
|
|
||||||
|
# Object files
|
||||||
|
*.o
|
||||||
|
|||||||
20
Makefile
20
Makefile
@@ -8,7 +8,7 @@ SHELL=/bin/bash
|
|||||||
# HELP
|
# HELP
|
||||||
# This will output the help for each task
|
# This will output the help for each task
|
||||||
# thanks to https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
|
# thanks to https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
|
||||||
.PHONY: help ui agent agent-debug cli tap docker
|
.PHONY: help ui agent agent-debug cli tap docker bpf clean-bpf
|
||||||
|
|
||||||
help: ## This help.
|
help: ## This help.
|
||||||
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
|
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
|
||||||
@@ -20,6 +20,13 @@ TS_SUFFIX="$(shell date '+%s')"
|
|||||||
GIT_BRANCH="$(shell git branch | grep \* | cut -d ' ' -f2 | tr '[:upper:]' '[:lower:]' | tr '/' '_')"
|
GIT_BRANCH="$(shell git branch | grep \* | cut -d ' ' -f2 | tr '[:upper:]' '[:lower:]' | tr '/' '_')"
|
||||||
BUCKET_PATH=static.up9.io/mizu/$(GIT_BRANCH)
|
BUCKET_PATH=static.up9.io/mizu/$(GIT_BRANCH)
|
||||||
export VER?=0.0
|
export VER?=0.0
|
||||||
|
ARCH=$(shell uname -m)
|
||||||
|
ifeq ($(ARCH),$(filter $(ARCH),aarch64 arm64))
|
||||||
|
BPF_O_ARCH_LABEL=arm64
|
||||||
|
else
|
||||||
|
BPF_O_ARCH_LABEL=x86
|
||||||
|
endif
|
||||||
|
BPF_O_FILES = tap/tlstapper/tlstapper46_bpfel_$(BPF_O_ARCH_LABEL).o tap/tlstapper/tlstapper_bpfel_$(BPF_O_ARCH_LABEL).o
|
||||||
|
|
||||||
ui: ## Build UI.
|
ui: ## Build UI.
|
||||||
@(cd ui; npm i ; npm run build; )
|
@(cd ui; npm i ; npm run build; )
|
||||||
@@ -31,11 +38,17 @@ cli: ## Build CLI.
|
|||||||
cli-debug: ## Build CLI.
|
cli-debug: ## Build CLI.
|
||||||
@echo "building cli"; cd cli && $(MAKE) build-debug
|
@echo "building cli"; cd cli && $(MAKE) build-debug
|
||||||
|
|
||||||
agent: ## Build agent.
|
agent: bpf ## Build agent.
|
||||||
@(echo "building mizu agent .." )
|
@(echo "building mizu agent .." )
|
||||||
@(cd agent; go build -o build/mizuagent main.go)
|
@(cd agent; go build -o build/mizuagent main.go)
|
||||||
@ls -l agent/build
|
@ls -l agent/build
|
||||||
|
|
||||||
|
bpf: $(BPF_O_FILES)
|
||||||
|
|
||||||
|
$(BPF_O_FILES): $(wildcard tap/tlstapper/bpf/**/*.[ch])
|
||||||
|
@(echo "building tlstapper bpf")
|
||||||
|
@(./tap/tlstapper/bpf-builder/build.sh)
|
||||||
|
|
||||||
agent-debug: ## Build agent for debug.
|
agent-debug: ## Build agent for debug.
|
||||||
@(echo "building mizu agent for debug.." )
|
@(echo "building mizu agent for debug.." )
|
||||||
@(cd agent; go build -gcflags="all=-N -l" -o build/mizuagent main.go)
|
@(cd agent; go build -gcflags="all=-N -l" -o build/mizuagent main.go)
|
||||||
@@ -76,6 +89,9 @@ clean-cli: ## Clean CLI.
|
|||||||
clean-docker: ## Run clean docker
|
clean-docker: ## Run clean docker
|
||||||
@(echo "DOCKER cleanup - NOT IMPLEMENTED YET " )
|
@(echo "DOCKER cleanup - NOT IMPLEMENTED YET " )
|
||||||
|
|
||||||
|
clean-bpf:
|
||||||
|
@(rm $(BPF_O_FILES) ; echo "bpf cleanup done" )
|
||||||
|
|
||||||
test-lint: ## Run lint on all modules
|
test-lint: ## Run lint on all modules
|
||||||
cd agent && golangci-lint run
|
cd agent && golangci-lint run
|
||||||
cd shared && golangci-lint run
|
cd shared && golangci-lint run
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ module.exports = defineConfig({
|
|||||||
testUrl: 'http://localhost:8899/',
|
testUrl: 'http://localhost:8899/',
|
||||||
redactHeaderContent: 'User-Header[REDACTED]',
|
redactHeaderContent: 'User-Header[REDACTED]',
|
||||||
redactBodyContent: '{ "User": "[REDACTED]" }',
|
redactBodyContent: '{ "User": "[REDACTED]" }',
|
||||||
regexMaskingBodyContent: '[REDACTED]',
|
|
||||||
greenFilterColor: 'rgb(210, 250, 210)',
|
greenFilterColor: 'rgb(210, 250, 210)',
|
||||||
redFilterColor: 'rgb(250, 214, 220)',
|
redFilterColor: 'rgb(250, 214, 220)',
|
||||||
bodyJsonClass: '.hljs',
|
bodyJsonClass: '.hljs',
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
import {isValueExistsInElement} from "../testHelpers/TrafficHelper";
|
|
||||||
|
|
||||||
it('Loading Mizu', function () {
|
|
||||||
cy.visit(Cypress.env('testUrl'));
|
|
||||||
});
|
|
||||||
|
|
||||||
isValueExistsInElement(true, Cypress.env('regexMaskingBodyContent'), Cypress.env('bodyJsonClass'));
|
|
||||||
@@ -2,10 +2,8 @@ package acceptanceTests
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
"bytes"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -343,7 +341,7 @@ func TestTapRedact(t *testing.T) {
|
|||||||
|
|
||||||
tapNamespace := GetDefaultTapNamespace()
|
tapNamespace := GetDefaultTapNamespace()
|
||||||
tapCmdArgs = append(tapCmdArgs, tapNamespace...)
|
tapCmdArgs = append(tapCmdArgs, tapNamespace...)
|
||||||
tapCmdArgs = append(tapCmdArgs, "--redact")
|
tapCmdArgs = append(tapCmdArgs, "--redact", "--set", "tap.redact-patterns.request-headers=User-Header", "--set", "tap.redact-patterns.request-body=User")
|
||||||
|
|
||||||
tapCmd := exec.Command(cliPath, tapCmdArgs...)
|
tapCmd := exec.Command(cliPath, tapCmdArgs...)
|
||||||
t.Logf("running command: %v", tapCmd.String())
|
t.Logf("running command: %v", tapCmd.String())
|
||||||
@@ -429,60 +427,6 @@ func TestTapNoRedact(t *testing.T) {
|
|||||||
RunCypressTests(t, "npx cypress run --spec \"cypress/e2e/tests/NoRedact.js\"")
|
RunCypressTests(t, "npx cypress run --spec \"cypress/e2e/tests/NoRedact.js\"")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTapRegexMasking(t *testing.T) {
|
|
||||||
if testing.Short() {
|
|
||||||
t.Skip("ignored acceptance test")
|
|
||||||
}
|
|
||||||
|
|
||||||
cliPath, cliPathErr := GetCliPath()
|
|
||||||
if cliPathErr != nil {
|
|
||||||
t.Errorf("failed to get cli path, err: %v", cliPathErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tapCmdArgs := GetDefaultTapCommandArgs()
|
|
||||||
|
|
||||||
tapNamespace := GetDefaultTapNamespace()
|
|
||||||
tapCmdArgs = append(tapCmdArgs, tapNamespace...)
|
|
||||||
|
|
||||||
tapCmdArgs = append(tapCmdArgs, "--redact")
|
|
||||||
|
|
||||||
tapCmdArgs = append(tapCmdArgs, "-r", "Mizu")
|
|
||||||
|
|
||||||
tapCmd := exec.Command(cliPath, tapCmdArgs...)
|
|
||||||
t.Logf("running command: %v", tapCmd.String())
|
|
||||||
|
|
||||||
t.Cleanup(func() {
|
|
||||||
if err := CleanupCommand(tapCmd); err != nil {
|
|
||||||
t.Logf("failed to cleanup tap command, err: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if err := tapCmd.Start(); err != nil {
|
|
||||||
t.Errorf("failed to start tap command, err: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
apiServerUrl := GetApiServerUrl(DefaultApiServerPort)
|
|
||||||
|
|
||||||
if err := WaitTapPodsReady(apiServerUrl); err != nil {
|
|
||||||
t.Errorf("failed to start tap pods on time, err: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
proxyUrl := GetProxyUrl(DefaultNamespaceName, DefaultServiceName)
|
|
||||||
for i := 0; i < DefaultEntriesCount; i++ {
|
|
||||||
response, requestErr := http.Post(fmt.Sprintf("%v/post", proxyUrl), "text/plain", bytes.NewBufferString("Mizu"))
|
|
||||||
if _, requestErr = ExecuteHttpRequest(response, requestErr); requestErr != nil {
|
|
||||||
t.Errorf("failed to send proxy request, err: %v", requestErr)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
RunCypressTests(t, "npx cypress run --spec \"cypress/e2e/tests/RegexMasking.js\"")
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTapIgnoredUserAgents(t *testing.T) {
|
func TestTapIgnoredUserAgents(t *testing.T) {
|
||||||
if testing.Short() {
|
if testing.Short() {
|
||||||
t.Skip("ignored acceptance test")
|
t.Skip("ignored acceptance test")
|
||||||
|
|||||||
@@ -97,7 +97,9 @@ func websocketHandler(c *gin.Context, eventHandlers EventHandlers, isTapper bool
|
|||||||
websocketIdsLock.Unlock()
|
websocketIdsLock.Unlock()
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
socketCleanup(socketId, connectedWebsockets[socketId])
|
if socketConnection := connectedWebsockets[socketId]; socketConnection != nil {
|
||||||
|
socketCleanup(socketId, socketConnection)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
eventHandlers.WebSocketConnect(c, socketId, isTapper)
|
eventHandlers.WebSocketConnect(c, socketId, isTapper)
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
package controllers
|
package controllers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
core "k8s.io/api/core/v1"
|
core "k8s.io/api/core/v1"
|
||||||
|
|
||||||
@@ -80,7 +83,24 @@ func GetGeneralStats(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetTrafficStats(c *gin.Context) {
|
func GetTrafficStats(c *gin.Context) {
|
||||||
c.JSON(http.StatusOK, providers.GetTrafficStats())
|
startTime, endTime, err := getStartEndTime(c)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, providers.GetTrafficStats(startTime, endTime))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getStartEndTime(c *gin.Context) (time.Time, time.Time, error) {
|
||||||
|
startTimeValue, err := strconv.Atoi(c.Query("startTimeMs"))
|
||||||
|
if err != nil {
|
||||||
|
return time.UnixMilli(0), time.UnixMilli(0), fmt.Errorf("invalid start time: %v", err)
|
||||||
|
}
|
||||||
|
endTimeValue, err := strconv.Atoi(c.Query("endTimeMs"))
|
||||||
|
if err != nil {
|
||||||
|
return time.UnixMilli(0), time.UnixMilli(0), fmt.Errorf("invalid end time: %v", err)
|
||||||
|
}
|
||||||
|
return time.UnixMilli(int64(startTimeValue)), time.UnixMilli(int64(endTimeValue)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetCurrentResolvingInformation(c *gin.Context) {
|
func GetCurrentResolvingInformation(c *gin.Context) {
|
||||||
|
|||||||
@@ -11,75 +11,30 @@ import (
|
|||||||
"github.com/up9inc/mizu/logger"
|
"github.com/up9inc/mizu/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Keep it because we might want cookies in the future
|
func BuildHeaders(rawHeaders map[string]interface{}) ([]Header, string, string, string, string, string) {
|
||||||
//func BuildCookies(rawCookies []interface{}) []har.Cookie {
|
|
||||||
// cookies := make([]har.Cookie, 0, len(rawCookies))
|
|
||||||
//
|
|
||||||
// for _, cookie := range rawCookies {
|
|
||||||
// c := cookie.(map[string]interface{})
|
|
||||||
// expiresStr := ""
|
|
||||||
// if c["expires"] != nil {
|
|
||||||
// expiresStr = c["expires"].(string)
|
|
||||||
// }
|
|
||||||
// expires, _ := time.Parse(time.RFC3339, expiresStr)
|
|
||||||
// httpOnly := false
|
|
||||||
// if c["httponly"] != nil {
|
|
||||||
// httpOnly, _ = strconv.ParseBool(c["httponly"].(string))
|
|
||||||
// }
|
|
||||||
// secure := false
|
|
||||||
// if c["secure"] != nil {
|
|
||||||
// secure, _ = strconv.ParseBool(c["secure"].(string))
|
|
||||||
// }
|
|
||||||
// path := ""
|
|
||||||
// if c["path"] != nil {
|
|
||||||
// path = c["path"].(string)
|
|
||||||
// }
|
|
||||||
// domain := ""
|
|
||||||
// if c["domain"] != nil {
|
|
||||||
// domain = c["domain"].(string)
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// cookies = append(cookies, har.Cookie{
|
|
||||||
// Name: c["name"].(string),
|
|
||||||
// Value: c["value"].(string),
|
|
||||||
// Path: path,
|
|
||||||
// Domain: domain,
|
|
||||||
// HTTPOnly: httpOnly,
|
|
||||||
// Secure: secure,
|
|
||||||
// Expires: expires,
|
|
||||||
// Expires8601: expiresStr,
|
|
||||||
// })
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// return cookies
|
|
||||||
//}
|
|
||||||
|
|
||||||
func BuildHeaders(rawHeaders []interface{}) ([]Header, string, string, string, string, string) {
|
|
||||||
var host, scheme, authority, path, status string
|
var host, scheme, authority, path, status string
|
||||||
headers := make([]Header, 0, len(rawHeaders))
|
headers := make([]Header, 0, len(rawHeaders))
|
||||||
|
|
||||||
for _, header := range rawHeaders {
|
for key, value := range rawHeaders {
|
||||||
h := header.(map[string]interface{})
|
|
||||||
|
|
||||||
headers = append(headers, Header{
|
headers = append(headers, Header{
|
||||||
Name: h["name"].(string),
|
Name: key,
|
||||||
Value: h["value"].(string),
|
Value: value.(string),
|
||||||
})
|
})
|
||||||
|
|
||||||
if h["name"] == "Host" {
|
if key == "Host" {
|
||||||
host = h["value"].(string)
|
host = value.(string)
|
||||||
}
|
}
|
||||||
if h["name"] == ":authority" {
|
if key == ":authority" {
|
||||||
authority = h["value"].(string)
|
authority = value.(string)
|
||||||
}
|
}
|
||||||
if h["name"] == ":scheme" {
|
if key == ":scheme" {
|
||||||
scheme = h["value"].(string)
|
scheme = value.(string)
|
||||||
}
|
}
|
||||||
if h["name"] == ":path" {
|
if key == ":path" {
|
||||||
path = h["value"].(string)
|
path = value.(string)
|
||||||
}
|
}
|
||||||
if h["name"] == ":status" {
|
if key == ":status" {
|
||||||
status = h["value"].(string)
|
status = value.(string)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,8 +74,8 @@ func BuildPostParams(rawParams []interface{}) []Param {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewRequest(request map[string]interface{}) (harRequest *Request, err error) {
|
func NewRequest(request map[string]interface{}) (harRequest *Request, err error) {
|
||||||
headers, host, scheme, authority, path, _ := BuildHeaders(request["_headers"].([]interface{}))
|
headers, host, scheme, authority, path, _ := BuildHeaders(request["headers"].(map[string]interface{}))
|
||||||
cookies := make([]Cookie, 0) // BuildCookies(request["_cookies"].([]interface{}))
|
cookies := make([]Cookie, 0)
|
||||||
|
|
||||||
postData, _ := request["postData"].(map[string]interface{})
|
postData, _ := request["postData"].(map[string]interface{})
|
||||||
mimeType := postData["mimeType"]
|
mimeType := postData["mimeType"]
|
||||||
@@ -134,12 +89,20 @@ func NewRequest(request map[string]interface{}) (harRequest *Request, err error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
queryString := make([]QueryString, 0)
|
queryString := make([]QueryString, 0)
|
||||||
for _, _qs := range request["_queryString"].([]interface{}) {
|
for key, value := range request["queryString"].(map[string]interface{}) {
|
||||||
qs := _qs.(map[string]interface{})
|
if valuesInterface, ok := value.([]interface{}); ok {
|
||||||
queryString = append(queryString, QueryString{
|
for _, valueInterface := range valuesInterface {
|
||||||
Name: qs["name"].(string),
|
queryString = append(queryString, QueryString{
|
||||||
Value: qs["value"].(string),
|
Name: key,
|
||||||
})
|
Value: valueInterface.(string),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
queryString = append(queryString, QueryString{
|
||||||
|
Name: key,
|
||||||
|
Value: value.(string),
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
url := fmt.Sprintf("http://%s%s", host, request["url"].(string))
|
url := fmt.Sprintf("http://%s%s", host, request["url"].(string))
|
||||||
@@ -172,8 +135,8 @@ func NewRequest(request map[string]interface{}) (harRequest *Request, err error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewResponse(response map[string]interface{}) (harResponse *Response, err error) {
|
func NewResponse(response map[string]interface{}) (harResponse *Response, err error) {
|
||||||
headers, _, _, _, _, _status := BuildHeaders(response["_headers"].([]interface{}))
|
headers, _, _, _, _, _status := BuildHeaders(response["headers"].(map[string]interface{}))
|
||||||
cookies := make([]Cookie, 0) // BuildCookies(response["_cookies"].([]interface{}))
|
cookies := make([]Cookie, 0)
|
||||||
|
|
||||||
content, _ := response["content"].(map[string]interface{})
|
content, _ := response["content"].(map[string]interface{})
|
||||||
mimeType := content["mimeType"]
|
mimeType := content["mimeType"]
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -82,13 +81,12 @@ func GetGeneralStats() *GeneralStats {
|
|||||||
|
|
||||||
func InitProtocolToColor(protocolMap map[string]*api.Protocol) {
|
func InitProtocolToColor(protocolMap map[string]*api.Protocol) {
|
||||||
for item, value := range protocolMap {
|
for item, value := range protocolMap {
|
||||||
splitted := strings.SplitN(item, "/", 3)
|
protocolToColor[api.GetProtocolSummary(item).Abbreviation] = value.BackgroundColor
|
||||||
protocolToColor[splitted[len(splitted)-1]] = value.BackgroundColor
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetTrafficStats() *TrafficStatsResponse {
|
func GetTrafficStats(startTime time.Time, endTime time.Time) *TrafficStatsResponse {
|
||||||
bucketsStatsCopy := getBucketStatsCopy()
|
bucketsStatsCopy := getFilteredBucketStatsCopy(startTime, endTime)
|
||||||
|
|
||||||
return &TrafficStatsResponse{
|
return &TrafficStatsResponse{
|
||||||
Protocols: getAvailableProtocols(bucketsStatsCopy),
|
Protocols: getAvailableProtocols(bucketsStatsCopy),
|
||||||
@@ -264,7 +262,7 @@ func convertAccumulativeStatsDictToArray(methodsPerProtocolAggregated map[string
|
|||||||
return protocolsData
|
return protocolsData
|
||||||
}
|
}
|
||||||
|
|
||||||
func getBucketStatsCopy() BucketStats {
|
func getFilteredBucketStatsCopy(startTime time.Time, endTime time.Time) BucketStats {
|
||||||
bucketStatsCopy := BucketStats{}
|
bucketStatsCopy := BucketStats{}
|
||||||
bucketStatsLocker.Lock()
|
bucketStatsLocker.Lock()
|
||||||
if err := copier.Copy(&bucketStatsCopy, bucketsStats); err != nil {
|
if err := copier.Copy(&bucketStatsCopy, bucketsStats); err != nil {
|
||||||
@@ -272,7 +270,18 @@ func getBucketStatsCopy() BucketStats {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
bucketStatsLocker.Unlock()
|
bucketStatsLocker.Unlock()
|
||||||
return bucketStatsCopy
|
|
||||||
|
filteredBucketStatsCopy := BucketStats{}
|
||||||
|
interval := InternalBucketThreshold
|
||||||
|
|
||||||
|
for _, bucket := range bucketStatsCopy {
|
||||||
|
if (bucket.BucketTime.After(startTime.Add(-1*interval/2).Round(interval)) && bucket.BucketTime.Before(endTime.Add(-1*interval/2).Round(interval))) ||
|
||||||
|
bucket.BucketTime.Equal(startTime.Add(-1*interval/2).Round(interval)) ||
|
||||||
|
bucket.BucketTime.Equal(endTime.Add(-1*interval/2).Round(interval)) {
|
||||||
|
filteredBucketStatsCopy = append(filteredBucketStatsCopy, bucket)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filteredBucketStatsCopy
|
||||||
}
|
}
|
||||||
|
|
||||||
func getAggregatedResultTiming(stats BucketStats, interval time.Duration) map[time.Time]map[string]map[string]*AccumulativeStatsCounter {
|
func getAggregatedResultTiming(stats BucketStats, interval time.Duration) map[time.Time]map[string]map[string]*AccumulativeStatsCounter {
|
||||||
|
|||||||
@@ -48,7 +48,6 @@ func init() {
|
|||||||
tapCmd.Flags().Uint16P(configStructs.GuiPortTapName, "p", defaultTapConfig.GuiPort, "Provide a custom port for the web interface webserver")
|
tapCmd.Flags().Uint16P(configStructs.GuiPortTapName, "p", defaultTapConfig.GuiPort, "Provide a custom port for the web interface webserver")
|
||||||
tapCmd.Flags().StringSliceP(configStructs.NamespacesTapName, "n", defaultTapConfig.Namespaces, "Namespaces selector")
|
tapCmd.Flags().StringSliceP(configStructs.NamespacesTapName, "n", defaultTapConfig.Namespaces, "Namespaces selector")
|
||||||
tapCmd.Flags().BoolP(configStructs.AllNamespacesTapName, "A", defaultTapConfig.AllNamespaces, "Tap all namespaces")
|
tapCmd.Flags().BoolP(configStructs.AllNamespacesTapName, "A", defaultTapConfig.AllNamespaces, "Tap all namespaces")
|
||||||
tapCmd.Flags().StringSliceP(configStructs.PlainTextFilterRegexesTapName, "r", defaultTapConfig.PlainTextFilterRegexes, "List of regex expressions that are used to filter matching values from text/plain http bodies")
|
|
||||||
tapCmd.Flags().Bool(configStructs.EnableRedactionTapName, defaultTapConfig.EnableRedaction, "Enables redaction of potentially sensitive request/response headers and body values")
|
tapCmd.Flags().Bool(configStructs.EnableRedactionTapName, defaultTapConfig.EnableRedaction, "Enables redaction of potentially sensitive request/response headers and body values")
|
||||||
tapCmd.Flags().String(configStructs.HumanMaxEntriesDBSizeTapName, defaultTapConfig.HumanMaxEntriesDBSize, "Override the default max entries db size")
|
tapCmd.Flags().String(configStructs.HumanMaxEntriesDBSizeTapName, defaultTapConfig.HumanMaxEntriesDBSize, "Override the default max entries db size")
|
||||||
tapCmd.Flags().String(configStructs.InsertionFilterName, defaultTapConfig.InsertionFilter, "Set the insertion filter. Accepts string or a file path.")
|
tapCmd.Flags().String(configStructs.InsertionFilterName, defaultTapConfig.InsertionFilter, "Set the insertion filter. Accepts string or a file path.")
|
||||||
|
|||||||
@@ -151,17 +151,18 @@ func printTappedPodsPreview(ctx context.Context, kubernetesProvider *kubernetes.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func startTapperSyncer(ctx context.Context, cancel context.CancelFunc, provider *kubernetes.Provider, targetNamespaces []string, mizuApiFilteringOptions api.TrafficFilteringOptions, startTime time.Time) error {
|
func startTapperSyncer(ctx context.Context, cancel context.CancelFunc, provider *kubernetes.Provider, targetNamespaces []string, startTime time.Time) error {
|
||||||
tapperSyncer, err := kubernetes.CreateAndStartMizuTapperSyncer(ctx, provider, kubernetes.TapperSyncerConfig{
|
tapperSyncer, err := kubernetes.CreateAndStartMizuTapperSyncer(ctx, provider, kubernetes.TapperSyncerConfig{
|
||||||
TargetNamespaces: targetNamespaces,
|
TargetNamespaces: targetNamespaces,
|
||||||
PodFilterRegex: *config.Config.Tap.PodRegex(),
|
PodFilterRegex: *config.Config.Tap.PodRegex(),
|
||||||
MizuResourcesNamespace: config.Config.MizuResourcesNamespace,
|
MizuResourcesNamespace: config.Config.MizuResourcesNamespace,
|
||||||
AgentImage: config.Config.AgentImage,
|
AgentImage: config.Config.AgentImage,
|
||||||
TapperResources: config.Config.Tap.TapperResources,
|
TapperResources: config.Config.Tap.TapperResources,
|
||||||
ImagePullPolicy: config.Config.ImagePullPolicy(),
|
ImagePullPolicy: config.Config.ImagePullPolicy(),
|
||||||
LogLevel: config.Config.LogLevel(),
|
LogLevel: config.Config.LogLevel(),
|
||||||
IgnoredUserAgents: config.Config.Tap.IgnoredUserAgents,
|
MizuApiFilteringOptions: api.TrafficFilteringOptions{
|
||||||
MizuApiFilteringOptions: mizuApiFilteringOptions,
|
IgnoredUserAgents: config.Config.Tap.IgnoredUserAgents,
|
||||||
|
},
|
||||||
MizuServiceAccountExists: state.mizuServiceAccountExists,
|
MizuServiceAccountExists: state.mizuServiceAccountExists,
|
||||||
ServiceMesh: config.Config.Tap.ServiceMesh,
|
ServiceMesh: config.Config.Tap.ServiceMesh,
|
||||||
Tls: config.Config.Tap.Tls,
|
Tls: config.Config.Tap.Tls,
|
||||||
@@ -229,27 +230,6 @@ func getErrorDisplayTextForK8sTapManagerError(err kubernetes.K8sTapManagerError)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getMizuApiFilteringOptions() (*api.TrafficFilteringOptions, error) {
|
|
||||||
var compiledRegexSlice []*api.SerializableRegexp
|
|
||||||
|
|
||||||
if config.Config.Tap.PlainTextFilterRegexes != nil && len(config.Config.Tap.PlainTextFilterRegexes) > 0 {
|
|
||||||
compiledRegexSlice = make([]*api.SerializableRegexp, 0)
|
|
||||||
for _, regexStr := range config.Config.Tap.PlainTextFilterRegexes {
|
|
||||||
compiledRegex, err := api.CompileRegexToSerializableRegexp(regexStr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
compiledRegexSlice = append(compiledRegexSlice, compiledRegex)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return &api.TrafficFilteringOptions{
|
|
||||||
PlainTextMaskingRegexes: compiledRegexSlice,
|
|
||||||
IgnoredUserAgents: config.Config.Tap.IgnoredUserAgents,
|
|
||||||
EnableRedaction: config.Config.Tap.EnableRedaction,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func watchApiServerPod(ctx context.Context, kubernetesProvider *kubernetes.Provider, cancel context.CancelFunc) {
|
func watchApiServerPod(ctx context.Context, kubernetesProvider *kubernetes.Provider, cancel context.CancelFunc) {
|
||||||
podExactRegex := regexp.MustCompile(fmt.Sprintf("^%s$", kubernetes.ApiServerPodName))
|
podExactRegex := regexp.MustCompile(fmt.Sprintf("^%s$", kubernetes.ApiServerPodName))
|
||||||
podWatchHelper := kubernetes.NewPodWatchHelper(kubernetesProvider, podExactRegex)
|
podWatchHelper := kubernetes.NewPodWatchHelper(kubernetesProvider, podExactRegex)
|
||||||
@@ -367,8 +347,7 @@ func watchApiServerEvents(ctx context.Context, kubernetesProvider *kubernetes.Pr
|
|||||||
func postApiServerStarted(ctx context.Context, kubernetesProvider *kubernetes.Provider, cancel context.CancelFunc) {
|
func postApiServerStarted(ctx context.Context, kubernetesProvider *kubernetes.Provider, cancel context.CancelFunc) {
|
||||||
startProxyReportErrorIfAny(kubernetesProvider, ctx, cancel, config.Config.Tap.GuiPort)
|
startProxyReportErrorIfAny(kubernetesProvider, ctx, cancel, config.Config.Tap.GuiPort)
|
||||||
|
|
||||||
options, _ := getMizuApiFilteringOptions()
|
if err := startTapperSyncer(ctx, cancel, kubernetesProvider, state.targetNamespaces, state.startTime); err != nil {
|
||||||
if err := startTapperSyncer(ctx, cancel, kubernetesProvider, state.targetNamespaces, *options, state.startTime); err != nil {
|
|
||||||
logger.Log.Errorf(uiUtils.Error, fmt.Sprintf("Error starting mizu tapper syncer: %v", errormessage.FormatError(err)))
|
logger.Log.Errorf(uiUtils.Error, fmt.Sprintf("Error starting mizu tapper syncer: %v", errormessage.FormatError(err)))
|
||||||
cancel()
|
cancel()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/up9inc/mizu/cli/uiUtils"
|
"github.com/up9inc/mizu/cli/uiUtils"
|
||||||
"github.com/up9inc/mizu/shared"
|
"github.com/up9inc/mizu/shared"
|
||||||
@@ -15,38 +16,43 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
GuiPortTapName = "gui-port"
|
GuiPortTapName = "gui-port"
|
||||||
NamespacesTapName = "namespaces"
|
NamespacesTapName = "namespaces"
|
||||||
AllNamespacesTapName = "all-namespaces"
|
AllNamespacesTapName = "all-namespaces"
|
||||||
PlainTextFilterRegexesTapName = "regex-masking"
|
EnableRedactionTapName = "redact"
|
||||||
EnableRedactionTapName = "redact"
|
HumanMaxEntriesDBSizeTapName = "max-entries-db-size"
|
||||||
HumanMaxEntriesDBSizeTapName = "max-entries-db-size"
|
InsertionFilterName = "insertion-filter"
|
||||||
InsertionFilterName = "insertion-filter"
|
DryRunTapName = "dry-run"
|
||||||
DryRunTapName = "dry-run"
|
ServiceMeshName = "service-mesh"
|
||||||
ServiceMeshName = "service-mesh"
|
TlsName = "tls"
|
||||||
TlsName = "tls"
|
ProfilerName = "profiler"
|
||||||
ProfilerName = "profiler"
|
MaxLiveStreamsName = "max-live-streams"
|
||||||
MaxLiveStreamsName = "max-live-streams"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type TapConfig struct {
|
type TapConfig struct {
|
||||||
PodRegexStr string `yaml:"regex" default:".*"`
|
PodRegexStr string `yaml:"regex" default:".*"`
|
||||||
GuiPort uint16 `yaml:"gui-port" default:"8899"`
|
GuiPort uint16 `yaml:"gui-port" default:"8899"`
|
||||||
ProxyHost string `yaml:"proxy-host" default:"127.0.0.1"`
|
ProxyHost string `yaml:"proxy-host" default:"127.0.0.1"`
|
||||||
Namespaces []string `yaml:"namespaces"`
|
Namespaces []string `yaml:"namespaces"`
|
||||||
AllNamespaces bool `yaml:"all-namespaces" default:"false"`
|
AllNamespaces bool `yaml:"all-namespaces" default:"false"`
|
||||||
PlainTextFilterRegexes []string `yaml:"regex-masking"`
|
IgnoredUserAgents []string `yaml:"ignored-user-agents"`
|
||||||
IgnoredUserAgents []string `yaml:"ignored-user-agents"`
|
EnableRedaction bool `yaml:"redact" default:"false"`
|
||||||
EnableRedaction bool `yaml:"redact" default:"false"`
|
RedactPatterns struct {
|
||||||
HumanMaxEntriesDBSize string `yaml:"max-entries-db-size" default:"200MB"`
|
RequestHeaders []string `yaml:"request-headers"`
|
||||||
InsertionFilter string `yaml:"insertion-filter" default:""`
|
ResponseHeaders []string `yaml:"response-headers"`
|
||||||
DryRun bool `yaml:"dry-run" default:"false"`
|
RequestBody []string `yaml:"request-body"`
|
||||||
ApiServerResources shared.Resources `yaml:"api-server-resources"`
|
ResponseBody []string `yaml:"response-body"`
|
||||||
TapperResources shared.Resources `yaml:"tapper-resources"`
|
RequestQueryParams []string `yaml:"request-query-params"`
|
||||||
ServiceMesh bool `yaml:"service-mesh" default:"false"`
|
} `yaml:"redact-patterns"`
|
||||||
Tls bool `yaml:"tls" default:"false"`
|
HumanMaxEntriesDBSize string `yaml:"max-entries-db-size" default:"200MB"`
|
||||||
Profiler bool `yaml:"profiler" default:"false"`
|
InsertionFilter string `yaml:"insertion-filter" default:""`
|
||||||
MaxLiveStreams int `yaml:"max-live-streams" default:"500"`
|
DryRun bool `yaml:"dry-run" default:"false"`
|
||||||
|
ApiServerResources shared.Resources `yaml:"api-server-resources"`
|
||||||
|
TapperResources shared.Resources `yaml:"tapper-resources"`
|
||||||
|
ServiceMesh bool `yaml:"service-mesh" default:"false"`
|
||||||
|
Tls bool `yaml:"tls" default:"false"`
|
||||||
|
Profiler bool `yaml:"profiler" default:"false"`
|
||||||
|
MaxLiveStreams int `yaml:"max-live-streams" default:"500"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (config *TapConfig) PodRegex() *regexp.Regexp {
|
func (config *TapConfig) PodRegex() *regexp.Regexp {
|
||||||
@@ -71,9 +77,48 @@ func (config *TapConfig) GetInsertionFilter() string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
redactFilter := getRedactFilter(config)
|
||||||
|
if insertionFilter != "" && redactFilter != "" {
|
||||||
|
return fmt.Sprintf("(%s) and (%s)", insertionFilter, redactFilter)
|
||||||
|
} else if insertionFilter == "" && redactFilter != "" {
|
||||||
|
return redactFilter
|
||||||
|
}
|
||||||
|
|
||||||
return insertionFilter
|
return insertionFilter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getRedactFilter(config *TapConfig) string {
|
||||||
|
if !config.EnableRedaction {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
var redactValues []string
|
||||||
|
for _, requestHeader := range config.RedactPatterns.RequestHeaders {
|
||||||
|
redactValues = append(redactValues, fmt.Sprintf("request.headers['%s']", requestHeader))
|
||||||
|
}
|
||||||
|
for _, responseHeader := range config.RedactPatterns.ResponseHeaders {
|
||||||
|
redactValues = append(redactValues, fmt.Sprintf("response.headers['%s']", responseHeader))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, requestBody := range config.RedactPatterns.RequestBody {
|
||||||
|
redactValues = append(redactValues, fmt.Sprintf("request.postData.text.json()...%s", requestBody))
|
||||||
|
}
|
||||||
|
for _, responseBody := range config.RedactPatterns.ResponseBody {
|
||||||
|
redactValues = append(redactValues, fmt.Sprintf("response.content.text.json()...%s", responseBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, requestQueryParams := range config.RedactPatterns.RequestQueryParams {
|
||||||
|
redactValues = append(redactValues, fmt.Sprintf("request.queryString['%s']", requestQueryParams))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(redactValues) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("redact(\"%s\")", strings.Join(redactValues, "\",\""))
|
||||||
|
}
|
||||||
|
|
||||||
func (config *TapConfig) Validate() error {
|
func (config *TapConfig) Validate() error {
|
||||||
_, compileErr := regexp.Compile(config.PodRegexStr)
|
_, compileErr := regexp.Compile(config.PodRegexStr)
|
||||||
if compileErr != nil {
|
if compileErr != nil {
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ log "Writing output to $MIZU_BENCHMARK_OUTPUT_DIR"
|
|||||||
cd $MIZU_HOME || exit 1
|
cd $MIZU_HOME || exit 1
|
||||||
|
|
||||||
export HOST_MODE=0
|
export HOST_MODE=0
|
||||||
export SENSITIVE_DATA_FILTERING_OPTIONS='{"EnableRedaction": false}'
|
export SENSITIVE_DATA_FILTERING_OPTIONS='{}'
|
||||||
export MIZU_DEBUG_DISABLE_PCAP=false
|
export MIZU_DEBUG_DISABLE_PCAP=false
|
||||||
export MIZU_DEBUG_DISABLE_TCP_REASSEMBLY=false
|
export MIZU_DEBUG_DISABLE_TCP_REASSEMBLY=false
|
||||||
export MIZU_DEBUG_DISABLE_TCP_STREAM=false
|
export MIZU_DEBUG_DISABLE_TCP_STREAM=false
|
||||||
|
|||||||
@@ -43,7 +43,6 @@ type TapperSyncerConfig struct {
|
|||||||
TapperResources shared.Resources
|
TapperResources shared.Resources
|
||||||
ImagePullPolicy core.PullPolicy
|
ImagePullPolicy core.PullPolicy
|
||||||
LogLevel logging.Level
|
LogLevel logging.Level
|
||||||
IgnoredUserAgents []string
|
|
||||||
MizuApiFilteringOptions api.TrafficFilteringOptions
|
MizuApiFilteringOptions api.TrafficFilteringOptions
|
||||||
MizuServiceAccountExists bool
|
MizuServiceAccountExists bool
|
||||||
ServiceMesh bool
|
ServiceMesh bool
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -25,6 +26,15 @@ func (protocol *ProtocolSummary) ToString() string {
|
|||||||
return fmt.Sprintf("%s?%s?%s", protocol.Name, protocol.Version, protocol.Abbreviation)
|
return fmt.Sprintf("%s?%s?%s", protocol.Name, protocol.Version, protocol.Abbreviation)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetProtocolSummary(inputString string) *ProtocolSummary {
|
||||||
|
splitted := strings.SplitN(inputString, "?", 3)
|
||||||
|
return &ProtocolSummary{
|
||||||
|
Name: splitted[0],
|
||||||
|
Version: splitted[1],
|
||||||
|
Abbreviation: splitted[2],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type Protocol struct {
|
type Protocol struct {
|
||||||
ProtocolSummary
|
ProtocolSummary
|
||||||
LongName string `json:"longName"`
|
LongName string `json:"longName"`
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
type TrafficFilteringOptions struct {
|
type TrafficFilteringOptions struct {
|
||||||
IgnoredUserAgents []string
|
IgnoredUserAgents []string
|
||||||
PlainTextMaskingRegexes []*SerializableRegexp
|
|
||||||
EnableRedaction bool
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,4 +13,4 @@ test-pull-bin:
|
|||||||
|
|
||||||
test-pull-expect:
|
test-pull-expect:
|
||||||
@mkdir -p expect
|
@mkdir -p expect
|
||||||
@[ "${skipexpect}" ] && echo "Skipping downloading expected JSONs" || gsutil -o 'GSUtil:parallel_process_count=5' -o 'GSUtil:parallel_thread_count=5' -m cp -r gs://static.up9.io/mizu/test-pcap/expect15/amqp/\* expect
|
@[ "${skipexpect}" ] && echo "Skipping downloading expected JSONs" || gsutil -o 'GSUtil:parallel_process_count=5' -o 'GSUtil:parallel_thread_count=5' -m cp -r gs://static.up9.io/mizu/test-pcap/expect16/amqp/\* expect
|
||||||
|
|||||||
@@ -4,16 +4,20 @@ go 1.17
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/stretchr/testify v1.7.0
|
github.com/stretchr/testify v1.7.0
|
||||||
|
github.com/up9inc/mizu/logger v0.0.0
|
||||||
github.com/up9inc/mizu/tap/api v0.0.0
|
github.com/up9inc/mizu/tap/api v0.0.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/davecgh/go-spew v1.1.0 // indirect
|
github.com/davecgh/go-spew v1.1.0 // indirect
|
||||||
|
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/up9inc/mizu/tap/dbgctl v0.0.0 // indirect
|
github.com/up9inc/mizu/tap/dbgctl v0.0.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
|
replace github.com/up9inc/mizu/logger v0.0.0 => ../../../logger
|
||||||
|
|
||||||
replace github.com/up9inc/mizu/tap/api v0.0.0 => ../../api
|
replace github.com/up9inc/mizu/tap/api v0.0.0 => ../../api
|
||||||
|
|
||||||
replace github.com/up9inc/mizu/tap/dbgctl v0.0.0 => ../../dbgctl
|
replace github.com/up9inc/mizu/tap/dbgctl v0.0.0 => ../../dbgctl
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88=
|
||||||
|
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
|
||||||
|
|
||||||
|
"github.com/up9inc/mizu/logger"
|
||||||
"github.com/up9inc/mizu/tap/api"
|
"github.com/up9inc/mizu/tap/api"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,14 +25,14 @@ var connectionMethodMap = map[int]string{
|
|||||||
61: "connection unblocked",
|
61: "connection unblocked",
|
||||||
}
|
}
|
||||||
|
|
||||||
// var channelMethodMap = map[int]string{
|
var channelMethodMap = map[int]string{
|
||||||
// 10: "channel open",
|
10: "channel open",
|
||||||
// 11: "channel open-ok",
|
11: "channel open-ok",
|
||||||
// 20: "channel flow",
|
20: "channel flow",
|
||||||
// 21: "channel flow-ok",
|
21: "channel flow-ok",
|
||||||
// 40: "channel close",
|
40: "channel close",
|
||||||
// 41: "channel close-ok",
|
41: "channel close-ok",
|
||||||
// }
|
}
|
||||||
|
|
||||||
var exchangeMethodMap = map[int]string{
|
var exchangeMethodMap = map[int]string{
|
||||||
10: "exchange declare",
|
10: "exchange declare",
|
||||||
@@ -94,29 +94,41 @@ type AMQPWrapper struct {
|
|||||||
Details interface{} `json:"details"`
|
Details interface{} `json:"details"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func emitAMQP(event interface{}, _type string, method string, connectionInfo *api.ConnectionInfo, captureTime time.Time, captureSize int, emitter api.Emitter, capture api.Capture) {
|
type emptyResponse struct {
|
||||||
request := &api.GenericMessage{
|
}
|
||||||
IsRequest: true,
|
|
||||||
CaptureTime: captureTime,
|
const emptyMethod = "empty"
|
||||||
Payload: AMQPPayload{
|
|
||||||
Data: &AMQPWrapper{
|
func getIdent(reader api.TcpReader, methodFrame *MethodFrame) (ident string) {
|
||||||
Method: method,
|
tcpID := reader.GetTcpID()
|
||||||
Url: "",
|
// To match methods to their Ok(s)
|
||||||
Details: event,
|
methodId := methodFrame.MethodId - methodFrame.MethodId%10
|
||||||
},
|
|
||||||
},
|
if reader.GetIsClient() {
|
||||||
|
ident = fmt.Sprintf(
|
||||||
|
"%s_%s_%s_%s_%d_%d_%d",
|
||||||
|
tcpID.SrcIP,
|
||||||
|
tcpID.DstIP,
|
||||||
|
tcpID.SrcPort,
|
||||||
|
tcpID.DstPort,
|
||||||
|
methodFrame.ChannelId,
|
||||||
|
methodFrame.ClassId,
|
||||||
|
methodId,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
ident = fmt.Sprintf(
|
||||||
|
"%s_%s_%s_%s_%d_%d_%d",
|
||||||
|
tcpID.DstIP,
|
||||||
|
tcpID.SrcIP,
|
||||||
|
tcpID.DstPort,
|
||||||
|
tcpID.SrcPort,
|
||||||
|
methodFrame.ChannelId,
|
||||||
|
methodFrame.ClassId,
|
||||||
|
methodId,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
item := &api.OutputChannelItem{
|
|
||||||
Protocol: protocol,
|
return
|
||||||
Capture: capture,
|
|
||||||
Timestamp: captureTime.UnixNano() / int64(time.Millisecond),
|
|
||||||
ConnectionInfo: connectionInfo,
|
|
||||||
Pair: &api.RequestResponsePair{
|
|
||||||
Request: *request,
|
|
||||||
Response: api.GenericMessage{},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
emitter.Emit(item)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func representProperties(properties map[string]interface{}, rep []interface{}) ([]interface{}, string, string) {
|
func representProperties(properties map[string]interface{}, rep []interface{}) ([]interface{}, string, string) {
|
||||||
@@ -460,6 +472,36 @@ func representQueueDeclare(event map[string]interface{}) []interface{} {
|
|||||||
return rep
|
return rep
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func representQueueDeclareOk(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
details, _ := json.Marshal([]api.TableData{
|
||||||
|
{
|
||||||
|
Name: "Queue",
|
||||||
|
Value: event["queue"].(string),
|
||||||
|
Selector: `response.queue`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "Message Count",
|
||||||
|
Value: fmt.Sprintf("%g", event["messageCount"].(float64)),
|
||||||
|
Selector: `response.messageCount`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "Consumer Count",
|
||||||
|
Value: fmt.Sprintf("%g", event["consumerCount"].(float64)),
|
||||||
|
Selector: `response.consumerCount`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Details",
|
||||||
|
Data: string(details),
|
||||||
|
})
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
func representExchangeDeclare(event map[string]interface{}) []interface{} {
|
func representExchangeDeclare(event map[string]interface{}) []interface{} {
|
||||||
rep := make([]interface{}, 0)
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
@@ -571,7 +613,7 @@ func representConnectionStart(event map[string]interface{}) []interface{} {
|
|||||||
x, _ := json.Marshal(value)
|
x, _ := json.Marshal(value)
|
||||||
outcome = string(x)
|
outcome = string(x)
|
||||||
default:
|
default:
|
||||||
panic("Unknown data type for the server property!")
|
logger.Log.Info("Unknown data type for the server property!")
|
||||||
}
|
}
|
||||||
headers = append(headers, api.TableData{
|
headers = append(headers, api.TableData{
|
||||||
Name: name,
|
Name: name,
|
||||||
@@ -593,6 +635,65 @@ func representConnectionStart(event map[string]interface{}) []interface{} {
|
|||||||
return rep
|
return rep
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func representConnectionStartOk(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
details, _ := json.Marshal([]api.TableData{
|
||||||
|
{
|
||||||
|
Name: "Mechanism",
|
||||||
|
Value: event["mechanism"].(string),
|
||||||
|
Selector: `response.mechanism`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "Mechanism",
|
||||||
|
Value: event["mechanism"].(string),
|
||||||
|
Selector: `response.response`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "Locale",
|
||||||
|
Value: event["locale"].(string),
|
||||||
|
Selector: `response.locale`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Details",
|
||||||
|
Data: string(details),
|
||||||
|
})
|
||||||
|
|
||||||
|
if event["clientProperties"] != nil {
|
||||||
|
headers := make([]api.TableData, 0)
|
||||||
|
for name, value := range event["clientProperties"].(map[string]interface{}) {
|
||||||
|
var outcome string
|
||||||
|
switch v := value.(type) {
|
||||||
|
case string:
|
||||||
|
outcome = v
|
||||||
|
case map[string]interface{}:
|
||||||
|
x, _ := json.Marshal(value)
|
||||||
|
outcome = string(x)
|
||||||
|
default:
|
||||||
|
logger.Log.Info("Unknown data type for the client property!")
|
||||||
|
}
|
||||||
|
headers = append(headers, api.TableData{
|
||||||
|
Name: name,
|
||||||
|
Value: outcome,
|
||||||
|
Selector: fmt.Sprintf(`response.clientProperties["%s"]`, name),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
sort.Slice(headers, func(i, j int) bool {
|
||||||
|
return headers[i].Name < headers[j].Name
|
||||||
|
})
|
||||||
|
headersMarshaled, _ := json.Marshal(headers)
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Client Properties",
|
||||||
|
Data: string(headersMarshaled),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
func representConnectionClose(event map[string]interface{}) []interface{} {
|
func representConnectionClose(event map[string]interface{}) []interface{} {
|
||||||
replyCode := ""
|
replyCode := ""
|
||||||
|
|
||||||
@@ -750,3 +851,122 @@ func representBasicConsume(event map[string]interface{}) []interface{} {
|
|||||||
|
|
||||||
return rep
|
return rep
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func representBasicConsumeOk(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
details, _ := json.Marshal([]api.TableData{
|
||||||
|
{
|
||||||
|
Name: "Consumer Tag",
|
||||||
|
Value: event["consumerTag"].(string),
|
||||||
|
Selector: `response.consumerTag`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Details",
|
||||||
|
Data: string(details),
|
||||||
|
})
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
func representConnectionOpen(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
details, _ := json.Marshal([]api.TableData{
|
||||||
|
{
|
||||||
|
Name: "Virtual Host",
|
||||||
|
Value: event["virtualHost"].(string),
|
||||||
|
Selector: `request.virtualHost`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Details",
|
||||||
|
Data: string(details),
|
||||||
|
})
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
func representConnectionTune(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
details, _ := json.Marshal([]api.TableData{
|
||||||
|
{
|
||||||
|
Name: "Channel Max",
|
||||||
|
Value: fmt.Sprintf("%g", event["channelMax"].(float64)),
|
||||||
|
Selector: `request.channelMax`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "Frame Max",
|
||||||
|
Value: fmt.Sprintf("%g", event["frameMax"].(float64)),
|
||||||
|
Selector: `request.frameMax`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "Heartbeat",
|
||||||
|
Value: fmt.Sprintf("%g", event["heartbeat"].(float64)),
|
||||||
|
Selector: `request.heartbeat`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Details",
|
||||||
|
Data: string(details),
|
||||||
|
})
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
func representBasicCancel(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
details, _ := json.Marshal([]api.TableData{
|
||||||
|
{
|
||||||
|
Name: "Consumer Tag",
|
||||||
|
Value: event["consumerTag"].(string),
|
||||||
|
Selector: `response.consumerTag`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "NoWait",
|
||||||
|
Value: strconv.FormatBool(event["noWait"].(bool)),
|
||||||
|
Selector: `request.noWait`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Details",
|
||||||
|
Data: string(details),
|
||||||
|
})
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
func representBasicCancelOk(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
details, _ := json.Marshal([]api.TableData{
|
||||||
|
{
|
||||||
|
Name: "Consumer Tag",
|
||||||
|
Value: event["consumerTag"].(string),
|
||||||
|
Selector: `response.consumerTag`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
rep = append(rep, api.SectionData{
|
||||||
|
Type: api.TABLE,
|
||||||
|
Title: "Details",
|
||||||
|
Data: string(details),
|
||||||
|
})
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
func representEmpty(event map[string]interface{}) []interface{} {
|
||||||
|
rep := make([]interface{}, 0)
|
||||||
|
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,22 +46,12 @@ func (d dissecting) Ping() {
|
|||||||
log.Printf("pong %s", protocol.Name)
|
log.Printf("pong %s", protocol.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
const amqpRequest string = "amqp_request"
|
|
||||||
|
|
||||||
func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.TrafficFilteringOptions) error {
|
func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.TrafficFilteringOptions) error {
|
||||||
r := AmqpReader{b}
|
r := AmqpReader{b}
|
||||||
|
|
||||||
var remaining int
|
var remaining int
|
||||||
var header *HeaderFrame
|
var header *HeaderFrame
|
||||||
|
|
||||||
connectionInfo := &api.ConnectionInfo{
|
|
||||||
ClientIP: reader.GetTcpID().SrcIP,
|
|
||||||
ClientPort: reader.GetTcpID().SrcPort,
|
|
||||||
ServerIP: reader.GetTcpID().DstIP,
|
|
||||||
ServerPort: reader.GetTcpID().DstPort,
|
|
||||||
IsOutgoing: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
eventBasicPublish := &BasicPublish{
|
eventBasicPublish := &BasicPublish{
|
||||||
Exchange: "",
|
Exchange: "",
|
||||||
RoutingKey: "",
|
RoutingKey: "",
|
||||||
@@ -83,6 +73,10 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
|
|
||||||
var lastMethodFrameMessage Message
|
var lastMethodFrameMessage Message
|
||||||
|
|
||||||
|
var ident string
|
||||||
|
isClient := reader.GetIsClient()
|
||||||
|
reqResMatcher := reader.GetReqResMatcher().(*requestResponseMatcher)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
frameVal, err := r.readFrame()
|
frameVal, err := r.readFrame()
|
||||||
if err == io.EOF {
|
if err == io.EOF {
|
||||||
@@ -121,16 +115,22 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
switch lastMethodFrameMessage.(type) {
|
switch lastMethodFrameMessage.(type) {
|
||||||
case *BasicPublish:
|
case *BasicPublish:
|
||||||
eventBasicPublish.Body = f.Body
|
eventBasicPublish.Body = f.Body
|
||||||
emitAMQP(*eventBasicPublish, amqpRequest, basicMethodMap[40], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
reqResMatcher.emitEvent(isClient, ident, basicMethodMap[40], *eventBasicPublish, reader)
|
||||||
|
reqResMatcher.emitEvent(!isClient, ident, emptyMethod, &emptyResponse{}, reader)
|
||||||
|
|
||||||
case *BasicDeliver:
|
case *BasicDeliver:
|
||||||
eventBasicDeliver.Body = f.Body
|
eventBasicDeliver.Body = f.Body
|
||||||
emitAMQP(*eventBasicDeliver, amqpRequest, basicMethodMap[60], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
reqResMatcher.emitEvent(!isClient, ident, basicMethodMap[60], *eventBasicDeliver, reader)
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, emptyMethod, &emptyResponse{}, reader)
|
||||||
}
|
}
|
||||||
|
|
||||||
case *MethodFrame:
|
case *MethodFrame:
|
||||||
reader.GetParent().SetProtocol(&protocol)
|
reader.GetParent().SetProtocol(&protocol)
|
||||||
|
|
||||||
lastMethodFrameMessage = f.Method
|
lastMethodFrameMessage = f.Method
|
||||||
|
|
||||||
|
ident = getIdent(reader, f)
|
||||||
|
|
||||||
switch m := f.Method.(type) {
|
switch m := f.Method.(type) {
|
||||||
case *BasicPublish:
|
case *BasicPublish:
|
||||||
eventBasicPublish.Exchange = m.Exchange
|
eventBasicPublish.Exchange = m.Exchange
|
||||||
@@ -146,7 +146,10 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
NoWait: m.NoWait,
|
NoWait: m.NoWait,
|
||||||
Arguments: m.Arguments,
|
Arguments: m.Arguments,
|
||||||
}
|
}
|
||||||
emitAMQP(*eventQueueBind, amqpRequest, queueMethodMap[20], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
reqResMatcher.emitEvent(isClient, ident, queueMethodMap[20], *eventQueueBind, reader)
|
||||||
|
|
||||||
|
case *QueueBindOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, queueMethodMap[21], m, reader)
|
||||||
|
|
||||||
case *BasicConsume:
|
case *BasicConsume:
|
||||||
eventBasicConsume := &BasicConsume{
|
eventBasicConsume := &BasicConsume{
|
||||||
@@ -158,7 +161,10 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
NoWait: m.NoWait,
|
NoWait: m.NoWait,
|
||||||
Arguments: m.Arguments,
|
Arguments: m.Arguments,
|
||||||
}
|
}
|
||||||
emitAMQP(*eventBasicConsume, amqpRequest, basicMethodMap[20], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
reqResMatcher.emitEvent(isClient, ident, basicMethodMap[20], *eventBasicConsume, reader)
|
||||||
|
|
||||||
|
case *BasicConsumeOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, basicMethodMap[21], m, reader)
|
||||||
|
|
||||||
case *BasicDeliver:
|
case *BasicDeliver:
|
||||||
eventBasicDeliver.ConsumerTag = m.ConsumerTag
|
eventBasicDeliver.ConsumerTag = m.ConsumerTag
|
||||||
@@ -177,7 +183,10 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
NoWait: m.NoWait,
|
NoWait: m.NoWait,
|
||||||
Arguments: m.Arguments,
|
Arguments: m.Arguments,
|
||||||
}
|
}
|
||||||
emitAMQP(*eventQueueDeclare, amqpRequest, queueMethodMap[10], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
reqResMatcher.emitEvent(isClient, ident, queueMethodMap[10], *eventQueueDeclare, reader)
|
||||||
|
|
||||||
|
case *QueueDeclareOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, queueMethodMap[11], m, reader)
|
||||||
|
|
||||||
case *ExchangeDeclare:
|
case *ExchangeDeclare:
|
||||||
eventExchangeDeclare := &ExchangeDeclare{
|
eventExchangeDeclare := &ExchangeDeclare{
|
||||||
@@ -190,17 +199,19 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
NoWait: m.NoWait,
|
NoWait: m.NoWait,
|
||||||
Arguments: m.Arguments,
|
Arguments: m.Arguments,
|
||||||
}
|
}
|
||||||
emitAMQP(*eventExchangeDeclare, amqpRequest, exchangeMethodMap[10], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
reqResMatcher.emitEvent(isClient, ident, exchangeMethodMap[10], *eventExchangeDeclare, reader)
|
||||||
|
|
||||||
|
case *ExchangeDeclareOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, exchangeMethodMap[11], m, reader)
|
||||||
|
|
||||||
case *ConnectionStart:
|
case *ConnectionStart:
|
||||||
eventConnectionStart := &ConnectionStart{
|
// In our tests, *ConnectionStart does not result in *ConnectionStartOk
|
||||||
VersionMajor: m.VersionMajor,
|
reqResMatcher.emitEvent(!isClient, ident, connectionMethodMap[10], m, reader)
|
||||||
VersionMinor: m.VersionMinor,
|
reqResMatcher.emitEvent(isClient, ident, emptyMethod, &emptyResponse{}, reader)
|
||||||
ServerProperties: m.ServerProperties,
|
|
||||||
Mechanisms: m.Mechanisms,
|
case *ConnectionStartOk:
|
||||||
Locales: m.Locales,
|
// In our tests, *ConnectionStart does not result in *ConnectionStartOk
|
||||||
}
|
reqResMatcher.emitEvent(isClient, ident, connectionMethodMap[11], m, reader)
|
||||||
emitAMQP(*eventConnectionStart, amqpRequest, connectionMethodMap[10], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
|
||||||
|
|
||||||
case *ConnectionClose:
|
case *ConnectionClose:
|
||||||
eventConnectionClose := &ConnectionClose{
|
eventConnectionClose := &ConnectionClose{
|
||||||
@@ -209,7 +220,40 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
ClassId: m.ClassId,
|
ClassId: m.ClassId,
|
||||||
MethodId: m.MethodId,
|
MethodId: m.MethodId,
|
||||||
}
|
}
|
||||||
emitAMQP(*eventConnectionClose, amqpRequest, connectionMethodMap[50], connectionInfo, reader.GetCaptureTime(), reader.GetReadProgress().Current(), reader.GetEmitter(), reader.GetParent().GetOrigin())
|
reqResMatcher.emitEvent(isClient, ident, connectionMethodMap[50], *eventConnectionClose, reader)
|
||||||
|
|
||||||
|
case *ConnectionCloseOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, connectionMethodMap[51], m, reader)
|
||||||
|
|
||||||
|
case *connectionOpen:
|
||||||
|
eventConnectionOpen := &connectionOpen{
|
||||||
|
VirtualHost: m.VirtualHost,
|
||||||
|
}
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, connectionMethodMap[40], *eventConnectionOpen, reader)
|
||||||
|
|
||||||
|
case *connectionOpenOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, connectionMethodMap[41], m, reader)
|
||||||
|
|
||||||
|
case *channelOpen:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, channelMethodMap[10], m, reader)
|
||||||
|
|
||||||
|
case *channelOpenOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, channelMethodMap[11], m, reader)
|
||||||
|
|
||||||
|
case *connectionTune:
|
||||||
|
// In our tests, *connectionTune does not result in *connectionTuneOk
|
||||||
|
reqResMatcher.emitEvent(!isClient, ident, connectionMethodMap[30], m, reader)
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, emptyMethod, &emptyResponse{}, reader)
|
||||||
|
|
||||||
|
case *connectionTuneOk:
|
||||||
|
// In our tests, *connectionTune does not result in *connectionTuneOk
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, connectionMethodMap[31], m, reader)
|
||||||
|
|
||||||
|
case *basicCancel:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, basicMethodMap[30], m, reader)
|
||||||
|
|
||||||
|
case *basicCancelOk:
|
||||||
|
reqResMatcher.emitEvent(isClient, ident, basicMethodMap[31], m, reader)
|
||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -220,9 +264,17 @@ func (d dissecting) Dissect(b *bufio.Reader, reader api.TcpReader, options *api.
|
|||||||
|
|
||||||
func (d dissecting) Analyze(item *api.OutputChannelItem, resolvedSource string, resolvedDestination string, namespace string) *api.Entry {
|
func (d dissecting) Analyze(item *api.OutputChannelItem, resolvedSource string, resolvedDestination string, namespace string) *api.Entry {
|
||||||
request := item.Pair.Request.Payload.(map[string]interface{})
|
request := item.Pair.Request.Payload.(map[string]interface{})
|
||||||
|
response := item.Pair.Response.Payload.(map[string]interface{})
|
||||||
reqDetails := request["details"].(map[string]interface{})
|
reqDetails := request["details"].(map[string]interface{})
|
||||||
|
resDetails := response["details"].(map[string]interface{})
|
||||||
|
|
||||||
|
elapsedTime := item.Pair.Response.CaptureTime.Sub(item.Pair.Request.CaptureTime).Round(time.Millisecond).Milliseconds()
|
||||||
|
if elapsedTime < 0 {
|
||||||
|
elapsedTime = 0
|
||||||
|
}
|
||||||
|
|
||||||
reqDetails["method"] = request["method"]
|
reqDetails["method"] = request["method"]
|
||||||
|
resDetails["method"] = response["method"]
|
||||||
return &api.Entry{
|
return &api.Entry{
|
||||||
Protocol: protocol.ProtocolSummary,
|
Protocol: protocol.ProtocolSummary,
|
||||||
Capture: item.Capture,
|
Capture: item.Capture,
|
||||||
@@ -236,13 +288,15 @@ func (d dissecting) Analyze(item *api.OutputChannelItem, resolvedSource string,
|
|||||||
IP: item.ConnectionInfo.ServerIP,
|
IP: item.ConnectionInfo.ServerIP,
|
||||||
Port: item.ConnectionInfo.ServerPort,
|
Port: item.ConnectionInfo.ServerPort,
|
||||||
},
|
},
|
||||||
Namespace: namespace,
|
Namespace: namespace,
|
||||||
Outgoing: item.ConnectionInfo.IsOutgoing,
|
Outgoing: item.ConnectionInfo.IsOutgoing,
|
||||||
Request: reqDetails,
|
Request: reqDetails,
|
||||||
RequestSize: item.Pair.Request.CaptureSize,
|
Response: resDetails,
|
||||||
Timestamp: item.Timestamp,
|
RequestSize: item.Pair.Request.CaptureSize,
|
||||||
StartTime: item.Pair.Request.CaptureTime,
|
ResponseSize: item.Pair.Response.CaptureSize,
|
||||||
ElapsedTime: 0,
|
Timestamp: item.Timestamp,
|
||||||
|
StartTime: item.Pair.Request.CaptureTime,
|
||||||
|
ElapsedTime: elapsedTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -283,6 +337,21 @@ func (d dissecting) Summarize(entry *api.Entry) *api.BaseEntry {
|
|||||||
case basicMethodMap[20]:
|
case basicMethodMap[20]:
|
||||||
summary = entry.Request["queue"].(string)
|
summary = entry.Request["queue"].(string)
|
||||||
summaryQuery = fmt.Sprintf(`request.queue == "%s"`, summary)
|
summaryQuery = fmt.Sprintf(`request.queue == "%s"`, summary)
|
||||||
|
case connectionMethodMap[40]:
|
||||||
|
summary = entry.Request["virtualHost"].(string)
|
||||||
|
summaryQuery = fmt.Sprintf(`request.virtualHost == "%s"`, summary)
|
||||||
|
case connectionMethodMap[30]:
|
||||||
|
summary = fmt.Sprintf("%g", entry.Request["channelMax"].(float64))
|
||||||
|
summaryQuery = fmt.Sprintf(`request.channelMax == "%s"`, summary)
|
||||||
|
case connectionMethodMap[31]:
|
||||||
|
summary = fmt.Sprintf("%g", entry.Request["channelMax"].(float64))
|
||||||
|
summaryQuery = fmt.Sprintf(`request.channelMax == "%s"`, summary)
|
||||||
|
case basicMethodMap[30]:
|
||||||
|
summary = entry.Request["consumerTag"].(string)
|
||||||
|
summaryQuery = fmt.Sprintf(`request.consumerTag == "%s"`, summary)
|
||||||
|
case basicMethodMap[31]:
|
||||||
|
summary = entry.Request["consumerTag"].(string)
|
||||||
|
summaryQuery = fmt.Sprintf(`request.consumerTag == "%s"`, summary)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &api.BaseEntry{
|
return &api.BaseEntry{
|
||||||
@@ -306,6 +375,8 @@ func (d dissecting) Summarize(entry *api.Entry) *api.BaseEntry {
|
|||||||
func (d dissecting) Represent(request map[string]interface{}, response map[string]interface{}) (object []byte, err error) {
|
func (d dissecting) Represent(request map[string]interface{}, response map[string]interface{}) (object []byte, err error) {
|
||||||
representation := make(map[string]interface{})
|
representation := make(map[string]interface{})
|
||||||
var repRequest []interface{}
|
var repRequest []interface{}
|
||||||
|
var repResponse []interface{}
|
||||||
|
|
||||||
switch request["method"].(string) {
|
switch request["method"].(string) {
|
||||||
case basicMethodMap[40]:
|
case basicMethodMap[40]:
|
||||||
repRequest = representBasicPublish(request)
|
repRequest = representBasicPublish(request)
|
||||||
@@ -323,9 +394,45 @@ func (d dissecting) Represent(request map[string]interface{}, response map[strin
|
|||||||
repRequest = representQueueBind(request)
|
repRequest = representQueueBind(request)
|
||||||
case basicMethodMap[20]:
|
case basicMethodMap[20]:
|
||||||
repRequest = representBasicConsume(request)
|
repRequest = representBasicConsume(request)
|
||||||
|
case connectionMethodMap[40]:
|
||||||
|
repRequest = representConnectionOpen(request)
|
||||||
|
case channelMethodMap[10]:
|
||||||
|
repRequest = representEmpty(request)
|
||||||
|
case connectionMethodMap[30]:
|
||||||
|
repRequest = representConnectionTune(request)
|
||||||
|
case basicMethodMap[30]:
|
||||||
|
repRequest = representBasicCancel(request)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch response["method"].(string) {
|
||||||
|
case queueMethodMap[11]:
|
||||||
|
repResponse = representQueueDeclareOk(response)
|
||||||
|
case exchangeMethodMap[11]:
|
||||||
|
repResponse = representEmpty(response)
|
||||||
|
case connectionMethodMap[11]:
|
||||||
|
repResponse = representConnectionStartOk(response)
|
||||||
|
case connectionMethodMap[51]:
|
||||||
|
repResponse = representEmpty(response)
|
||||||
|
case basicMethodMap[21]:
|
||||||
|
repResponse = representBasicConsumeOk(response)
|
||||||
|
case queueMethodMap[21]:
|
||||||
|
repResponse = representEmpty(response)
|
||||||
|
case connectionMethodMap[41]:
|
||||||
|
repResponse = representEmpty(response)
|
||||||
|
case channelMethodMap[11]:
|
||||||
|
repResponse = representEmpty(request)
|
||||||
|
case connectionMethodMap[31]:
|
||||||
|
repResponse = representConnectionTune(request)
|
||||||
|
case basicMethodMap[31]:
|
||||||
|
repResponse = representBasicCancelOk(request)
|
||||||
|
case emptyMethod:
|
||||||
|
repResponse = representEmpty(response)
|
||||||
|
}
|
||||||
|
|
||||||
representation["request"] = repRequest
|
representation["request"] = repRequest
|
||||||
|
representation["response"] = repResponse
|
||||||
object, err = json.Marshal(representation)
|
object, err = json.Marshal(representation)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,7 +443,7 @@ func (d dissecting) Macros() map[string]string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d dissecting) NewResponseRequestMatcher() api.RequestResponseMatcher {
|
func (d dissecting) NewResponseRequestMatcher() api.RequestResponseMatcher {
|
||||||
return nil
|
return createResponseRequestMatcher()
|
||||||
}
|
}
|
||||||
|
|
||||||
var Dissector dissecting
|
var Dissector dissecting
|
||||||
|
|||||||
113
tap/extensions/amqp/matcher.go
Normal file
113
tap/extensions/amqp/matcher.go
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
package amqp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/up9inc/mizu/tap/api"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Key is {client_addr}_{client_port}_{dest_addr}_{dest_port}_{channel_id}_{class_id}_{method_id}
|
||||||
|
type requestResponseMatcher struct {
|
||||||
|
openMessagesMap *sync.Map
|
||||||
|
}
|
||||||
|
|
||||||
|
func createResponseRequestMatcher() api.RequestResponseMatcher {
|
||||||
|
return &requestResponseMatcher{openMessagesMap: &sync.Map{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (matcher *requestResponseMatcher) GetMap() *sync.Map {
|
||||||
|
return matcher.openMessagesMap
|
||||||
|
}
|
||||||
|
|
||||||
|
func (matcher *requestResponseMatcher) SetMaxTry(value int) {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (matcher *requestResponseMatcher) emitEvent(isRequest bool, ident string, method string, event interface{}, reader api.TcpReader) {
|
||||||
|
reader.GetParent().SetProtocol(&protocol)
|
||||||
|
|
||||||
|
var item *api.OutputChannelItem
|
||||||
|
if isRequest {
|
||||||
|
item = matcher.registerRequest(ident, method, event, reader.GetCaptureTime(), reader.GetReadProgress().Current())
|
||||||
|
} else {
|
||||||
|
item = matcher.registerResponse(ident, method, event, reader.GetCaptureTime(), reader.GetReadProgress().Current())
|
||||||
|
}
|
||||||
|
|
||||||
|
if item != nil {
|
||||||
|
item.ConnectionInfo = &api.ConnectionInfo{
|
||||||
|
ClientIP: reader.GetTcpID().SrcIP,
|
||||||
|
ClientPort: reader.GetTcpID().SrcPort,
|
||||||
|
ServerIP: reader.GetTcpID().DstIP,
|
||||||
|
ServerPort: reader.GetTcpID().DstPort,
|
||||||
|
IsOutgoing: true,
|
||||||
|
}
|
||||||
|
item.Capture = reader.GetParent().GetOrigin()
|
||||||
|
reader.GetEmitter().Emit(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (matcher *requestResponseMatcher) registerRequest(ident string, method string, request interface{}, captureTime time.Time, captureSize int) *api.OutputChannelItem {
|
||||||
|
requestAMQPMessage := api.GenericMessage{
|
||||||
|
IsRequest: true,
|
||||||
|
CaptureTime: captureTime,
|
||||||
|
CaptureSize: captureSize,
|
||||||
|
Payload: AMQPPayload{
|
||||||
|
Data: &AMQPWrapper{
|
||||||
|
Method: method,
|
||||||
|
Url: "",
|
||||||
|
Details: request,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if response, found := matcher.openMessagesMap.LoadAndDelete(ident); found {
|
||||||
|
// Type assertion always succeeds because all of the map's values are of api.GenericMessage type
|
||||||
|
responseAMQPMessage := response.(*api.GenericMessage)
|
||||||
|
if responseAMQPMessage.IsRequest {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return matcher.preparePair(&requestAMQPMessage, responseAMQPMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
matcher.openMessagesMap.Store(ident, &requestAMQPMessage)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (matcher *requestResponseMatcher) registerResponse(ident string, method string, response interface{}, captureTime time.Time, captureSize int) *api.OutputChannelItem {
|
||||||
|
responseAMQPMessage := api.GenericMessage{
|
||||||
|
IsRequest: false,
|
||||||
|
CaptureTime: captureTime,
|
||||||
|
CaptureSize: captureSize,
|
||||||
|
Payload: AMQPPayload{
|
||||||
|
Data: &AMQPWrapper{
|
||||||
|
Method: method,
|
||||||
|
Url: "",
|
||||||
|
Details: response,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if request, found := matcher.openMessagesMap.LoadAndDelete(ident); found {
|
||||||
|
// Type assertion always succeeds because all of the map's values are of api.GenericMessage type
|
||||||
|
requestAMQPMessage := request.(*api.GenericMessage)
|
||||||
|
if !requestAMQPMessage.IsRequest {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return matcher.preparePair(requestAMQPMessage, &responseAMQPMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
matcher.openMessagesMap.Store(ident, &responseAMQPMessage)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (matcher *requestResponseMatcher) preparePair(requestAMQPMessage *api.GenericMessage, responseAMQPMessage *api.GenericMessage) *api.OutputChannelItem {
|
||||||
|
return &api.OutputChannelItem{
|
||||||
|
Protocol: protocol,
|
||||||
|
Timestamp: requestAMQPMessage.CaptureTime.UnixNano() / int64(time.Millisecond),
|
||||||
|
ConnectionInfo: nil,
|
||||||
|
Pair: &api.RequestResponsePair{
|
||||||
|
Request: *requestAMQPMessage,
|
||||||
|
Response: *responseAMQPMessage,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -81,10 +81,10 @@ func (msg *ConnectionStart) read(r io.Reader) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ConnectionStartOk struct {
|
type ConnectionStartOk struct {
|
||||||
ClientProperties Table
|
ClientProperties Table `json:"clientProperties"`
|
||||||
Mechanism string
|
Mechanism string `json:"mechanism"`
|
||||||
Response string
|
Response string `json:"response"`
|
||||||
Locale string
|
Locale string `json:"locale"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (msg *ConnectionStartOk) read(r io.Reader) (err error) {
|
func (msg *ConnectionStartOk) read(r io.Reader) (err error) {
|
||||||
@@ -135,9 +135,9 @@ func (msg *connectionSecureOk) read(r io.Reader) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type connectionTune struct {
|
type connectionTune struct {
|
||||||
ChannelMax uint16
|
ChannelMax uint16 `json:"channelMax"`
|
||||||
FrameMax uint32
|
FrameMax uint32 `json:"frameMax"`
|
||||||
Heartbeat uint16
|
Heartbeat uint16 `json:"heartbeat"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (msg *connectionTune) read(r io.Reader) (err error) {
|
func (msg *connectionTune) read(r io.Reader) (err error) {
|
||||||
@@ -181,7 +181,7 @@ func (msg *connectionTuneOk) read(r io.Reader) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type connectionOpen struct {
|
type connectionOpen struct {
|
||||||
VirtualHost string
|
VirtualHost string `json:"virtualHost"`
|
||||||
reserved1 string
|
reserved1 string
|
||||||
reserved2 bool
|
reserved2 bool
|
||||||
}
|
}
|
||||||
@@ -580,9 +580,9 @@ func (msg *QueueDeclare) read(r io.Reader) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type QueueDeclareOk struct {
|
type QueueDeclareOk struct {
|
||||||
Queue string
|
Queue string `json:"queue"`
|
||||||
MessageCount uint32
|
MessageCount uint32 `json:"messageCount"`
|
||||||
ConsumerCount uint32
|
ConsumerCount uint32 `json:"consumerCount"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (msg *QueueDeclareOk) read(r io.Reader) (err error) {
|
func (msg *QueueDeclareOk) read(r io.Reader) (err error) {
|
||||||
@@ -840,7 +840,7 @@ func (msg *BasicConsume) read(r io.Reader) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type BasicConsumeOk struct {
|
type BasicConsumeOk struct {
|
||||||
ConsumerTag string
|
ConsumerTag string `json:"consumerTag"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (msg *BasicConsumeOk) read(r io.Reader) (err error) {
|
func (msg *BasicConsumeOk) read(r io.Reader) (err error) {
|
||||||
@@ -853,8 +853,8 @@ func (msg *BasicConsumeOk) read(r io.Reader) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type basicCancel struct {
|
type basicCancel struct {
|
||||||
ConsumerTag string
|
ConsumerTag string `json:"consumerTag"`
|
||||||
NoWait bool
|
NoWait bool `json:"noWait"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (msg *basicCancel) read(r io.Reader) (err error) {
|
func (msg *basicCancel) read(r io.Reader) (err error) {
|
||||||
@@ -873,7 +873,7 @@ func (msg *basicCancel) read(r io.Reader) (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type basicCancelOk struct {
|
type basicCancelOk struct {
|
||||||
ConsumerTag string
|
ConsumerTag string `json:"consumerTag"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (msg *basicCancelOk) read(r io.Reader) (err error) {
|
func (msg *basicCancelOk) read(r io.Reader) (err error) {
|
||||||
|
|||||||
@@ -13,4 +13,4 @@ test-pull-bin:
|
|||||||
|
|
||||||
test-pull-expect:
|
test-pull-expect:
|
||||||
@mkdir -p expect
|
@mkdir -p expect
|
||||||
@[ "${skipexpect}" ] && echo "Skipping downloading expected JSONs" || gsutil -o 'GSUtil:parallel_process_count=5' -o 'GSUtil:parallel_thread_count=5' -m cp -r gs://static.up9.io/mizu/test-pcap/expect15/http/\* expect
|
@[ "${skipexpect}" ] && echo "Skipping downloading expected JSONs" || gsutil -o 'GSUtil:parallel_process_count=5' -o 'GSUtil:parallel_thread_count=5' -m cp -r gs://static.up9.io/mizu/test-pcap/expect16/http/\* expect
|
||||||
|
|||||||
@@ -18,10 +18,6 @@ func filterAndEmit(item *api.OutputChannelItem, emitter api.Emitter, options *ap
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.EnableRedaction {
|
|
||||||
FilterSensitiveData(item, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
replaceForwardedFor(item)
|
replaceForwardedFor(item)
|
||||||
|
|
||||||
emitter.Emit(item)
|
emitter.Emit(item)
|
||||||
|
|||||||
@@ -6,13 +6,16 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/up9inc/mizu/tap/api"
|
"github.com/up9inc/mizu/tap/api"
|
||||||
)
|
)
|
||||||
|
|
||||||
func mapSliceRebuildAsMap(mapSlice []interface{}) (newMap map[string]interface{}) {
|
func mapSliceRebuildAsMap(mapSlice []interface{}) (newMap map[string]interface{}) {
|
||||||
newMap = make(map[string]interface{})
|
newMap = make(map[string]interface{})
|
||||||
for _, item := range mapSlice {
|
|
||||||
|
mergedMapSlice := mapSliceMergeRepeatedKeys(mapSlice)
|
||||||
|
for _, item := range mergedMapSlice {
|
||||||
h := item.(map[string]interface{})
|
h := item.(map[string]interface{})
|
||||||
newMap[h["name"].(string)] = h["value"]
|
newMap[h["name"].(string)] = h["value"]
|
||||||
}
|
}
|
||||||
@@ -20,6 +23,28 @@ func mapSliceRebuildAsMap(mapSlice []interface{}) (newMap map[string]interface{}
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func mapSliceRebuildAsMergedMap(mapSlice []interface{}) (newMap map[string]interface{}) {
|
||||||
|
newMap = make(map[string]interface{})
|
||||||
|
|
||||||
|
mergedMapSlice := mapSliceMergeRepeatedKeys(mapSlice)
|
||||||
|
for _, item := range mergedMapSlice {
|
||||||
|
h := item.(map[string]interface{})
|
||||||
|
|
||||||
|
if valuesInterface, ok := h["value"].([]interface{}); ok {
|
||||||
|
var values []string
|
||||||
|
for _, valueInterface := range valuesInterface {
|
||||||
|
values = append(values, valueInterface.(string))
|
||||||
|
}
|
||||||
|
|
||||||
|
newMap[h["name"].(string)] = strings.Join(values, ",")
|
||||||
|
} else {
|
||||||
|
newMap[h["name"].(string)] = h["value"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func mapSliceMergeRepeatedKeys(mapSlice []interface{}) (newMapSlice []interface{}) {
|
func mapSliceMergeRepeatedKeys(mapSlice []interface{}) (newMapSlice []interface{}) {
|
||||||
newMapSlice = make([]interface{}, 0)
|
newMapSlice = make([]interface{}, 0)
|
||||||
valuesMap := make(map[string][]interface{})
|
valuesMap := make(map[string][]interface{})
|
||||||
@@ -47,6 +72,24 @@ func mapSliceMergeRepeatedKeys(mapSlice []interface{}) (newMapSlice []interface{
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func representMapAsTable(mapToTable map[string]interface{}, selectorPrefix string) (representation string) {
|
||||||
|
var table []api.TableData
|
||||||
|
|
||||||
|
keys := make([]string, 0, len(mapToTable))
|
||||||
|
for k := range mapToTable {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
|
||||||
|
for _, key := range keys {
|
||||||
|
table = append(table, createTableForKey(key, mapToTable[key], selectorPrefix)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
obj, _ := json.Marshal(table)
|
||||||
|
representation = string(obj)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func representMapSliceAsTable(mapSlice []interface{}, selectorPrefix string) (representation string) {
|
func representMapSliceAsTable(mapSlice []interface{}, selectorPrefix string) (representation string) {
|
||||||
var table []api.TableData
|
var table []api.TableData
|
||||||
for _, item := range mapSlice {
|
for _, item := range mapSlice {
|
||||||
@@ -54,34 +97,7 @@ func representMapSliceAsTable(mapSlice []interface{}, selectorPrefix string) (re
|
|||||||
key := h["name"].(string)
|
key := h["name"].(string)
|
||||||
value := h["value"]
|
value := h["value"]
|
||||||
|
|
||||||
var reflectKind reflect.Kind
|
table = append(table, createTableForKey(key, value, selectorPrefix)...)
|
||||||
reflectType := reflect.TypeOf(value)
|
|
||||||
if reflectType == nil {
|
|
||||||
reflectKind = reflect.Interface
|
|
||||||
} else {
|
|
||||||
reflectKind = reflect.TypeOf(value).Kind()
|
|
||||||
}
|
|
||||||
|
|
||||||
switch reflectKind {
|
|
||||||
case reflect.Slice:
|
|
||||||
fallthrough
|
|
||||||
case reflect.Array:
|
|
||||||
for i, el := range value.([]interface{}) {
|
|
||||||
selector := fmt.Sprintf("%s.%s[%d]", selectorPrefix, key, i)
|
|
||||||
table = append(table, api.TableData{
|
|
||||||
Name: fmt.Sprintf("%s [%d]", key, i),
|
|
||||||
Value: el,
|
|
||||||
Selector: selector,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
selector := fmt.Sprintf("%s[\"%s\"]", selectorPrefix, key)
|
|
||||||
table = append(table, api.TableData{
|
|
||||||
Name: key,
|
|
||||||
Value: value,
|
|
||||||
Selector: selector,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
obj, _ := json.Marshal(table)
|
obj, _ := json.Marshal(table)
|
||||||
@@ -89,6 +105,41 @@ func representMapSliceAsTable(mapSlice []interface{}, selectorPrefix string) (re
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func createTableForKey(key string, value interface{}, selectorPrefix string) []api.TableData {
|
||||||
|
var table []api.TableData
|
||||||
|
|
||||||
|
var reflectKind reflect.Kind
|
||||||
|
reflectType := reflect.TypeOf(value)
|
||||||
|
if reflectType == nil {
|
||||||
|
reflectKind = reflect.Interface
|
||||||
|
} else {
|
||||||
|
reflectKind = reflect.TypeOf(value).Kind()
|
||||||
|
}
|
||||||
|
|
||||||
|
switch reflectKind {
|
||||||
|
case reflect.Slice:
|
||||||
|
fallthrough
|
||||||
|
case reflect.Array:
|
||||||
|
for i, el := range value.([]interface{}) {
|
||||||
|
selector := fmt.Sprintf("%s.%s[%d]", selectorPrefix, key, i)
|
||||||
|
table = append(table, api.TableData{
|
||||||
|
Name: fmt.Sprintf("%s [%d]", key, i),
|
||||||
|
Value: el,
|
||||||
|
Selector: selector,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
selector := fmt.Sprintf("%s[\"%s\"]", selectorPrefix, key)
|
||||||
|
table = append(table, api.TableData{
|
||||||
|
Name: key,
|
||||||
|
Value: value,
|
||||||
|
Selector: selector,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return table
|
||||||
|
}
|
||||||
|
|
||||||
func representSliceAsTable(slice []interface{}, selectorPrefix string) (representation string) {
|
func representSliceAsTable(slice []interface{}, selectorPrefix string) (representation string) {
|
||||||
var table []api.TableData
|
var table []api.TableData
|
||||||
for i, item := range slice {
|
for i, item := range slice {
|
||||||
|
|||||||
@@ -286,19 +286,13 @@ func (d dissecting) Analyze(item *api.OutputChannelItem, resolvedSource string,
|
|||||||
reqDetails["pathSegments"] = strings.Split(path, "/")[1:]
|
reqDetails["pathSegments"] = strings.Split(path, "/")[1:]
|
||||||
|
|
||||||
// Rearrange the maps for the querying
|
// Rearrange the maps for the querying
|
||||||
reqDetails["_headers"] = reqDetails["headers"]
|
reqDetails["headers"] = mapSliceRebuildAsMergedMap(reqDetails["headers"].([]interface{}))
|
||||||
reqDetails["headers"] = mapSliceRebuildAsMap(reqDetails["_headers"].([]interface{}))
|
resDetails["headers"] = mapSliceRebuildAsMergedMap(resDetails["headers"].([]interface{}))
|
||||||
resDetails["_headers"] = resDetails["headers"]
|
|
||||||
resDetails["headers"] = mapSliceRebuildAsMap(resDetails["_headers"].([]interface{}))
|
|
||||||
|
|
||||||
reqDetails["_cookies"] = reqDetails["cookies"]
|
reqDetails["cookies"] = mapSliceRebuildAsMergedMap(reqDetails["cookies"].([]interface{}))
|
||||||
reqDetails["cookies"] = mapSliceRebuildAsMap(reqDetails["_cookies"].([]interface{}))
|
resDetails["cookies"] = mapSliceRebuildAsMergedMap(resDetails["cookies"].([]interface{}))
|
||||||
resDetails["_cookies"] = resDetails["cookies"]
|
|
||||||
resDetails["cookies"] = mapSliceRebuildAsMap(resDetails["_cookies"].([]interface{}))
|
|
||||||
|
|
||||||
reqDetails["_queryString"] = reqDetails["queryString"]
|
reqDetails["queryString"] = mapSliceRebuildAsMap(reqDetails["queryString"].([]interface{}))
|
||||||
reqDetails["_queryStringMerged"] = mapSliceMergeRepeatedKeys(reqDetails["_queryString"].([]interface{}))
|
|
||||||
reqDetails["queryString"] = mapSliceRebuildAsMap(reqDetails["_queryStringMerged"].([]interface{}))
|
|
||||||
|
|
||||||
elapsedTime := item.Pair.Response.CaptureTime.Sub(item.Pair.Request.CaptureTime).Round(time.Millisecond).Milliseconds()
|
elapsedTime := item.Pair.Response.CaptureTime.Sub(item.Pair.Request.CaptureTime).Round(time.Millisecond).Milliseconds()
|
||||||
if elapsedTime < 0 {
|
if elapsedTime < 0 {
|
||||||
@@ -397,19 +391,19 @@ func representRequest(request map[string]interface{}) (repRequest []interface{})
|
|||||||
repRequest = append(repRequest, api.SectionData{
|
repRequest = append(repRequest, api.SectionData{
|
||||||
Type: api.TABLE,
|
Type: api.TABLE,
|
||||||
Title: "Headers",
|
Title: "Headers",
|
||||||
Data: representMapSliceAsTable(request["_headers"].([]interface{}), `request.headers`),
|
Data: representMapAsTable(request["headers"].(map[string]interface{}), `request.headers`),
|
||||||
})
|
})
|
||||||
|
|
||||||
repRequest = append(repRequest, api.SectionData{
|
repRequest = append(repRequest, api.SectionData{
|
||||||
Type: api.TABLE,
|
Type: api.TABLE,
|
||||||
Title: "Cookies",
|
Title: "Cookies",
|
||||||
Data: representMapSliceAsTable(request["_cookies"].([]interface{}), `request.cookies`),
|
Data: representMapAsTable(request["cookies"].(map[string]interface{}), `request.cookies`),
|
||||||
})
|
})
|
||||||
|
|
||||||
repRequest = append(repRequest, api.SectionData{
|
repRequest = append(repRequest, api.SectionData{
|
||||||
Type: api.TABLE,
|
Type: api.TABLE,
|
||||||
Title: "Query String",
|
Title: "Query String",
|
||||||
Data: representMapSliceAsTable(request["_queryStringMerged"].([]interface{}), `request.queryString`),
|
Data: representMapAsTable(request["queryString"].(map[string]interface{}), `request.queryString`),
|
||||||
})
|
})
|
||||||
|
|
||||||
postData, _ := request["postData"].(map[string]interface{})
|
postData, _ := request["postData"].(map[string]interface{})
|
||||||
@@ -485,13 +479,13 @@ func representResponse(response map[string]interface{}) (repResponse []interface
|
|||||||
repResponse = append(repResponse, api.SectionData{
|
repResponse = append(repResponse, api.SectionData{
|
||||||
Type: api.TABLE,
|
Type: api.TABLE,
|
||||||
Title: "Headers",
|
Title: "Headers",
|
||||||
Data: representMapSliceAsTable(response["_headers"].([]interface{}), `response.headers`),
|
Data: representMapAsTable(response["headers"].(map[string]interface{}), `response.headers`),
|
||||||
})
|
})
|
||||||
|
|
||||||
repResponse = append(repResponse, api.SectionData{
|
repResponse = append(repResponse, api.SectionData{
|
||||||
Type: api.TABLE,
|
Type: api.TABLE,
|
||||||
Title: "Cookies",
|
Title: "Cookies",
|
||||||
Data: representMapSliceAsTable(response["_cookies"].([]interface{}), `response.cookies`),
|
Data: representMapAsTable(response["cookies"].(map[string]interface{}), `response.cookies`),
|
||||||
})
|
})
|
||||||
|
|
||||||
content, _ := response["content"].(map[string]interface{})
|
content, _ := response["content"].(map[string]interface{})
|
||||||
|
|||||||
@@ -1,30 +1,14 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"encoding/xml"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io/ioutil"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/beevik/etree"
|
|
||||||
"github.com/up9inc/mizu/tap/api"
|
"github.com/up9inc/mizu/tap/api"
|
||||||
)
|
)
|
||||||
|
|
||||||
const maskedFieldPlaceholderValue = "[REDACTED]"
|
|
||||||
const userAgent = "user-agent"
|
const userAgent = "user-agent"
|
||||||
|
|
||||||
//these values MUST be all lower case and contain no `-` or `_` characters
|
|
||||||
var personallyIdentifiableDataFields = []string{"token", "authorization", "authentication", "cookie", "userid", "password",
|
|
||||||
"username", "user", "key", "passcode", "pass", "auth", "authtoken", "jwt",
|
|
||||||
"bearer", "clientid", "clientsecret", "redirecturi", "phonenumber",
|
|
||||||
"zip", "zipcode", "address", "country", "firstname", "lastname",
|
|
||||||
"middlename", "fname", "lname", "birthdate"}
|
|
||||||
|
|
||||||
func IsIgnoredUserAgent(item *api.OutputChannelItem, options *api.TrafficFilteringOptions) bool {
|
func IsIgnoredUserAgent(item *api.OutputChannelItem, options *api.TrafficFilteringOptions) bool {
|
||||||
if item.Protocol.Name != "http" {
|
if item.Protocol.Name != "http" {
|
||||||
return false
|
return false
|
||||||
@@ -48,192 +32,3 @@ func IsIgnoredUserAgent(item *api.OutputChannelItem, options *api.TrafficFilteri
|
|||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func FilterSensitiveData(item *api.OutputChannelItem, options *api.TrafficFilteringOptions) {
|
|
||||||
request := item.Pair.Request.Payload.(HTTPPayload).Data.(*http.Request)
|
|
||||||
response := item.Pair.Response.Payload.(HTTPPayload).Data.(*http.Response)
|
|
||||||
|
|
||||||
filterHeaders(&request.Header)
|
|
||||||
filterHeaders(&response.Header)
|
|
||||||
filterUrl(request.URL)
|
|
||||||
filterRequestBody(request, options)
|
|
||||||
filterResponseBody(response, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterRequestBody(request *http.Request, options *api.TrafficFilteringOptions) {
|
|
||||||
contenType := getContentTypeHeaderValue(request.Header)
|
|
||||||
body, err := ioutil.ReadAll(request.Body)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
filteredBody, err := filterHttpBody(body, contenType, options)
|
|
||||||
if err == nil {
|
|
||||||
request.Body = ioutil.NopCloser(bytes.NewBuffer(filteredBody))
|
|
||||||
} else {
|
|
||||||
request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterResponseBody(response *http.Response, options *api.TrafficFilteringOptions) {
|
|
||||||
contentType := getContentTypeHeaderValue(response.Header)
|
|
||||||
body, err := ioutil.ReadAll(response.Body)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
filteredBody, err := filterHttpBody(body, contentType, options)
|
|
||||||
if err == nil {
|
|
||||||
response.Body = ioutil.NopCloser(bytes.NewBuffer(filteredBody))
|
|
||||||
} else {
|
|
||||||
response.Body = ioutil.NopCloser(bytes.NewBuffer(body))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterHeaders(headers *http.Header) {
|
|
||||||
for key := range *headers {
|
|
||||||
if strings.ToLower(key) == userAgent {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.ToLower(key) == "cookie" {
|
|
||||||
headers.Del(key)
|
|
||||||
} else if isFieldNameSensitive(key) {
|
|
||||||
headers.Set(key, maskedFieldPlaceholderValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getContentTypeHeaderValue(headers http.Header) string {
|
|
||||||
for key := range headers {
|
|
||||||
if strings.ToLower(key) == "content-type" {
|
|
||||||
return headers.Get(key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func isFieldNameSensitive(fieldName string) bool {
|
|
||||||
if fieldName == ":authority" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
name := strings.ToLower(fieldName)
|
|
||||||
name = strings.ReplaceAll(name, "_", "")
|
|
||||||
name = strings.ReplaceAll(name, "-", "")
|
|
||||||
name = strings.ReplaceAll(name, " ", "")
|
|
||||||
|
|
||||||
for _, sensitiveField := range personallyIdentifiableDataFields {
|
|
||||||
if strings.Contains(name, sensitiveField) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterHttpBody(bytes []byte, contentType string, options *api.TrafficFilteringOptions) ([]byte, error) {
|
|
||||||
mimeType := strings.Split(contentType, ";")[0]
|
|
||||||
switch strings.ToLower(mimeType) {
|
|
||||||
case "application/json":
|
|
||||||
return filterJsonBody(bytes)
|
|
||||||
case "text/html":
|
|
||||||
fallthrough
|
|
||||||
case "application/xhtml+xml":
|
|
||||||
fallthrough
|
|
||||||
case "text/xml":
|
|
||||||
fallthrough
|
|
||||||
case "application/xml":
|
|
||||||
return filterXmlEtree(bytes)
|
|
||||||
case "text/plain":
|
|
||||||
if options != nil && options.PlainTextMaskingRegexes != nil {
|
|
||||||
return filterPlainText(bytes, options), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return bytes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterPlainText(bytes []byte, options *api.TrafficFilteringOptions) []byte {
|
|
||||||
for _, regex := range options.PlainTextMaskingRegexes {
|
|
||||||
bytes = regex.ReplaceAll(bytes, []byte(maskedFieldPlaceholderValue))
|
|
||||||
}
|
|
||||||
return bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterXmlEtree(bytes []byte) ([]byte, error) {
|
|
||||||
if !IsValidXML(bytes) {
|
|
||||||
return nil, errors.New("Invalid XML")
|
|
||||||
}
|
|
||||||
xmlDoc := etree.NewDocument()
|
|
||||||
err := xmlDoc.ReadFromBytes(bytes)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
} else {
|
|
||||||
filterXmlElement(xmlDoc.Root())
|
|
||||||
}
|
|
||||||
return xmlDoc.WriteToBytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsValidXML(data []byte) bool {
|
|
||||||
return xml.Unmarshal(data, new(interface{})) == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterXmlElement(element *etree.Element) {
|
|
||||||
for i, attribute := range element.Attr {
|
|
||||||
if isFieldNameSensitive(attribute.Key) {
|
|
||||||
element.Attr[i].Value = maskedFieldPlaceholderValue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if element.ChildElements() == nil || len(element.ChildElements()) == 0 {
|
|
||||||
if isFieldNameSensitive(element.Tag) {
|
|
||||||
element.SetText(maskedFieldPlaceholderValue)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for _, element := range element.ChildElements() {
|
|
||||||
filterXmlElement(element)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterJsonBody(bytes []byte) ([]byte, error) {
|
|
||||||
var bodyJsonMap map[string]interface{}
|
|
||||||
err := json.Unmarshal(bytes, &bodyJsonMap)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
filterJsonMap(bodyJsonMap)
|
|
||||||
return json.Marshal(bodyJsonMap)
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterJsonMap(jsonMap map[string]interface{}) {
|
|
||||||
for key, value := range jsonMap {
|
|
||||||
// Do not replace nil values with maskedFieldPlaceholderValue
|
|
||||||
if value == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
nestedMap, isNested := value.(map[string]interface{})
|
|
||||||
if isNested {
|
|
||||||
filterJsonMap(nestedMap)
|
|
||||||
} else {
|
|
||||||
if isFieldNameSensitive(key) {
|
|
||||||
jsonMap[key] = maskedFieldPlaceholderValue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func filterUrl(url *url.URL) {
|
|
||||||
if len(url.RawQuery) > 0 {
|
|
||||||
newQueryArgs := make([]string, 0)
|
|
||||||
for urlQueryParamName, urlQueryParamValues := range url.Query() {
|
|
||||||
newValues := urlQueryParamValues
|
|
||||||
if isFieldNameSensitive(urlQueryParamName) {
|
|
||||||
newValues = []string{maskedFieldPlaceholderValue}
|
|
||||||
}
|
|
||||||
for _, paramValue := range newValues {
|
|
||||||
newQueryArgs = append(newQueryArgs, fmt.Sprintf("%s=%s", urlQueryParamName, paramValue))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
url.RawQuery = strings.Join(newQueryArgs, "&")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ docker build -t mizu-ebpf-builder . || exit 1
|
|||||||
BPF_TARGET=amd64
|
BPF_TARGET=amd64
|
||||||
BPF_CFLAGS="-O2 -g -D__TARGET_ARCH_x86"
|
BPF_CFLAGS="-O2 -g -D__TARGET_ARCH_x86"
|
||||||
ARCH=$(uname -m)
|
ARCH=$(uname -m)
|
||||||
if [[ $ARCH == "aarch64" ]]; then
|
if [[ $ARCH == "aarch64" || $ARCH == "arm64" ]]; then
|
||||||
BPF_TARGET=arm64
|
BPF_TARGET=arm64
|
||||||
BPF_CFLAGS="-O2 -g -D__TARGET_ARCH_arm64"
|
BPF_CFLAGS="-O2 -g -D__TARGET_ARCH_arm64"
|
||||||
fi
|
fi
|
||||||
@@ -18,7 +18,7 @@ docker run --rm \
|
|||||||
--name mizu-ebpf-builder \
|
--name mizu-ebpf-builder \
|
||||||
-v $MIZU_HOME:/mizu \
|
-v $MIZU_HOME:/mizu \
|
||||||
-v $(go env GOPATH):/root/go \
|
-v $(go env GOPATH):/root/go \
|
||||||
-it mizu-ebpf-builder \
|
mizu-ebpf-builder \
|
||||||
sh -c "
|
sh -c "
|
||||||
BPF_TARGET=\"$BPF_TARGET\" BPF_CFLAGS=\"$BPF_CFLAGS\" go generate tap/tlstapper/tls_tapper.go
|
BPF_TARGET=\"$BPF_TARGET\" BPF_CFLAGS=\"$BPF_CFLAGS\" go generate tap/tlstapper/tls_tapper.go
|
||||||
chown $(id -u):$(id -g) tap/tlstapper/tlstapper*_bpf*
|
chown $(id -u):$(id -g) tap/tlstapper/tlstapper*_bpf*
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ Copyright (C) UP9 Inc.
|
|||||||
#include "include/common.h"
|
#include "include/common.h"
|
||||||
|
|
||||||
|
|
||||||
static __always_inline int add_address_to_chunk(struct pt_regs *ctx, struct tls_chunk* chunk, __u64 id, __u32 fd) {
|
static __always_inline int add_address_to_chunk(struct pt_regs *ctx, struct tls_chunk* chunk, __u64 id, __u32 fd, struct ssl_info* info) {
|
||||||
__u32 pid = id >> 32;
|
__u32 pid = id >> 32;
|
||||||
__u64 key = (__u64) pid << 32 | fd;
|
__u64 key = (__u64) pid << 32 | fd;
|
||||||
|
|
||||||
@@ -22,14 +22,29 @@ static __always_inline int add_address_to_chunk(struct pt_regs *ctx, struct tls_
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int err = bpf_probe_read(chunk->address, sizeof(chunk->address), fdinfo->ipv4_addr);
|
int err;
|
||||||
chunk->flags |= (fdinfo->flags & FLAGS_IS_CLIENT_BIT);
|
|
||||||
|
|
||||||
if (err != 0) {
|
switch (info->address_info.mode) {
|
||||||
log_error(ctx, LOG_ERROR_READING_FD_ADDRESS, id, err, 0l);
|
case ADDRESS_INFO_MODE_UNDEFINED:
|
||||||
return 0;
|
chunk->address_info.mode = ADDRESS_INFO_MODE_SINGLE;
|
||||||
|
err = bpf_probe_read(&chunk->address_info.sport, sizeof(chunk->address_info.sport), &fdinfo->ipv4_addr[2]);
|
||||||
|
if (err != 0) {
|
||||||
|
log_error(ctx, LOG_ERROR_READING_FD_ADDRESS, id, err, 0l);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
err = bpf_probe_read(&chunk->address_info.saddr, sizeof(chunk->address_info.saddr), &fdinfo->ipv4_addr[4]);
|
||||||
|
if (err != 0) {
|
||||||
|
log_error(ctx, LOG_ERROR_READING_FD_ADDRESS, id, err, 0l);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
bpf_probe_read(&chunk->address_info, sizeof(chunk->address_info), &info->address_info);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
chunk->flags |= (fdinfo->flags & FLAGS_IS_CLIENT_BIT);
|
||||||
|
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,7 +119,7 @@ static __always_inline void output_ssl_chunk(struct pt_regs *ctx, struct ssl_inf
|
|||||||
chunk->len = count_bytes;
|
chunk->len = count_bytes;
|
||||||
chunk->fd = info->fd;
|
chunk->fd = info->fd;
|
||||||
|
|
||||||
if (!add_address_to_chunk(ctx, chunk, id, chunk->fd)) {
|
if (!add_address_to_chunk(ctx, chunk, id, chunk->fd, info)) {
|
||||||
// Without an address, we drop the chunk because there is not much to do with it in Go
|
// Without an address, we drop the chunk because there is not much to do with it in Go
|
||||||
//
|
//
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -7,9 +7,11 @@ Copyright (C) UP9 Inc.
|
|||||||
#ifndef __COMMON__
|
#ifndef __COMMON__
|
||||||
#define __COMMON__
|
#define __COMMON__
|
||||||
|
|
||||||
|
#define AF_INET 2 /* Internet IP Protocol */
|
||||||
|
|
||||||
const __s32 invalid_fd = -1;
|
const __s32 invalid_fd = -1;
|
||||||
|
|
||||||
static int add_address_to_chunk(struct pt_regs *ctx, struct tls_chunk* chunk, __u64 id, __u32 fd);
|
static int add_address_to_chunk(struct pt_regs *ctx, struct tls_chunk* chunk, __u64 id, __u32 fd, struct ssl_info* info);
|
||||||
static void send_chunk_part(struct pt_regs *ctx, __u8* buffer, __u64 id, struct tls_chunk* chunk, int start, int end);
|
static void send_chunk_part(struct pt_regs *ctx, __u8* buffer, __u64 id, struct tls_chunk* chunk, int start, int end);
|
||||||
static void send_chunk(struct pt_regs *ctx, __u8* buffer, __u64 id, struct tls_chunk* chunk);
|
static void send_chunk(struct pt_regs *ctx, __u8* buffer, __u64 id, struct tls_chunk* chunk);
|
||||||
static void output_ssl_chunk(struct pt_regs *ctx, struct ssl_info* info, int count_bytes, __u64 id, __u32 flags);
|
static void output_ssl_chunk(struct pt_regs *ctx, struct ssl_info* info, int count_bytes, __u64 id, __u32 flags);
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ Copyright (C) UP9 Inc.
|
|||||||
|
|
||||||
#include "legacy_kernel.h"
|
#include "legacy_kernel.h"
|
||||||
|
|
||||||
|
#include <bpf/bpf_endian.h>
|
||||||
#include <bpf/bpf_helpers.h>
|
#include <bpf/bpf_helpers.h>
|
||||||
#include <bpf/bpf_tracing.h>
|
#include <bpf/bpf_tracing.h>
|
||||||
#include <bpf/bpf_core_read.h>
|
#include <bpf/bpf_core_read.h>
|
||||||
|
|||||||
@@ -26,6 +26,11 @@ Copyright (C) UP9 Inc.
|
|||||||
#define LOG_ERROR_PUTTING_CONNECT_INFO (14)
|
#define LOG_ERROR_PUTTING_CONNECT_INFO (14)
|
||||||
#define LOG_ERROR_GETTING_CONNECT_INFO (15)
|
#define LOG_ERROR_GETTING_CONNECT_INFO (15)
|
||||||
#define LOG_ERROR_READING_CONNECT_INFO (16)
|
#define LOG_ERROR_READING_CONNECT_INFO (16)
|
||||||
|
#define LOG_ERROR_READING_SOCKET_FAMILY (17)
|
||||||
|
#define LOG_ERROR_READING_SOCKET_DADDR (18)
|
||||||
|
#define LOG_ERROR_READING_SOCKET_SADDR (19)
|
||||||
|
#define LOG_ERROR_READING_SOCKET_DPORT (20)
|
||||||
|
#define LOG_ERROR_READING_SOCKET_SPORT (21)
|
||||||
|
|
||||||
// Sometimes we have the same error, happening from different locations.
|
// Sometimes we have the same error, happening from different locations.
|
||||||
// in order to be able to distinct between them in the log, we add an
|
// in order to be able to distinct between them in the log, we add an
|
||||||
|
|||||||
@@ -24,6 +24,21 @@ Copyright (C) UP9 Inc.
|
|||||||
//
|
//
|
||||||
// Be careful when editing, alignment and padding should be exactly the same in go/c.
|
// Be careful when editing, alignment and padding should be exactly the same in go/c.
|
||||||
//
|
//
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
ADDRESS_INFO_MODE_UNDEFINED,
|
||||||
|
ADDRESS_INFO_MODE_SINGLE,
|
||||||
|
ADDRESS_INFO_MODE_PAIR,
|
||||||
|
} address_info_mode;
|
||||||
|
|
||||||
|
struct address_info {
|
||||||
|
address_info_mode mode;
|
||||||
|
__be32 saddr;
|
||||||
|
__be32 daddr;
|
||||||
|
__be16 sport;
|
||||||
|
__be16 dport;
|
||||||
|
};
|
||||||
|
|
||||||
struct tls_chunk {
|
struct tls_chunk {
|
||||||
__u32 pid;
|
__u32 pid;
|
||||||
__u32 tgid;
|
__u32 tgid;
|
||||||
@@ -32,7 +47,7 @@ struct tls_chunk {
|
|||||||
__u32 recorded;
|
__u32 recorded;
|
||||||
__u32 fd;
|
__u32 fd;
|
||||||
__u32 flags;
|
__u32 flags;
|
||||||
__u8 address[16];
|
struct address_info address_info;
|
||||||
__u8 data[CHUNK_SIZE]; // Must be N^2
|
__u8 data[CHUNK_SIZE]; // Must be N^2
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -41,6 +56,7 @@ struct ssl_info {
|
|||||||
__u32 buffer_len;
|
__u32 buffer_len;
|
||||||
__u32 fd;
|
__u32 fd;
|
||||||
__u64 created_at_nano;
|
__u64 created_at_nano;
|
||||||
|
struct address_info address_info;
|
||||||
|
|
||||||
// for ssl_write and ssl_read must be zero
|
// for ssl_write and ssl_read must be zero
|
||||||
// for ssl_write_ex and ssl_read_ex save the *written/*readbytes pointer.
|
// for ssl_write_ex and ssl_read_ex save the *written/*readbytes pointer.
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ static __always_inline int get_count_bytes(struct pt_regs *ctx, struct ssl_info*
|
|||||||
}
|
}
|
||||||
|
|
||||||
static __always_inline void ssl_uprobe(struct pt_regs *ctx, void* ssl, void* buffer, int num, struct bpf_map_def* map_fd, size_t *count_ptr) {
|
static __always_inline void ssl_uprobe(struct pt_regs *ctx, void* ssl, void* buffer, int num, struct bpf_map_def* map_fd, size_t *count_ptr) {
|
||||||
|
long err;
|
||||||
|
|
||||||
__u64 id = bpf_get_current_pid_tgid();
|
__u64 id = bpf_get_current_pid_tgid();
|
||||||
|
|
||||||
if (!should_tap(id >> 32)) {
|
if (!should_tap(id >> 32)) {
|
||||||
@@ -53,7 +55,7 @@ static __always_inline void ssl_uprobe(struct pt_regs *ctx, void* ssl, void* buf
|
|||||||
info.count_ptr = count_ptr;
|
info.count_ptr = count_ptr;
|
||||||
info.buffer = buffer;
|
info.buffer = buffer;
|
||||||
|
|
||||||
long err = bpf_map_update_elem(map_fd, &id, &info, BPF_ANY);
|
err = bpf_map_update_elem(map_fd, &id, &info, BPF_ANY);
|
||||||
|
|
||||||
if (err != 0) {
|
if (err != 0) {
|
||||||
log_error(ctx, LOG_ERROR_PUTTING_SSL_CONTEXT, id, err, 0l);
|
log_error(ctx, LOG_ERROR_PUTTING_SSL_CONTEXT, id, err, 0l);
|
||||||
@@ -66,7 +68,7 @@ static __always_inline void ssl_uretprobe(struct pt_regs *ctx, struct bpf_map_de
|
|||||||
if (!should_tap(id >> 32)) {
|
if (!should_tap(id >> 32)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ssl_info *infoPtr = bpf_map_lookup_elem(map_fd, &id);
|
struct ssl_info *infoPtr = bpf_map_lookup_elem(map_fd, &id);
|
||||||
|
|
||||||
if (infoPtr == NULL) {
|
if (infoPtr == NULL) {
|
||||||
@@ -99,10 +101,10 @@ static __always_inline void ssl_uretprobe(struct pt_regs *ctx, struct bpf_map_de
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
int count_bytes = get_count_bytes(ctx, &info, id);
|
int count_bytes = get_count_bytes(ctx, &info, id);
|
||||||
if (count_bytes <= 0) {
|
if (count_bytes <= 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
output_ssl_chunk(ctx, &info, count_bytes, id, flags);
|
output_ssl_chunk(ctx, &info, count_bytes, id, flags);
|
||||||
}
|
}
|
||||||
|
|||||||
79
tap/tlstapper/bpf/tcp_kprobes.c
Normal file
79
tap/tlstapper/bpf/tcp_kprobes.c
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
#include "include/headers.h"
|
||||||
|
#include "include/maps.h"
|
||||||
|
#include "include/log.h"
|
||||||
|
#include "include/logger_messages.h"
|
||||||
|
#include "include/pids.h"
|
||||||
|
#include "include/common.h"
|
||||||
|
|
||||||
|
static __always_inline void tcp_kprobe(struct pt_regs *ctx, struct bpf_map_def *map_fd, _Bool is_send) {
|
||||||
|
long err;
|
||||||
|
|
||||||
|
__u64 id = bpf_get_current_pid_tgid();
|
||||||
|
__u32 pid = id >> 32;
|
||||||
|
|
||||||
|
if (!should_tap(id >> 32)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ssl_info *info_ptr = bpf_map_lookup_elem(map_fd, &id);
|
||||||
|
// Happens when the connection is not tls
|
||||||
|
if (info_ptr == NULL) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct sock *sk = (struct sock *) PT_REGS_PARM1(ctx);
|
||||||
|
|
||||||
|
short unsigned int family;
|
||||||
|
err = bpf_probe_read(&family, sizeof(family), (void *)&sk->__sk_common.skc_family);
|
||||||
|
if (err != 0) {
|
||||||
|
log_error(ctx, LOG_ERROR_READING_SOCKET_FAMILY, id, err, 0l);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (family != AF_INET) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// daddr, saddr and dport are in network byte order (big endian)
|
||||||
|
// sport is in host byte order
|
||||||
|
__be32 saddr;
|
||||||
|
__be32 daddr;
|
||||||
|
__be16 dport;
|
||||||
|
__u16 sport;
|
||||||
|
|
||||||
|
err = bpf_probe_read(&saddr, sizeof(saddr), (void *)&sk->__sk_common.skc_rcv_saddr);
|
||||||
|
if (err != 0) {
|
||||||
|
log_error(ctx, LOG_ERROR_READING_SOCKET_SADDR, id, err, 0l);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
err = bpf_probe_read(&daddr, sizeof(daddr), (void *)&sk->__sk_common.skc_daddr);
|
||||||
|
if (err != 0) {
|
||||||
|
log_error(ctx, LOG_ERROR_READING_SOCKET_DADDR, id, err, 0l);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
err = bpf_probe_read(&dport, sizeof(dport), (void *)&sk->__sk_common.skc_dport);
|
||||||
|
if (err != 0) {
|
||||||
|
log_error(ctx, LOG_ERROR_READING_SOCKET_DPORT, id, err, 0l);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
err = bpf_probe_read(&sport, sizeof(sport), (void *)&sk->__sk_common.skc_num);
|
||||||
|
if (err != 0) {
|
||||||
|
log_error(ctx, LOG_ERROR_READING_SOCKET_SPORT, id, err, 0l);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
info_ptr->address_info.mode = ADDRESS_INFO_MODE_PAIR;
|
||||||
|
info_ptr->address_info.daddr = daddr;
|
||||||
|
info_ptr->address_info.saddr = saddr;
|
||||||
|
info_ptr->address_info.dport = dport;
|
||||||
|
info_ptr->address_info.sport = bpf_htons(sport);
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("kprobe/tcp_sendmsg")
|
||||||
|
void BPF_KPROBE(tcp_sendmsg) {
|
||||||
|
tcp_kprobe(ctx, &openssl_write_context, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("kprobe/tcp_recvmsg")
|
||||||
|
void BPF_KPROBE(tcp_recvmsg) {
|
||||||
|
tcp_kprobe(ctx, &openssl_read_context, false);
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ Copyright (C) UP9 Inc.
|
|||||||
//
|
//
|
||||||
#include "common.c"
|
#include "common.c"
|
||||||
#include "openssl_uprobes.c"
|
#include "openssl_uprobes.c"
|
||||||
|
#include "tcp_kprobes.c"
|
||||||
#include "go_uprobes.c"
|
#include "go_uprobes.c"
|
||||||
#include "fd_tracepoints.c"
|
#include "fd_tracepoints.c"
|
||||||
#include "fd_to_address_tracepoints.c"
|
#include "fd_to_address_tracepoints.c"
|
||||||
|
|||||||
@@ -20,4 +20,9 @@ var bpfLogMessages = []string{
|
|||||||
/*0014*/ "[%d] Unable to put connect info [err: %d]",
|
/*0014*/ "[%d] Unable to put connect info [err: %d]",
|
||||||
/*0015*/ "[%d] Unable to get connect info",
|
/*0015*/ "[%d] Unable to get connect info",
|
||||||
/*0016*/ "[%d] Unable to read connect info [err: %d]",
|
/*0016*/ "[%d] Unable to read connect info [err: %d]",
|
||||||
|
/*0017*/ "[%d] Unable to read socket family [err: %d]",
|
||||||
|
/*0018*/ "[%d] Unable to read socket daddr [err: %d]",
|
||||||
|
/*0019*/ "[%d] Unable to read socket saddr [err: %d]",
|
||||||
|
/*0019*/ "[%d] Unable to read socket dport [err: %d]",
|
||||||
|
/*0021*/ "[%d] Unable to read socket sport [err: %d]",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,33 @@
|
|||||||
package tlstapper
|
package tlstapper
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"net"
|
"net"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
"github.com/go-errors/errors"
|
|
||||||
"github.com/up9inc/mizu/tap/api"
|
"github.com/up9inc/mizu/tap/api"
|
||||||
)
|
)
|
||||||
|
|
||||||
const FlagsIsClientBit uint32 = 1 << 0
|
const FlagsIsClientBit uint32 = 1 << 0
|
||||||
const FlagsIsReadBit uint32 = 1 << 1
|
const FlagsIsReadBit uint32 = 1 << 1
|
||||||
|
const (
|
||||||
|
addressInfoModeUndefined = iota
|
||||||
|
addressInfoModeSingle
|
||||||
|
addressInfoModePair
|
||||||
|
)
|
||||||
|
|
||||||
func (c *tlsTapperTlsChunk) getAddress() (net.IP, uint16, error) {
|
func (c *tlsTapperTlsChunk) getSrcAddress() (net.IP, uint16) {
|
||||||
address := bytes.NewReader(c.Address[:])
|
ip := intToIP(c.AddressInfo.Saddr)
|
||||||
var family uint16
|
port := ntohs(c.AddressInfo.Sport)
|
||||||
var port uint16
|
|
||||||
var ip32 uint32
|
|
||||||
|
|
||||||
if err := binary.Read(address, binary.BigEndian, &family); err != nil {
|
return ip, port
|
||||||
return nil, 0, errors.Wrap(err, 0)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if err := binary.Read(address, binary.BigEndian, &port); err != nil {
|
func (c *tlsTapperTlsChunk) getDstAddress() (net.IP, uint16) {
|
||||||
return nil, 0, errors.Wrap(err, 0)
|
ip := intToIP(c.AddressInfo.Daddr)
|
||||||
}
|
port := ntohs(c.AddressInfo.Dport)
|
||||||
|
|
||||||
if err := binary.Read(address, binary.BigEndian, &ip32); err != nil {
|
return ip, port
|
||||||
return nil, 0, errors.Wrap(err, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
ip := net.IP{uint8(ip32 >> 24), uint8(ip32 >> 16), uint8(ip32 >> 8), uint8(ip32)}
|
|
||||||
|
|
||||||
return ip, port, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *tlsTapperTlsChunk) isClient() bool {
|
func (c *tlsTapperTlsChunk) isClient() bool {
|
||||||
@@ -59,26 +54,54 @@ func (c *tlsTapperTlsChunk) isRequest() bool {
|
|||||||
return (c.isClient() && c.isWrite()) || (c.isServer() && c.isRead())
|
return (c.isClient() && c.isWrite()) || (c.isServer() && c.isRead())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *tlsTapperTlsChunk) getAddressPair() (addressPair, error) {
|
func (c *tlsTapperTlsChunk) getAddressPair() (addressPair, bool) {
|
||||||
ip, port, err := c.getAddress()
|
var (
|
||||||
|
srcIp, dstIp net.IP
|
||||||
|
srcPort, dstPort uint16
|
||||||
|
full bool
|
||||||
|
)
|
||||||
|
|
||||||
if err != nil {
|
switch c.AddressInfo.Mode {
|
||||||
return addressPair{}, err
|
case addressInfoModeSingle:
|
||||||
|
if c.isRequest() {
|
||||||
|
srcIp, srcPort = api.UnknownIp, api.UnknownPort
|
||||||
|
dstIp, dstPort = c.getSrcAddress()
|
||||||
|
} else {
|
||||||
|
srcIp, srcPort = c.getSrcAddress()
|
||||||
|
dstIp, dstPort = api.UnknownIp, api.UnknownPort
|
||||||
|
}
|
||||||
|
full = false
|
||||||
|
case addressInfoModePair:
|
||||||
|
if c.isRequest() {
|
||||||
|
srcIp, srcPort = c.getSrcAddress()
|
||||||
|
dstIp, dstPort = c.getDstAddress()
|
||||||
|
} else {
|
||||||
|
srcIp, srcPort = c.getDstAddress()
|
||||||
|
dstIp, dstPort = c.getSrcAddress()
|
||||||
|
}
|
||||||
|
full = true
|
||||||
|
case addressInfoModeUndefined:
|
||||||
|
srcIp, srcPort = api.UnknownIp, api.UnknownPort
|
||||||
|
dstIp, dstPort = api.UnknownIp, api.UnknownPort
|
||||||
|
full = false
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.isRequest() {
|
return addressPair{
|
||||||
return addressPair{
|
srcIp: srcIp,
|
||||||
srcIp: api.UnknownIp,
|
srcPort: srcPort,
|
||||||
srcPort: api.UnknownPort,
|
dstIp: dstIp,
|
||||||
dstIp: ip,
|
dstPort: dstPort,
|
||||||
dstPort: port,
|
}, full
|
||||||
}, nil
|
}
|
||||||
} else {
|
|
||||||
return addressPair{
|
// intToIP converts IPv4 number to net.IP
|
||||||
srcIp: ip,
|
func intToIP(ip32be uint32) net.IP {
|
||||||
srcPort: port,
|
return net.IPv4(uint8(ip32be), uint8(ip32be>>8), uint8(ip32be>>16), uint8(ip32be>>24))
|
||||||
dstIp: api.UnknownIp,
|
}
|
||||||
dstPort: api.UnknownPort,
|
|
||||||
}, nil
|
// ntohs converts big endian (network byte order) to little endian (assuming that's the host byte order)
|
||||||
}
|
func ntohs(i16be uint16) uint16 {
|
||||||
|
b := make([]byte, 2)
|
||||||
|
binary.BigEndian.PutUint16(b, i16be)
|
||||||
|
return *(*uint16)(unsafe.Pointer(&b[0]))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ type sslHooks struct {
|
|||||||
sslWriteExRetProbe link.Link
|
sslWriteExRetProbe link.Link
|
||||||
sslReadExProbe link.Link
|
sslReadExProbe link.Link
|
||||||
sslReadExRetProbe link.Link
|
sslReadExRetProbe link.Link
|
||||||
|
tcpSendmsg link.Link
|
||||||
|
tcpRecvmsg link.Link
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *sslHooks) installUprobes(bpfObjects *tlsTapperObjects, sslLibraryPath string) error {
|
func (s *sslHooks) installUprobes(bpfObjects *tlsTapperObjects, sslLibraryPath string) error {
|
||||||
@@ -103,6 +105,16 @@ func (s *sslHooks) installSslHooks(bpfObjects *tlsTapperObjects, sslLibrary *lin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
s.tcpSendmsg, err = link.Kprobe("tcp_sendmsg", bpfObjects.TcpSendmsg, nil)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
s.tcpRecvmsg, err = link.Kprobe("tcp_recvmsg", bpfObjects.TcpRecvmsg, nil)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, 0)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,5 +161,17 @@ func (s *sslHooks) close() []error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if s.tcpSendmsg != nil {
|
||||||
|
if err := s.tcpSendmsg.Close(); err != nil {
|
||||||
|
returnValue = append(returnValue, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.tcpRecvmsg != nil {
|
||||||
|
if err := s.tcpRecvmsg.Close(); err != nil {
|
||||||
|
returnValue = append(returnValue, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return returnValue
|
return returnValue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -134,14 +134,9 @@ func (p *tlsPoller) pollChunksPerfBuffer(chunks chan<- *tlsTapperTlsChunk) {
|
|||||||
|
|
||||||
func (p *tlsPoller) handleTlsChunk(chunk *tlsTapperTlsChunk, extension *api.Extension, emitter api.Emitter,
|
func (p *tlsPoller) handleTlsChunk(chunk *tlsTapperTlsChunk, extension *api.Extension, emitter api.Emitter,
|
||||||
options *api.TrafficFilteringOptions, streamsMap api.TcpStreamMap) error {
|
options *api.TrafficFilteringOptions, streamsMap api.TcpStreamMap) error {
|
||||||
address, err := p.getSockfdAddressPair(chunk)
|
address, err := p.getAddressPair(chunk)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
address, err = chunk.getAddressPair()
|
return err
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
key := buildTlsKey(address)
|
key := buildTlsKey(address)
|
||||||
@@ -161,6 +156,22 @@ func (p *tlsPoller) handleTlsChunk(chunk *tlsTapperTlsChunk, extension *api.Exte
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *tlsPoller) getAddressPair(chunk *tlsTapperTlsChunk) (addressPair, error) {
|
||||||
|
addrPairFromChunk, full := chunk.getAddressPair()
|
||||||
|
if full {
|
||||||
|
return addrPairFromChunk, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
addrPairFromSockfd, err := p.getSockfdAddressPair(chunk)
|
||||||
|
if err == nil {
|
||||||
|
return addrPairFromSockfd, nil
|
||||||
|
} else {
|
||||||
|
logger.Log.Error("failed to get address from sock fd:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return addrPairFromChunk, err
|
||||||
|
}
|
||||||
|
|
||||||
func (p *tlsPoller) startNewTlsReader(chunk *tlsTapperTlsChunk, address *addressPair, key string,
|
func (p *tlsPoller) startNewTlsReader(chunk *tlsTapperTlsChunk, address *addressPair, key string,
|
||||||
emitter api.Emitter, extension *api.Extension, options *api.TrafficFilteringOptions,
|
emitter api.Emitter, extension *api.Extension, options *api.TrafficFilteringOptions,
|
||||||
streamsMap api.TcpStreamMap) *tlsReader {
|
streamsMap api.TcpStreamMap) *tlsReader {
|
||||||
|
|||||||
@@ -19,15 +19,21 @@ type tlsTapper46GoidOffsets struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type tlsTapper46TlsChunk struct {
|
type tlsTapper46TlsChunk struct {
|
||||||
Pid uint32
|
Pid uint32
|
||||||
Tgid uint32
|
Tgid uint32
|
||||||
Len uint32
|
Len uint32
|
||||||
Start uint32
|
Start uint32
|
||||||
Recorded uint32
|
Recorded uint32
|
||||||
Fd uint32
|
Fd uint32
|
||||||
Flags uint32
|
Flags uint32
|
||||||
Address [16]uint8
|
AddressInfo struct {
|
||||||
Data [4096]uint8
|
Mode int32
|
||||||
|
Saddr uint32
|
||||||
|
Daddr uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
Data [4096]uint8
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadTlsTapper46 returns the embedded CollectionSpec for tlsTapper46.
|
// loadTlsTapper46 returns the embedded CollectionSpec for tlsTapper46.
|
||||||
@@ -93,6 +99,8 @@ type tlsTapper46ProgramSpecs struct {
|
|||||||
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.ProgramSpec `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.ProgramSpec `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// tlsTapper46MapSpecs contains maps before they are loaded into the kernel.
|
// tlsTapper46MapSpecs contains maps before they are loaded into the kernel.
|
||||||
@@ -189,6 +197,8 @@ type tlsTapper46Programs struct {
|
|||||||
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.Program `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.Program `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *tlsTapper46Programs) Close() error {
|
func (p *tlsTapper46Programs) Close() error {
|
||||||
@@ -215,6 +225,8 @@ func (p *tlsTapper46Programs) Close() error {
|
|||||||
p.SysEnterWrite,
|
p.SysEnterWrite,
|
||||||
p.SysExitAccept4,
|
p.SysExitAccept4,
|
||||||
p.SysExitConnect,
|
p.SysExitConnect,
|
||||||
|
p.TcpRecvmsg,
|
||||||
|
p.TcpSendmsg,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -19,15 +19,21 @@ type tlsTapper46GoidOffsets struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type tlsTapper46TlsChunk struct {
|
type tlsTapper46TlsChunk struct {
|
||||||
Pid uint32
|
Pid uint32
|
||||||
Tgid uint32
|
Tgid uint32
|
||||||
Len uint32
|
Len uint32
|
||||||
Start uint32
|
Start uint32
|
||||||
Recorded uint32
|
Recorded uint32
|
||||||
Fd uint32
|
Fd uint32
|
||||||
Flags uint32
|
Flags uint32
|
||||||
Address [16]uint8
|
AddressInfo struct {
|
||||||
Data [4096]uint8
|
Mode int32
|
||||||
|
Saddr uint32
|
||||||
|
Daddr uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
Data [4096]uint8
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadTlsTapper46 returns the embedded CollectionSpec for tlsTapper46.
|
// loadTlsTapper46 returns the embedded CollectionSpec for tlsTapper46.
|
||||||
@@ -93,6 +99,8 @@ type tlsTapper46ProgramSpecs struct {
|
|||||||
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.ProgramSpec `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.ProgramSpec `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// tlsTapper46MapSpecs contains maps before they are loaded into the kernel.
|
// tlsTapper46MapSpecs contains maps before they are loaded into the kernel.
|
||||||
@@ -189,6 +197,8 @@ type tlsTapper46Programs struct {
|
|||||||
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.Program `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.Program `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *tlsTapper46Programs) Close() error {
|
func (p *tlsTapper46Programs) Close() error {
|
||||||
@@ -215,6 +225,8 @@ func (p *tlsTapper46Programs) Close() error {
|
|||||||
p.SysEnterWrite,
|
p.SysEnterWrite,
|
||||||
p.SysExitAccept4,
|
p.SysExitAccept4,
|
||||||
p.SysExitConnect,
|
p.SysExitConnect,
|
||||||
|
p.TcpRecvmsg,
|
||||||
|
p.TcpSendmsg,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -19,15 +19,21 @@ type tlsTapperGoidOffsets struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type tlsTapperTlsChunk struct {
|
type tlsTapperTlsChunk struct {
|
||||||
Pid uint32
|
Pid uint32
|
||||||
Tgid uint32
|
Tgid uint32
|
||||||
Len uint32
|
Len uint32
|
||||||
Start uint32
|
Start uint32
|
||||||
Recorded uint32
|
Recorded uint32
|
||||||
Fd uint32
|
Fd uint32
|
||||||
Flags uint32
|
Flags uint32
|
||||||
Address [16]uint8
|
AddressInfo struct {
|
||||||
Data [4096]uint8
|
Mode int32
|
||||||
|
Saddr uint32
|
||||||
|
Daddr uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
Data [4096]uint8
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadTlsTapper returns the embedded CollectionSpec for tlsTapper.
|
// loadTlsTapper returns the embedded CollectionSpec for tlsTapper.
|
||||||
@@ -93,6 +99,8 @@ type tlsTapperProgramSpecs struct {
|
|||||||
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.ProgramSpec `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.ProgramSpec `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// tlsTapperMapSpecs contains maps before they are loaded into the kernel.
|
// tlsTapperMapSpecs contains maps before they are loaded into the kernel.
|
||||||
@@ -189,6 +197,8 @@ type tlsTapperPrograms struct {
|
|||||||
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.Program `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.Program `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *tlsTapperPrograms) Close() error {
|
func (p *tlsTapperPrograms) Close() error {
|
||||||
@@ -215,6 +225,8 @@ func (p *tlsTapperPrograms) Close() error {
|
|||||||
p.SysEnterWrite,
|
p.SysEnterWrite,
|
||||||
p.SysExitAccept4,
|
p.SysExitAccept4,
|
||||||
p.SysExitConnect,
|
p.SysExitConnect,
|
||||||
|
p.TcpRecvmsg,
|
||||||
|
p.TcpSendmsg,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -19,15 +19,21 @@ type tlsTapperGoidOffsets struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type tlsTapperTlsChunk struct {
|
type tlsTapperTlsChunk struct {
|
||||||
Pid uint32
|
Pid uint32
|
||||||
Tgid uint32
|
Tgid uint32
|
||||||
Len uint32
|
Len uint32
|
||||||
Start uint32
|
Start uint32
|
||||||
Recorded uint32
|
Recorded uint32
|
||||||
Fd uint32
|
Fd uint32
|
||||||
Flags uint32
|
Flags uint32
|
||||||
Address [16]uint8
|
AddressInfo struct {
|
||||||
Data [4096]uint8
|
Mode int32
|
||||||
|
Saddr uint32
|
||||||
|
Daddr uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
Data [4096]uint8
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadTlsTapper returns the embedded CollectionSpec for tlsTapper.
|
// loadTlsTapper returns the embedded CollectionSpec for tlsTapper.
|
||||||
@@ -93,6 +99,8 @@ type tlsTapperProgramSpecs struct {
|
|||||||
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.ProgramSpec `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.ProgramSpec `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.ProgramSpec `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.ProgramSpec `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.ProgramSpec `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// tlsTapperMapSpecs contains maps before they are loaded into the kernel.
|
// tlsTapperMapSpecs contains maps before they are loaded into the kernel.
|
||||||
@@ -189,6 +197,8 @@ type tlsTapperPrograms struct {
|
|||||||
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
SysEnterWrite *ebpf.Program `ebpf:"sys_enter_write"`
|
||||||
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
SysExitAccept4 *ebpf.Program `ebpf:"sys_exit_accept4"`
|
||||||
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
SysExitConnect *ebpf.Program `ebpf:"sys_exit_connect"`
|
||||||
|
TcpRecvmsg *ebpf.Program `ebpf:"tcp_recvmsg"`
|
||||||
|
TcpSendmsg *ebpf.Program `ebpf:"tcp_sendmsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *tlsTapperPrograms) Close() error {
|
func (p *tlsTapperPrograms) Close() error {
|
||||||
@@ -215,6 +225,8 @@ func (p *tlsTapperPrograms) Close() error {
|
|||||||
p.SysEnterWrite,
|
p.SysEnterWrite,
|
||||||
p.SysExitAccept4,
|
p.SysExitAccept4,
|
||||||
p.SysExitConnect,
|
p.SysExitConnect,
|
||||||
|
p.TcpRecvmsg,
|
||||||
|
p.TcpSendmsg,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
2840
ui-common/package-lock.json
generated
2840
ui-common/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -26,14 +26,15 @@
|
|||||||
"@craco/craco": "^6.4.3",
|
"@craco/craco": "^6.4.3",
|
||||||
"@types/jest": "^26.0.24",
|
"@types/jest": "^26.0.24",
|
||||||
"@types/node": "^12.20.54",
|
"@types/node": "^12.20.54",
|
||||||
"sass": "^1.52.3",
|
|
||||||
"react": "^17.0.2",
|
"react": "^17.0.2",
|
||||||
"react-copy-to-clipboard": "^5.1.0",
|
"react-copy-to-clipboard": "^5.1.0",
|
||||||
"react-dom": "^17.0.2",
|
"react-dom": "^17.0.2",
|
||||||
"recoil": "^0.7.2"
|
"recoil": "^0.7.2",
|
||||||
|
"sass": "^1.52.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@craco/craco": "^6.4.3",
|
"@craco/craco": "^6.4.3",
|
||||||
|
"@elastic/eui": "^60.2.0",
|
||||||
"@emotion/react": "^11.9.0",
|
"@emotion/react": "^11.9.0",
|
||||||
"@emotion/styled": "^11.8.1",
|
"@emotion/styled": "^11.8.1",
|
||||||
"@mui/icons-material": "^5.8.2",
|
"@mui/icons-material": "^5.8.2",
|
||||||
@@ -65,12 +66,14 @@
|
|||||||
"recharts": "^2.1.10",
|
"recharts": "^2.1.10",
|
||||||
"redoc": "^2.0.0-rc.71",
|
"redoc": "^2.0.0-rc.71",
|
||||||
"styled-components": "^5.3.5",
|
"styled-components": "^5.3.5",
|
||||||
|
"use-file-picker": "^1.4.2",
|
||||||
"web-vitals": "^2.1.4",
|
"web-vitals": "^2.1.4",
|
||||||
"xml-formatter": "^2.6.1"
|
"xml-formatter": "^2.6.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@rollup/plugin-node-resolve": "^13.3.0",
|
"@rollup/plugin-node-resolve": "^13.3.0",
|
||||||
"@svgr/rollup": "^6.2.1",
|
"@svgr/rollup": "^6.2.1",
|
||||||
|
"@types/ace": "^0.0.48",
|
||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
"env-cmd": "^10.1.0",
|
"env-cmd": "^10.1.0",
|
||||||
"gh-pages": "^4.0.0",
|
"gh-pages": "^4.0.0",
|
||||||
@@ -83,7 +86,7 @@
|
|||||||
"rollup-plugin-postcss": "^4.0.2",
|
"rollup-plugin-postcss": "^4.0.2",
|
||||||
"rollup-plugin-sass": "^1.2.12",
|
"rollup-plugin-sass": "^1.2.12",
|
||||||
"rollup-plugin-scss": "^3.0.0",
|
"rollup-plugin-scss": "^3.0.0",
|
||||||
"typescript": "^4.7.2"
|
"typescript": "^4.5.3"
|
||||||
},
|
},
|
||||||
"eslintConfig": {
|
"eslintConfig": {
|
||||||
"extends": [
|
"extends": [
|
||||||
@@ -92,6 +95,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
|
"src/*.scss",
|
||||||
"dist"
|
"dist"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,6 @@
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
width: -moz-available;
|
width: -moz-available;
|
||||||
width: -webkit-fill-available;
|
width: -webkit-fill-available;
|
||||||
width: strech;
|
width: stretch;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
import React, {useCallback, useEffect, useMemo, useState} from "react";
|
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import styles from './EntriesList.module.sass';
|
import styles from './EntriesList.module.sass';
|
||||||
import ScrollableFeedVirtualized from "react-scrollable-feed-virtualized";
|
import ScrollableFeedVirtualized from "react-scrollable-feed-virtualized";
|
||||||
import Moment from 'moment';
|
import { EntryItem } from "../EntryListItem/EntryListItem";
|
||||||
import {EntryItem} from "../EntryListItem/EntryListItem";
|
|
||||||
import down from "assets/downImg.svg";
|
import down from "assets/downImg.svg";
|
||||||
import spinner from 'assets/spinner.svg';
|
import spinner from 'assets/spinner.svg';
|
||||||
import {RecoilState, useRecoilState, useRecoilValue, useSetRecoilState} from "recoil";
|
import { RecoilState, useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
|
||||||
import entriesAtom from "../../recoil/entries";
|
import entriesAtom from "../../recoil/entries";
|
||||||
import queryAtom from "../../recoil/query";
|
import queryAtom from "../../recoil/query";
|
||||||
import TrafficViewerApiAtom from "../../recoil/TrafficViewerApi";
|
import TrafficViewerApiAtom from "../../recoil/TrafficViewerApi";
|
||||||
import TrafficViewerApi from "../TrafficViewer/TrafficViewerApi";
|
import TrafficViewerApi from "../TrafficViewer/TrafficViewerApi";
|
||||||
import focusedEntryIdAtom from "../../recoil/focusedEntryId";
|
import focusedEntryIdAtom from "../../recoil/focusedEntryId";
|
||||||
import {toast} from "react-toastify";
|
import { toast } from "react-toastify";
|
||||||
import {MAX_ENTRIES, TOAST_CONTAINER_ID} from "../../configs/Consts";
|
import { MAX_ENTRIES, TOAST_CONTAINER_ID } from "../../configs/Consts";
|
||||||
import tappingStatusAtom from "../../recoil/tappingStatus";
|
import tappingStatusAtom from "../../recoil/tappingStatus";
|
||||||
import leftOffTopAtom from "../../recoil/leftOffTop";
|
import leftOffTopAtom from "../../recoil/leftOffTop";
|
||||||
|
import Moment from "moment";
|
||||||
|
|
||||||
interface EntriesListProps {
|
interface EntriesListProps {
|
||||||
listEntryREF: any;
|
listEntryREF: any;
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ export const AutoRepresentation: React.FC<any> = ({ representation, color, opene
|
|||||||
badge: null
|
badge: null
|
||||||
}]
|
}]
|
||||||
|
|
||||||
if (response) {
|
if (response && response.length > 0) {
|
||||||
arr.push({
|
arr.push({
|
||||||
tab: 'Response',
|
tab: 'Response',
|
||||||
badge: null
|
badge: null
|
||||||
@@ -71,7 +71,7 @@ export const AutoRepresentation: React.FC<any> = ({ representation, color, opene
|
|||||||
{getOpenedTabIndex() === TabsEnum.Request && <React.Fragment>
|
{getOpenedTabIndex() === TabsEnum.Request && <React.Fragment>
|
||||||
<SectionsRepresentation data={request} color={color} requestRepresentation={request} />
|
<SectionsRepresentation data={request} color={color} requestRepresentation={request} />
|
||||||
</React.Fragment>}
|
</React.Fragment>}
|
||||||
{response && getOpenedTabIndex() === TabsEnum.Response && <React.Fragment>
|
{response && response.length > 0 && getOpenedTabIndex() === TabsEnum.Response && <React.Fragment>
|
||||||
<SectionsRepresentation data={response} color={color} />
|
<SectionsRepresentation data={response} color={color} />
|
||||||
</React.Fragment>}
|
</React.Fragment>}
|
||||||
</div>}
|
</div>}
|
||||||
|
|||||||
@@ -37,11 +37,6 @@ const CodeEditor: React.FC<CodeEditorProps> = ({
|
|||||||
theme="github"
|
theme="github"
|
||||||
onChange={onChange}
|
onChange={onChange}
|
||||||
editorProps={{ $blockScrolling: true }}
|
editorProps={{ $blockScrolling: true }}
|
||||||
setOptions={{
|
|
||||||
enableBasicAutocompletion: true,
|
|
||||||
enableLiveAutocompletion: true,
|
|
||||||
enableSnippets: true
|
|
||||||
}}
|
|
||||||
showPrintMargin={false}
|
showPrintMargin={false}
|
||||||
value={code}
|
value={code}
|
||||||
width="100%"
|
width="100%"
|
||||||
|
|||||||
33
ui-common/src/components/UI/FilePicker/FilePicker.tsx
Normal file
33
ui-common/src/components/UI/FilePicker/FilePicker.tsx
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
import { useFilePicker } from 'use-file-picker';
|
||||||
|
import { FileContent } from 'use-file-picker/dist/interfaces';
|
||||||
|
|
||||||
|
interface IFilePickerProps {
|
||||||
|
onLoadingComplete: (file: FileContent) => void;
|
||||||
|
elem: any
|
||||||
|
}
|
||||||
|
|
||||||
|
const FilePicker = ({ elem, onLoadingComplete }: IFilePickerProps) => {
|
||||||
|
const [openFileSelector, { filesContent }] = useFilePicker({
|
||||||
|
accept: ['.json'],
|
||||||
|
limitFilesConfig: { max: 1 },
|
||||||
|
maxFileSize: 1
|
||||||
|
});
|
||||||
|
|
||||||
|
const onFileSelectorClick = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
openFileSelector();
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
filesContent.length && onLoadingComplete(filesContent[0])
|
||||||
|
}, [filesContent, onLoadingComplete]);
|
||||||
|
|
||||||
|
return (<React.Fragment>
|
||||||
|
{React.cloneElement(elem, { onClick: onFileSelectorClick })}
|
||||||
|
</React.Fragment>)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FilePicker;
|
||||||
@@ -75,5 +75,6 @@ const KeyValueTable: React.FC<KeyValueTableProps> = ({ data, onDataChange, keyPl
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
export const convertParamsToArr = (paramsObj) => Object.entries(paramsObj).map(([key, value]) => { return { key, value } })
|
||||||
|
export const convertArrToKeyValueObject = (arr) => arr.reduce((acc, curr) => { acc[curr.key] = curr.value; return acc }, {})
|
||||||
export default KeyValueTable
|
export default KeyValueTable
|
||||||
|
|||||||
@@ -79,5 +79,12 @@
|
|||||||
overflow: hidden
|
overflow: hidden
|
||||||
|
|
||||||
b::after
|
b::after
|
||||||
content: '\b'
|
content: '\b'
|
||||||
display: inline
|
display: inline
|
||||||
|
|
||||||
|
.icon
|
||||||
|
width: 24px
|
||||||
|
height: 26px
|
||||||
|
stroke-width: 0px
|
||||||
|
fill: $blue-color
|
||||||
|
stroke: $blue-color
|
||||||
|
|||||||
@@ -1,25 +1,30 @@
|
|||||||
import { Accordion, AccordionDetails, AccordionSummary, Backdrop, Box, Button, Fade, Modal } from "@mui/material";
|
|
||||||
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
|
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
|
||||||
|
import DownloadIcon from '@mui/icons-material/FileDownloadOutlined';
|
||||||
|
import UploadIcon from '@mui/icons-material/UploadFile';
|
||||||
|
import closeIcon from "assets/close.svg";
|
||||||
|
import refreshImg from "assets/refresh.svg";
|
||||||
|
import { Accordion, AccordionDetails, AccordionSummary, Backdrop, Box, Button, Fade, Modal } from "@mui/material";
|
||||||
import React, { Fragment, useCallback, useEffect, useState } from "react";
|
import React, { Fragment, useCallback, useEffect, useState } from "react";
|
||||||
import { useCommonStyles } from "../../../helpers/commonStyle";
|
|
||||||
import { Tabs } from "../../UI";
|
|
||||||
import KeyValueTable from "../../UI/KeyValueTable/KeyValueTable";
|
|
||||||
import CodeEditor from "../../UI/CodeEditor/CodeEditor";
|
|
||||||
import { useRecoilValue, RecoilState, useRecoilState } from "recoil";
|
|
||||||
import TrafficViewerApiAtom from "../../../recoil/TrafficViewerApi/atom";
|
|
||||||
import TrafficViewerApi from "../../TrafficViewer/TrafficViewerApi";
|
|
||||||
import { toast } from "react-toastify";
|
import { toast } from "react-toastify";
|
||||||
|
import { RecoilState, useRecoilState, useRecoilValue } from "recoil";
|
||||||
|
import { FileContent } from "use-file-picker/dist/interfaces";
|
||||||
import { TOAST_CONTAINER_ID } from "../../../configs/Consts";
|
import { TOAST_CONTAINER_ID } from "../../../configs/Consts";
|
||||||
import styles from './ReplayRequestModal.module.sass'
|
import { useCommonStyles } from "../../../helpers/commonStyle";
|
||||||
import closeIcon from "assets/close.svg"
|
|
||||||
import refreshImg from "assets/refresh.svg"
|
|
||||||
import { formatRequestWithOutError } from "../../EntryDetailed/EntrySections/EntrySections";
|
|
||||||
import entryDataAtom from "../../../recoil/entryData";
|
|
||||||
import { AutoRepresentation, TabsEnum } from "../../EntryDetailed/EntryViewer/AutoRepresentation";
|
|
||||||
import useDebounce from "../../../hooks/useDebounce"
|
|
||||||
import replayRequestModalOpenAtom from "../../../recoil/replayRequestModalOpen";
|
|
||||||
import { Utils } from "../../../helpers/Utils";
|
import { Utils } from "../../../helpers/Utils";
|
||||||
|
import useDebounce from "../../../hooks/useDebounce";
|
||||||
|
import entryDataAtom from "../../../recoil/entryData";
|
||||||
|
import replayRequestModalOpenAtom from "../../../recoil/replayRequestModalOpen";
|
||||||
|
import TrafficViewerApiAtom from "../../../recoil/TrafficViewerApi/atom";
|
||||||
|
import { formatRequestWithOutError } from "../../EntryDetailed/EntrySections/EntrySections";
|
||||||
|
import { AutoRepresentation, TabsEnum } from "../../EntryDetailed/EntryViewer/AutoRepresentation";
|
||||||
|
import TrafficViewerApi from "../../TrafficViewer/TrafficViewerApi";
|
||||||
|
import { Tabs } from "../../UI";
|
||||||
|
import CodeEditor from "../../UI/CodeEditor/CodeEditor";
|
||||||
|
import FilePicker from '../../UI/FilePicker/FilePicker';
|
||||||
|
import KeyValueTable, { convertArrToKeyValueObject, convertParamsToArr } from "../../UI/KeyValueTable/KeyValueTable";
|
||||||
import { LoadingWrapper } from "../../UI/withLoading/withLoading";
|
import { LoadingWrapper } from "../../UI/withLoading/withLoading";
|
||||||
|
import { IReplayRequestData, KeyValuePair } from './interfaces';
|
||||||
|
import styles from './ReplayRequestModal.module.sass';
|
||||||
|
|
||||||
const modalStyle = {
|
const modalStyle = {
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
@@ -37,11 +42,6 @@ const modalStyle = {
|
|||||||
paddingBottom: "15px"
|
paddingBottom: "15px"
|
||||||
};
|
};
|
||||||
|
|
||||||
interface ReplayRequestModalProps {
|
|
||||||
isOpen: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
enum RequestTabs {
|
enum RequestTabs {
|
||||||
Params = "params",
|
Params = "params",
|
||||||
Headers = "headers",
|
Headers = "headers",
|
||||||
@@ -51,8 +51,6 @@ enum RequestTabs {
|
|||||||
const HTTP_METHODS = ["get", "post", "put", "head", "options", "delete"]
|
const HTTP_METHODS = ["get", "post", "put", "head", "options", "delete"]
|
||||||
const TABS = [{ tab: RequestTabs.Headers }, { tab: RequestTabs.Params }, { tab: RequestTabs.Body }];
|
const TABS = [{ tab: RequestTabs.Headers }, { tab: RequestTabs.Params }, { tab: RequestTabs.Body }];
|
||||||
|
|
||||||
const convertParamsToArr = (paramsObj) => Object.entries(paramsObj).map(([key, value]) => { return { key, value } })
|
|
||||||
|
|
||||||
const getQueryStringParams = (link: String) => {
|
const getQueryStringParams = (link: String) => {
|
||||||
|
|
||||||
if (link) {
|
if (link) {
|
||||||
@@ -69,43 +67,61 @@ const decodeQueryParam = (p) => {
|
|||||||
return decodeURIComponent(p.replace(/\+/g, ' '));
|
return decodeURIComponent(p.replace(/\+/g, ' '));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ReplayRequestModalProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
const ReplayRequestModal: React.FC<ReplayRequestModalProps> = ({ isOpen, onClose }) => {
|
const ReplayRequestModal: React.FC<ReplayRequestModalProps> = ({ isOpen, onClose }) => {
|
||||||
const entryData = useRecoilValue(entryDataAtom)
|
const entryData = useRecoilValue(entryDataAtom)
|
||||||
const request = entryData.data.request
|
const request = entryData.data.request
|
||||||
const [method, setMethod] = useState(request?.method?.toLowerCase() as string)
|
|
||||||
const getHostUrl = useCallback(() => {
|
const getHostUrl = useCallback(() => {
|
||||||
return entryData.data.dst.name ? entryData.data?.dst?.name : entryData.data.dst.ip
|
return entryData.data.dst.name ? entryData.data?.dst?.name : entryData.data.dst.ip
|
||||||
}, [entryData.data.dst.ip, entryData.data.dst.name])
|
}, [entryData.data.dst.ip, entryData.data.dst.name])
|
||||||
const [hostPortInput, setHostPortInput] = useState(`${entryData.base.proto.name}://${getHostUrl()}:${entryData.data.dst.port}`)
|
const getHostPortVal = useCallback(() => {
|
||||||
|
return `${entryData.base.proto.name}://${getHostUrl()}:${entryData.data.dst.port}`
|
||||||
|
}, [entryData.base.proto.name, entryData.data.dst.port, getHostUrl])
|
||||||
|
const [hostPortInput, setHostPortInput] = useState(getHostPortVal())
|
||||||
const [pathInput, setPathInput] = useState(request.path);
|
const [pathInput, setPathInput] = useState(request.path);
|
||||||
const commonClasses = useCommonStyles();
|
const commonClasses = useCommonStyles();
|
||||||
const [currentTab, setCurrentTab] = useState(TABS[0].tab);
|
const [currentTab, setCurrentTab] = useState(TABS[0].tab);
|
||||||
const [response, setResponse] = useState(null);
|
const [response, setResponse] = useState(null);
|
||||||
const [postData, setPostData] = useState(request?.postData?.text || JSON.stringify(request?.postData?.params));
|
|
||||||
const [params, setParams] = useState(convertParamsToArr(request?.queryString || {}))
|
|
||||||
const [headers, setHeaders] = useState(convertParamsToArr(request?.headers || {}))
|
|
||||||
const trafficViewerApi = useRecoilValue(TrafficViewerApiAtom as RecoilState<TrafficViewerApi>)
|
const trafficViewerApi = useRecoilValue(TrafficViewerApiAtom as RecoilState<TrafficViewerApi>)
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
const [requestExpanded, setRequestExpanded] = useState(true)
|
const [requestExpanded, setRequestExpanded] = useState(true)
|
||||||
const [responseExpanded, setResponseExpanded] = useState(false)
|
const [responseExpanded, setResponseExpanded] = useState(false)
|
||||||
|
|
||||||
|
const getInitialRequestData = useCallback((): IReplayRequestData => {
|
||||||
|
return {
|
||||||
|
method: request?.method?.toLowerCase() as string,
|
||||||
|
hostPort: `${entryData.base.proto.name}://${getHostUrl()}:${entryData.data.dst.port}`,
|
||||||
|
path: request.path,
|
||||||
|
postData: request.postData?.text || JSON.stringify(request.postData?.params),
|
||||||
|
headers: convertParamsToArr(request.headers || {}),
|
||||||
|
params: convertParamsToArr(request.queryString || {})
|
||||||
|
}
|
||||||
|
}, [entryData.base.proto.name, entryData.data.dst.port, getHostUrl, request.headers, request?.method, request.path, request.postData?.params, request.postData?.text, request.queryString])
|
||||||
|
|
||||||
|
const [requestDataModel, setRequestData] = useState<IReplayRequestData>(getInitialRequestData())
|
||||||
|
|
||||||
const debouncedPath = useDebounce(pathInput, 500);
|
const debouncedPath = useDebounce(pathInput, 500);
|
||||||
|
|
||||||
|
const addParamsToUrl = useCallback((url: string, params: KeyValuePair[]) => {
|
||||||
|
const urlParams = new URLSearchParams("");
|
||||||
|
params.forEach(param => urlParams.append(param.key, param.value as string))
|
||||||
|
return `${url}?${urlParams.toString()}`
|
||||||
|
}, [])
|
||||||
|
|
||||||
const onParamsChange = useCallback((newParams) => {
|
const onParamsChange = useCallback((newParams) => {
|
||||||
setParams(newParams);
|
|
||||||
let newUrl = `${debouncedPath ? debouncedPath.split('?')[0] : ""}`
|
let newUrl = `${debouncedPath ? debouncedPath.split('?')[0] : ""}`
|
||||||
newParams.forEach(({ key, value }, index) => {
|
newUrl = addParamsToUrl(newUrl, newParams)
|
||||||
newUrl += index > 0 ? '&' : '?'
|
|
||||||
newUrl += `${key}` + (value ? `=${value}` : "")
|
|
||||||
})
|
|
||||||
|
|
||||||
setPathInput(newUrl)
|
setPathInput(newUrl)
|
||||||
|
}, [addParamsToUrl, debouncedPath])
|
||||||
}, [debouncedPath])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const newParams = getQueryStringParams(debouncedPath);
|
const params = convertParamsToArr(getQueryStringParams(debouncedPath));
|
||||||
setParams(convertParamsToArr(newParams))
|
setRequestData({ ...requestDataModel, params })
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [debouncedPath])
|
}, [debouncedPath])
|
||||||
|
|
||||||
const onModalClose = () => {
|
const onModalClose = () => {
|
||||||
@@ -114,33 +130,28 @@ const ReplayRequestModal: React.FC<ReplayRequestModalProps> = ({ isOpen, onClose
|
|||||||
onClose()
|
onClose()
|
||||||
}
|
}
|
||||||
|
|
||||||
const resetModel = useCallback(() => {
|
const resetModal = useCallback((requestDataModel: IReplayRequestData, hostPortInputVal, pathVal) => {
|
||||||
setMethod(request?.method?.toLowerCase() as string)
|
setRequestData(requestDataModel)
|
||||||
setHostPortInput(`${entryData.base.proto.name}://${getHostUrl()}:${entryData.data.dst.port}`)
|
setHostPortInput(hostPortInputVal)
|
||||||
setPathInput(request.path);
|
setPathInput(addParamsToUrl(pathVal, requestDataModel.params));
|
||||||
setResponse(null);
|
setResponse(null);
|
||||||
setPostData(request?.postData?.text || JSON.stringify(request?.postData?.params));
|
setRequestExpanded(true);
|
||||||
setParams(convertParamsToArr(request?.queryString || {}))
|
}, [addParamsToUrl])
|
||||||
setHeaders(convertParamsToArr(request?.headers || {}))
|
|
||||||
setRequestExpanded(true)
|
|
||||||
}, [entryData.base.proto.name, entryData.data.dst.port, getHostUrl, request?.headers, request?.method, request.path, request?.postData?.params, request?.postData?.text, request?.queryString])
|
|
||||||
|
|
||||||
const onRefreshRequest = useCallback((event) => {
|
const onRefreshRequest = useCallback((event) => {
|
||||||
event.stopPropagation()
|
event.stopPropagation();
|
||||||
resetModel()
|
const hostPortInputVal = getHostPortVal();
|
||||||
}, [resetModel])
|
resetModal(getInitialRequestData(), hostPortInputVal, request.path);
|
||||||
|
}, [getHostPortVal, getInitialRequestData, request.path, resetModal])
|
||||||
|
|
||||||
|
|
||||||
const sendRequest = useCallback(async () => {
|
const sendRequest = useCallback(async () => {
|
||||||
setResponse(null)
|
setResponse(null)
|
||||||
const headersData = headers.reduce((prev, corrent) => {
|
const headersData = convertArrToKeyValueObject(requestDataModel.headers)
|
||||||
prev[corrent.key] = corrent.value
|
|
||||||
return prev
|
|
||||||
}, {})
|
|
||||||
const buildUrl = `${hostPortInput}${pathInput}`
|
|
||||||
const requestData = { url: buildUrl, headers: headersData, data: postData, method }
|
|
||||||
try {
|
try {
|
||||||
setIsLoading(true)
|
setIsLoading(true)
|
||||||
|
const requestData = { url: `${hostPortInput}${pathInput}`, headers: headersData, data: requestDataModel.postData, method: requestDataModel.method }
|
||||||
const response = await trafficViewerApi.replayRequest(requestData)
|
const response = await trafficViewerApi.replayRequest(requestData)
|
||||||
setResponse(response?.data?.representation)
|
setResponse(response?.data?.representation)
|
||||||
if (response.errorMessage) {
|
if (response.errorMessage) {
|
||||||
@@ -150,7 +161,6 @@ const ReplayRequestModal: React.FC<ReplayRequestModalProps> = ({ isOpen, onClose
|
|||||||
setRequestExpanded(false)
|
setRequestExpanded(false)
|
||||||
setResponseExpanded(true)
|
setResponseExpanded(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setRequestExpanded(true)
|
setRequestExpanded(true)
|
||||||
toast.error("Error occurred while fetching response", { containerId: TOAST_CONTAINER_ID });
|
toast.error("Error occurred while fetching response", { containerId: TOAST_CONTAINER_ID });
|
||||||
@@ -159,27 +169,37 @@ const ReplayRequestModal: React.FC<ReplayRequestModalProps> = ({ isOpen, onClose
|
|||||||
finally {
|
finally {
|
||||||
setIsLoading(false)
|
setIsLoading(false)
|
||||||
}
|
}
|
||||||
|
}, [hostPortInput, pathInput, requestDataModel.headers, requestDataModel.method, requestDataModel.postData, trafficViewerApi])
|
||||||
|
|
||||||
}, [headers, hostPortInput, method, pathInput, postData, trafficViewerApi])
|
const onDownloadRequest = useCallback((e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
const date = Utils.getNow()
|
||||||
|
Utils.exportToJson(requestDataModel, `${getHostUrl()} - ${date}`)
|
||||||
|
}, [getHostUrl, requestDataModel])
|
||||||
|
|
||||||
|
const onLoadingComplete = useCallback((fileContent: FileContent) => {
|
||||||
|
const requestData = JSON.parse(fileContent.content) as IReplayRequestData
|
||||||
|
resetModal(requestData, requestData.hostPort, requestData.path)
|
||||||
|
}, [resetModal])
|
||||||
|
|
||||||
let innerComponent
|
let innerComponent
|
||||||
switch (currentTab) {
|
switch (currentTab) {
|
||||||
case RequestTabs.Params:
|
case RequestTabs.Params:
|
||||||
innerComponent = <div className={styles.keyValueContainer}><KeyValueTable data={params} onDataChange={onParamsChange} key={"params"} valuePlaceholder="New Param Value" keyPlaceholder="New param Key" /></div>
|
innerComponent = <div className={styles.keyValueContainer}><KeyValueTable data={requestDataModel.params} onDataChange={onParamsChange} key={"params"} valuePlaceholder="New Param Value" keyPlaceholder="New param Key" /></div>
|
||||||
break;
|
break;
|
||||||
case RequestTabs.Headers:
|
case RequestTabs.Headers:
|
||||||
innerComponent = <Fragment>
|
innerComponent = <Fragment>
|
||||||
<div className={styles.keyValueContainer}><KeyValueTable data={headers} onDataChange={(heaedrs) => setHeaders(heaedrs)} key={"Header"} valuePlaceholder="New Headers Value" keyPlaceholder="New Headers Key" />
|
<div className={styles.keyValueContainer}><KeyValueTable data={requestDataModel.headers} onDataChange={(headers) => setRequestData({ ...requestDataModel, headers: headers })} key={"Header"} valuePlaceholder="New Headers Value" keyPlaceholder="New Headers Key" />
|
||||||
</div>
|
</div>
|
||||||
<span className={styles.note}><b>* </b> X-Mizu Header added to reuqests</span>
|
<span className={styles.note}><b>* </b> X-Mizu Header added to requests</span>
|
||||||
</Fragment>
|
</Fragment>
|
||||||
break;
|
break;
|
||||||
case RequestTabs.Body:
|
case RequestTabs.Body:
|
||||||
const formatedCode = formatRequestWithOutError(postData || "", request?.postData?.mimeType)
|
const formattedCode = formatRequestWithOutError(requestDataModel.postData || "", request?.postData?.mimeType)
|
||||||
innerComponent = <div className={styles.codeEditor}>
|
innerComponent = <div className={styles.codeEditor}>
|
||||||
<CodeEditor language={request?.postData?.mimeType.split("/")[1]}
|
<CodeEditor language={request?.postData?.mimeType.split("/")[1]}
|
||||||
code={Utils.isJson(formatedCode) ? JSON.stringify(JSON.parse(formatedCode || "{}"), null, 2) : formatedCode}
|
code={Utils.isJson(formattedCode) ? JSON.stringify(JSON.parse(formattedCode || "{}"), null, 2) : formattedCode}
|
||||||
onChange={setPostData} />
|
onChange={(postData) => setRequestData({ ...requestDataModel, postData })} />
|
||||||
</div>
|
</div>
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -204,17 +224,43 @@ const ReplayRequestModal: React.FC<ReplayRequestModalProps> = ({ isOpen, onClose
|
|||||||
<div className={styles.headerContainer}>
|
<div className={styles.headerContainer}>
|
||||||
<div className={styles.headerSection}>
|
<div className={styles.headerSection}>
|
||||||
<span className={styles.title}>Replay Request</span>
|
<span className={styles.title}>Replay Request</span>
|
||||||
|
<Button style={{ marginLeft: "2%", textTransform: 'unset' }}
|
||||||
|
startIcon={<img src={refreshImg} className="custom" alt="Refresh Request"></img>}
|
||||||
|
size="medium"
|
||||||
|
variant="contained"
|
||||||
|
className={commonClasses.outlinedButton + " " + commonClasses.imagedButton}
|
||||||
|
onClick={onRefreshRequest}
|
||||||
|
>
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
<Button style={{ marginLeft: "2%", textTransform: 'unset' }}
|
||||||
|
startIcon={<DownloadIcon className={`custom ${styles.icon}`} />}
|
||||||
|
size="medium"
|
||||||
|
variant="contained"
|
||||||
|
className={commonClasses.outlinedButton + " " + commonClasses.imagedButton}
|
||||||
|
onClick={onDownloadRequest}
|
||||||
|
>
|
||||||
|
Download
|
||||||
|
</Button>
|
||||||
|
<FilePicker onLoadingComplete={onLoadingComplete}
|
||||||
|
elem={<Button style={{ marginLeft: "2%", textTransform: 'unset' }}
|
||||||
|
startIcon={<UploadIcon className={`custom ${styles.icon}`} />}
|
||||||
|
size="medium"
|
||||||
|
variant="contained"
|
||||||
|
className={commonClasses.outlinedButton + " " + commonClasses.imagedButton}>
|
||||||
|
Upload
|
||||||
|
</Button>}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.modalContainer}>
|
<div className={styles.modalContainer}>
|
||||||
<Accordion TransitionProps={{ unmountOnExit: true }} expanded={requestExpanded} onChange={() => setRequestExpanded(!requestExpanded)}>
|
<Accordion TransitionProps={{ unmountOnExit: true }} expanded={requestExpanded} onChange={() => setRequestExpanded(!requestExpanded)}>
|
||||||
<AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls="response-content">
|
<AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls="response-content">
|
||||||
<span className={styles.sectionHeader}>REQUEST</span>
|
<span className={styles.sectionHeader}>REQUEST</span>
|
||||||
<img src={refreshImg} style={{ marginLeft: "10px" }} title="Refresh Reuqest" alt="Refresh Reuqest" onClick={onRefreshRequest} />
|
|
||||||
</AccordionSummary>
|
</AccordionSummary>
|
||||||
<AccordionDetails>
|
<AccordionDetails>
|
||||||
<div className={styles.path}>
|
<div className={styles.path}>
|
||||||
<select className={styles.select} value={method} onChange={(e) => setMethod(e.target.value)}>
|
<select className={styles.select} value={requestDataModel.method} onChange={(e) => setRequestData({ ...requestDataModel, method: e.target.value })}>
|
||||||
{HTTP_METHODS.map(method => <option value={method} key={method}>{method}</option>)}
|
{HTTP_METHODS.map(method => <option value={method} key={method}>{method}</option>)}
|
||||||
</select>
|
</select>
|
||||||
<input placeholder="Host:Port" value={hostPortInput} onChange={(event) => setHostPortInput(event.target.value)} className={`${commonClasses.textField} ${styles.hostPort}`} />
|
<input placeholder="Host:Port" value={hostPortInput} onChange={(event) => setHostPortInput(event.target.value)} className={`${commonClasses.textField} ${styles.hostPort}`} />
|
||||||
@@ -246,7 +292,7 @@ const ReplayRequestModal: React.FC<ReplayRequestModalProps> = ({ isOpen, onClose
|
|||||||
</div>
|
</div>
|
||||||
</Box>
|
</Box>
|
||||||
</Fade>
|
</Fade>
|
||||||
</Modal>
|
</Modal >
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
export interface KeyValuePair {
|
||||||
|
key: string;
|
||||||
|
value: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReplayRequestData {
|
||||||
|
method: string;
|
||||||
|
hostPort: string;
|
||||||
|
path: string;
|
||||||
|
postData: string;
|
||||||
|
headers: KeyValuePair[]
|
||||||
|
params: KeyValuePair[]
|
||||||
|
}
|
||||||
@@ -35,6 +35,7 @@ $modalMargin-from-edge : 35px
|
|||||||
color: $blue-gray
|
color: $blue-gray
|
||||||
font-weight: 600
|
font-weight: 600
|
||||||
margin-right: 35px
|
margin-right: 35px
|
||||||
|
white-space: nowrap
|
||||||
|
|
||||||
.graphSection
|
.graphSection
|
||||||
flex: 85%
|
flex: 85%
|
||||||
@@ -96,4 +97,7 @@ $modalMargin-from-edge : 35px
|
|||||||
overflow: hidden
|
overflow: hidden
|
||||||
|
|
||||||
.servicesFilterList
|
.servicesFilterList
|
||||||
height: calc(100% - 30px - 52px)
|
height: calc(100% - 30px)
|
||||||
|
|
||||||
|
.protocolsFilterList
|
||||||
|
height: 100%
|
||||||
|
|||||||
@@ -228,7 +228,7 @@ export const ServiceMapModal: React.FC<ServiceMapModalProps> = ({ isOpen, onClos
|
|||||||
<div className={styles.filterWrapper}>
|
<div className={styles.filterWrapper}>
|
||||||
<div className={styles.card}>
|
<div className={styles.card}>
|
||||||
<SelectList items={getProtocolsForFilter} checkBoxWidth="5%" tableName={"PROTOCOLS"} multiSelect={true}
|
<SelectList items={getProtocolsForFilter} checkBoxWidth="5%" tableName={"PROTOCOLS"} multiSelect={true}
|
||||||
checkedValues={checkedProtocols} setCheckedValues={onProtocolsChange} tableClassName={styles.filters}
|
checkedValues={checkedProtocols} setCheckedValues={onProtocolsChange} tableClassName={styles.filters + ` ${styles.protocolsFilterList}`}
|
||||||
inputSearchClass={styles.servicesFilterSearch} isFilterable={false} />
|
inputSearchClass={styles.servicesFilterSearch} isFilterable={false} />
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.servicesFilterWrapper + ` ${styles.card}`}>
|
<div className={styles.servicesFilterWrapper + ` ${styles.card}`}>
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import React, { useState, Fragment } from 'react';
|
||||||
|
import { EuiProvider } from '@elastic/eui';
|
||||||
|
|
||||||
|
import {
|
||||||
|
EuiSuperDatePicker,
|
||||||
|
EuiSpacer,
|
||||||
|
} from '@elastic/eui';
|
||||||
|
import dateMath from '@elastic/datemath';
|
||||||
|
import '@elastic/eui/dist/eui_theme_light.css';
|
||||||
|
|
||||||
|
interface TimeRangePickerProps {
|
||||||
|
refreshStats: (startTime, endTime) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TimeRangePicker: React.FC<TimeRangePickerProps> = ({ refreshStats }) => {
|
||||||
|
const [recentlyUsedRanges, setRecentlyUsedRanges] = useState([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [start, setStart] = useState('now-30m');
|
||||||
|
const [end, setEnd] = useState('now');
|
||||||
|
const [isPaused, setIsPaused] = useState(true);
|
||||||
|
const [refreshInterval, setRefreshInterval] = useState();
|
||||||
|
|
||||||
|
const dateConvertor = (inputStart, inputEnd) => {
|
||||||
|
const startMoment = dateMath.parse(inputStart);
|
||||||
|
if (!startMoment || !startMoment.isValid()) {
|
||||||
|
console.error("Unable to parse start string");
|
||||||
|
}
|
||||||
|
const endMoment = dateMath.parse(inputEnd, { roundUp: true });
|
||||||
|
if (!endMoment || !endMoment.isValid()) {
|
||||||
|
console.error("Unable to parse end string");
|
||||||
|
}
|
||||||
|
return { startMoment: startMoment.format("x"), endMoment: endMoment.format("x") }
|
||||||
|
}
|
||||||
|
|
||||||
|
const onTimeChange = ({ start, end }) => {
|
||||||
|
const recentlyUsedRange = recentlyUsedRanges.filter(recentlyUsedRange => {
|
||||||
|
const isDuplicate =
|
||||||
|
recentlyUsedRange.start === start && recentlyUsedRange.end === end;
|
||||||
|
return !isDuplicate;
|
||||||
|
});
|
||||||
|
recentlyUsedRange.unshift({ start, end });
|
||||||
|
setStart(start);
|
||||||
|
setEnd(end);
|
||||||
|
setRecentlyUsedRanges(
|
||||||
|
recentlyUsedRange.length > 10
|
||||||
|
? recentlyUsedRange.slice(0, 9)
|
||||||
|
: recentlyUsedRange
|
||||||
|
);
|
||||||
|
const { startMoment, endMoment } = dateConvertor(start, end)
|
||||||
|
refreshStats(startMoment, endMoment)
|
||||||
|
setIsLoading(true);
|
||||||
|
startLoading();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onRefresh = ({ start, end, refreshInterval }) => {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
setTimeout(resolve, 100);
|
||||||
|
}).then(() => {
|
||||||
|
const { startMoment, endMoment } = dateConvertor(start, end)
|
||||||
|
refreshStats(startMoment, endMoment)
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const startLoading = () => {
|
||||||
|
setTimeout(stopLoading, 1000);
|
||||||
|
};
|
||||||
|
const stopLoading = () => {
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onRefreshChange = ({ isPaused, refreshInterval }) => {
|
||||||
|
setIsPaused(isPaused);
|
||||||
|
setRefreshInterval(refreshInterval);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<EuiProvider>
|
||||||
|
<Fragment>
|
||||||
|
<EuiSpacer />
|
||||||
|
<EuiSuperDatePicker
|
||||||
|
width='auto'
|
||||||
|
isLoading={isLoading}
|
||||||
|
start={start}
|
||||||
|
end={end}
|
||||||
|
onTimeChange={onTimeChange}
|
||||||
|
onRefresh={onRefresh}
|
||||||
|
isPaused={isPaused}
|
||||||
|
refreshInterval={refreshInterval}
|
||||||
|
onRefreshChange={onRefreshChange}
|
||||||
|
recentlyUsedRanges={recentlyUsedRanges}
|
||||||
|
/>
|
||||||
|
<EuiSpacer />
|
||||||
|
</Fragment>
|
||||||
|
</EuiProvider>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
@import "../../../../variables.module"
|
||||||
|
|
||||||
.barChartContainer
|
.barChartContainer
|
||||||
width: 100%
|
width: 100%
|
||||||
display: flex
|
display: flex
|
||||||
@@ -6,3 +8,4 @@
|
|||||||
.axisText
|
.axisText
|
||||||
font-size: 12px
|
font-size: 12px
|
||||||
opacity: 0.9
|
opacity: 0.9
|
||||||
|
font-family: $text-font-family
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ export const TimelineBarChart: React.FC<TimelineBarChartProps> = ({ timeLineBarC
|
|||||||
})
|
})
|
||||||
protocolsBarsData.push(newProtocolObj);
|
protocolsBarsData.push(newProtocolObj);
|
||||||
})
|
})
|
||||||
const uniqueObjArray = Utils.creatUniqueObjArrayByProp(prtcNames, "name")
|
const uniqueObjArray = Utils.createUniqueObjArrayByProp(prtcNames, "name")
|
||||||
setProtocolStats(protocolsBarsData);
|
setProtocolStats(protocolsBarsData);
|
||||||
setProtocolsNamesAndColors(uniqueObjArray);
|
setProtocolsNamesAndColors(uniqueObjArray);
|
||||||
}, [data, timeLineBarChartMode])
|
}, [data, timeLineBarChartMode])
|
||||||
@@ -57,7 +57,7 @@ export const TimelineBarChart: React.FC<TimelineBarChartProps> = ({ timeLineBarC
|
|||||||
})
|
})
|
||||||
protocolsMethods.push(newMethodObj);
|
protocolsMethods.push(newMethodObj);
|
||||||
})
|
})
|
||||||
const uniqueObjArray = Utils.creatUniqueObjArrayByProp(protocolsMethodsNamesAndColors, "name")
|
const uniqueObjArray = Utils.createUniqueObjArrayByProp(protocolsMethodsNamesAndColors, "name")
|
||||||
setMethodsNamesAndColors(uniqueObjArray);
|
setMethodsNamesAndColors(uniqueObjArray);
|
||||||
setMethodsStats(protocolsMethods);
|
setMethodsStats(protocolsMethods);
|
||||||
}, [data, timeLineBarChartMode, selectedProtocol])
|
}, [data, timeLineBarChartMode, selectedProtocol])
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
@import "../../../../variables.module"
|
||||||
|
|
||||||
|
.entryName
|
||||||
|
margin-left: 5px
|
||||||
|
font-family: $text-font-family
|
||||||
@@ -2,6 +2,7 @@ import React, { useEffect, useMemo, useState } from "react";
|
|||||||
import { Cell, Legend, Pie, PieChart, Tooltip } from "recharts";
|
import { Cell, Legend, Pie, PieChart, Tooltip } from "recharts";
|
||||||
import { Utils } from "../../../../helpers/Utils";
|
import { Utils } from "../../../../helpers/Utils";
|
||||||
import { ALL_PROTOCOLS ,StatsMode as PieChartMode } from "../consts"
|
import { ALL_PROTOCOLS ,StatsMode as PieChartMode } from "../consts"
|
||||||
|
import styles from "./TrafficPieChart.module.sass";
|
||||||
|
|
||||||
const RADIAN = Math.PI / 180;
|
const RADIAN = Math.PI / 180;
|
||||||
const renderCustomizedLabel = ({
|
const renderCustomizedLabel = ({
|
||||||
@@ -76,7 +77,7 @@ export const TrafficPieChart: React.FC<TrafficPieChartProps> = ({ pieChartMode,
|
|||||||
if (selectedProtocol === ALL_PROTOCOLS) {
|
if (selectedProtocol === ALL_PROTOCOLS) {
|
||||||
legend = data.map(protocol => <div style={{ marginBottom: 5, display: "flex" }}>
|
legend = data.map(protocol => <div style={{ marginBottom: 5, display: "flex" }}>
|
||||||
<div style={{ height: 15, width: 30, background: protocol?.color }} />
|
<div style={{ height: 15, width: 30, background: protocol?.color }} />
|
||||||
<span style={{ marginLeft: 5 }}>
|
<span className={styles.entryName}>
|
||||||
{protocol.name}
|
{protocol.name}
|
||||||
</span>
|
</span>
|
||||||
</div>)
|
</div>)
|
||||||
@@ -84,7 +85,7 @@ export const TrafficPieChart: React.FC<TrafficPieChartProps> = ({ pieChartMode,
|
|||||||
legend = data.find(protocol => protocol.name === selectedProtocol)?.methods.map((method) => <div
|
legend = data.find(protocol => protocol.name === selectedProtocol)?.methods.map((method) => <div
|
||||||
style={{ marginBottom: 5, display: "flex" }}>
|
style={{ marginBottom: 5, display: "flex" }}>
|
||||||
<div style={{ height: 15, width: 30, background: method.color}} />
|
<div style={{ height: 15, width: 30, background: method.color}} />
|
||||||
<span style={{ marginLeft: 5 }}>
|
<span className={styles.entryName}>
|
||||||
{method.name}
|
{method.name}
|
||||||
</span>
|
</span>
|
||||||
</div>)
|
</div>)
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
|
@import "../../../variables.module"
|
||||||
|
|
||||||
.headlineContainer
|
.headlineContainer
|
||||||
display: flex
|
display: flex
|
||||||
|
|
||||||
.title
|
.title
|
||||||
color: #494677
|
color: #494677
|
||||||
font-family: Source Sans Pro,Lucida Grande,Tahoma,sans-serif
|
font-family: $text-font-family
|
||||||
font-size: 28px
|
font-size: 28px
|
||||||
font-weight: 600
|
font-weight: 600
|
||||||
|
|
||||||
@@ -13,16 +15,21 @@
|
|||||||
top: 20px
|
top: 20px
|
||||||
|
|
||||||
.mainContainer
|
.mainContainer
|
||||||
padding: 30px
|
|
||||||
text-align: center
|
text-align: center
|
||||||
|
|
||||||
.selectContainer
|
.selectContainer
|
||||||
display: flex
|
display: flex
|
||||||
justify-content: space-evenly
|
justify-content: space-evenly
|
||||||
|
align-items: center
|
||||||
margin-bottom: 4%
|
margin-bottom: 4%
|
||||||
|
|
||||||
|
.selectTitle
|
||||||
|
font-family: $text-font-family
|
||||||
|
margin-right: 15px
|
||||||
|
|
||||||
.select
|
.select
|
||||||
border: none
|
border: none
|
||||||
border-bottom: 1px black solid
|
border-bottom: 1px black solid
|
||||||
outline: none
|
outline: none
|
||||||
width: 100px
|
width: 100px
|
||||||
|
font-family: $text-font-family
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
import React, { useCallback, useEffect, useState } from "react";
|
import React, { useCallback, useEffect, useState } from "react";
|
||||||
import { Backdrop, Box, Button, debounce, Fade, Modal } from "@mui/material";
|
import { Backdrop, Box, debounce, Fade, Modal } from "@mui/material";
|
||||||
import styles from "./TrafficStatsModal.module.sass";
|
import styles from "./TrafficStatsModal.module.sass";
|
||||||
import closeIcon from "assets/close.svg";
|
import closeIcon from "assets/close.svg";
|
||||||
import { TrafficPieChart } from "./TrafficPieChart/TrafficPieChart";
|
import { TrafficPieChart } from "./TrafficPieChart/TrafficPieChart";
|
||||||
import { TimelineBarChart } from "./TimelineBarChart/TimelineBarChart";
|
import { TimelineBarChart } from "./TimelineBarChart/TimelineBarChart";
|
||||||
import refreshIcon from "assets/refresh.svg";
|
|
||||||
import { useCommonStyles } from "../../../helpers/commonStyle";
|
|
||||||
import { LoadingWrapper } from "../../UI/withLoading/withLoading";
|
import { LoadingWrapper } from "../../UI/withLoading/withLoading";
|
||||||
import { ALL_PROTOCOLS, StatsMode } from "./consts";
|
import { ALL_PROTOCOLS, StatsMode } from "./consts";
|
||||||
|
import { TimeRangePicker } from "./TimelineBarChart/TimeRangePicker/TimeTangePicker";
|
||||||
|
|
||||||
const modalStyle = {
|
const modalStyle = {
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
@@ -15,7 +14,7 @@ const modalStyle = {
|
|||||||
left: '50%',
|
left: '50%',
|
||||||
transform: 'translate(-50%, 0%)',
|
transform: 'translate(-50%, 0%)',
|
||||||
width: '60vw',
|
width: '60vw',
|
||||||
height: '82vh',
|
height: '90vh',
|
||||||
bgcolor: 'background.paper',
|
bgcolor: 'background.paper',
|
||||||
borderRadius: '5px',
|
borderRadius: '5px',
|
||||||
boxShadow: 24,
|
boxShadow: 24,
|
||||||
@@ -26,11 +25,10 @@ const modalStyle = {
|
|||||||
interface TrafficStatsModalProps {
|
interface TrafficStatsModalProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
getTrafficStatsDataApi: () => Promise<any>
|
getTrafficStatsDataApi: (start?, end?) => Promise<any>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const TrafficStatsModal: React.FC<TrafficStatsModalProps> = ({ isOpen, onClose, getTrafficStatsDataApi }) => {
|
export const TrafficStatsModal: React.FC<TrafficStatsModalProps> = ({ isOpen, onClose, getTrafficStatsDataApi }) => {
|
||||||
|
|
||||||
const modes = Object.keys(StatsMode).filter(x => !(parseInt(x) >= 0));
|
const modes = Object.keys(StatsMode).filter(x => !(parseInt(x) >= 0));
|
||||||
const [statsMode, setStatsMode] = useState(modes[0]);
|
const [statsMode, setStatsMode] = useState(modes[0]);
|
||||||
const [selectedProtocol, setSelectedProtocol] = useState(ALL_PROTOCOLS);
|
const [selectedProtocol, setSelectedProtocol] = useState(ALL_PROTOCOLS);
|
||||||
@@ -38,14 +36,13 @@ export const TrafficStatsModal: React.FC<TrafficStatsModalProps> = ({ isOpen, on
|
|||||||
const [timelineStatsData, setTimelineStatsData] = useState(null);
|
const [timelineStatsData, setTimelineStatsData] = useState(null);
|
||||||
const [protocols, setProtocols] = useState([])
|
const [protocols, setProtocols] = useState([])
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const commonClasses = useCommonStyles();
|
|
||||||
|
|
||||||
const getTrafficStats = useCallback(async () => {
|
const getTrafficStats = useCallback(async (startTime, endTime) => {
|
||||||
if (isOpen && getTrafficStatsDataApi) {
|
if (isOpen && getTrafficStatsDataApi) {
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
const statsData = await getTrafficStatsDataApi();
|
const statsData = await getTrafficStatsDataApi(startTime, endTime);
|
||||||
setPieStatsData(statsData.pie);
|
setPieStatsData(statsData.pie);
|
||||||
setTimelineStatsData(statsData.timeline);
|
setTimelineStatsData(statsData.timeline);
|
||||||
setProtocols(statsData.protocols)
|
setProtocols(statsData.protocols)
|
||||||
@@ -59,11 +56,13 @@ export const TrafficStatsModal: React.FC<TrafficStatsModalProps> = ({ isOpen, on
|
|||||||
}, [isOpen, getTrafficStatsDataApi, setPieStatsData, setTimelineStatsData])
|
}, [isOpen, getTrafficStatsDataApi, setPieStatsData, setTimelineStatsData])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getTrafficStats();
|
const now = new Date().getTime();
|
||||||
|
const halfAnHourAgo = now - (30 * 60 * 1000);
|
||||||
|
getTrafficStats(halfAnHourAgo, now);
|
||||||
}, [getTrafficStats])
|
}, [getTrafficStats])
|
||||||
|
|
||||||
const refreshStats = debounce(() => {
|
const refreshStats = debounce((newStartTime, newEndTime) => {
|
||||||
getTrafficStats();
|
getTrafficStats(newStartTime, newEndTime);
|
||||||
}, 500);
|
}, 500);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -82,30 +81,24 @@ export const TrafficStatsModal: React.FC<TrafficStatsModalProps> = ({ isOpen, on
|
|||||||
</div>
|
</div>
|
||||||
<div className={styles.headlineContainer}>
|
<div className={styles.headlineContainer}>
|
||||||
<div className={styles.title}>Traffic Statistics</div>
|
<div className={styles.title}>Traffic Statistics</div>
|
||||||
<Button style={{ marginLeft: "2%", textTransform: 'unset' }}
|
|
||||||
startIcon={<img src={refreshIcon} className="custom" alt="refresh"></img>}
|
|
||||||
size="medium"
|
|
||||||
variant="contained"
|
|
||||||
className={commonClasses.outlinedButton + " " + commonClasses.imagedButton}
|
|
||||||
onClick={refreshStats}
|
|
||||||
>
|
|
||||||
Refresh
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.mainContainer}>
|
<div className={styles.mainContainer}>
|
||||||
<div className={styles.selectContainer}>
|
<div className={styles.selectContainer}>
|
||||||
<div>
|
<div>
|
||||||
<span style={{ marginRight: 15 }}>Breakdown By</span>
|
<span className={styles.selectTitle}>Breakdown By</span>
|
||||||
<select className={styles.select} value={statsMode} onChange={(e) => setStatsMode(e.target.value)}>
|
<select className={styles.select} value={statsMode} onChange={(e) => setStatsMode(e.target.value)}>
|
||||||
{modes.map(mode => <option key={mode} value={mode}>{mode}</option>)}
|
{modes.map(mode => <option key={mode} value={mode}>{mode}</option>)}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span style={{ marginRight: 15 }}>Protocol</span>
|
<span className={styles.selectTitle}>Protocol</span>
|
||||||
<select className={styles.select} value={selectedProtocol} onChange={(e) => setSelectedProtocol(e.target.value)}>
|
<select className={styles.select} value={selectedProtocol} onChange={(e) => setSelectedProtocol(e.target.value)}>
|
||||||
{protocols.map(protocol => <option key={protocol} value={protocol}>{protocol}</option>)}
|
{protocols.map(protocol => <option key={protocol} value={protocol}>{protocol}</option>)}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<TimeRangePicker refreshStats={refreshStats} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<LoadingWrapper isLoading={isLoading} loaderMargin={20} loaderHeight={50}>
|
<LoadingWrapper isLoading={isLoading} loaderMargin={20} loaderHeight={50}>
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
|
import Moment from 'moment';
|
||||||
|
|
||||||
const IP_ADDRESS_REGEX = /([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})(:([0-9]{1,5}))?/
|
const IP_ADDRESS_REGEX = /([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})(:([0-9]{1,5}))?/
|
||||||
|
|
||||||
|
type JSONValue =
|
||||||
|
| string
|
||||||
|
| number
|
||||||
|
| boolean
|
||||||
|
| Object
|
||||||
|
|
||||||
|
|
||||||
export class Utils {
|
export class Utils {
|
||||||
static isIpAddress = (address: string): boolean => IP_ADDRESS_REGEX.test(address)
|
static isIpAddress = (address: string): boolean => IP_ADDRESS_REGEX.test(address)
|
||||||
@@ -51,7 +59,7 @@ export class Utils {
|
|||||||
return [hoursAndMinutes, newDate].join(' ');
|
return [hoursAndMinutes, newDate].join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
static creatUniqueObjArrayByProp = (objArray, prop) => {
|
static createUniqueObjArrayByProp = (objArray, prop) => {
|
||||||
const map = new Map(objArray.map((item) => [item[prop], item])).values()
|
const map = new Map(objArray.map((item) => [item[prop], item])).values()
|
||||||
return Array.from(map);
|
return Array.from(map);
|
||||||
}
|
}
|
||||||
@@ -65,4 +73,24 @@ export class Utils {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static downloadFile = (data: string, filename: string, fileType: string) => {
|
||||||
|
const blob = new Blob([data], { type: fileType })
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = window.URL.createObjectURL(blob);
|
||||||
|
a.download = filename;
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
static exportToJson = (data: JSONValue, name) => {
|
||||||
|
Utils.downloadFile(JSON.stringify(data), `${name}.json`, 'text/json')
|
||||||
|
}
|
||||||
|
|
||||||
|
static getTimeFormatted = (time: Moment.MomentInput) => {
|
||||||
|
return Moment(time).utc().format('MM/DD/YYYY, h:mm:ss.SSS A')
|
||||||
|
}
|
||||||
|
|
||||||
|
static getNow = (format: string = 'MM/DD/YYYY, HH:mm:ss.SSS') => {
|
||||||
|
return Moment().format(format)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ $content-section-color: #f8f9fc;
|
|||||||
$blue-gray: #494677;
|
$blue-gray: #494677;
|
||||||
$light-gray: #8F9BB2;
|
$light-gray: #8F9BB2;
|
||||||
|
|
||||||
|
$text-font-family: Source Sans Pro, Lucida Grande, Tahoma, sans-serif;
|
||||||
|
|
||||||
:export {
|
:export {
|
||||||
mainBackgroundColor: $main-background-color;
|
mainBackgroundColor: $main-background-color;
|
||||||
headerBackgroundColor: $header-background-color;
|
headerBackgroundColor: $header-background-color;
|
||||||
@@ -25,4 +27,6 @@ $light-gray: #8F9BB2;
|
|||||||
failureColor: $failure-color;
|
failureColor: $failure-color;
|
||||||
blueGray: $blue-gray;
|
blueGray: $blue-gray;
|
||||||
lightGray: $light-gray;
|
lightGray: $light-gray;
|
||||||
|
contentSectionColor: $content-section-color;
|
||||||
|
textFontFamily: $text-font-family
|
||||||
}
|
}
|
||||||
|
|||||||
67736
ui/package-lock.json
generated
67736
ui/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,8 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@craco/craco": "^6.4.3",
|
"@craco/craco": "^6.4.3",
|
||||||
|
"@elastic/datemath": "^5.0.3",
|
||||||
|
"@elastic/eui": "^60.2.0",
|
||||||
"@emotion/react": "^11.9.0",
|
"@emotion/react": "^11.9.0",
|
||||||
"@emotion/styled": "^11.8.1",
|
"@emotion/styled": "^11.8.1",
|
||||||
"@mui/material": "^5.8.2",
|
"@mui/material": "^5.8.2",
|
||||||
@@ -23,7 +25,6 @@
|
|||||||
"mobx": "^6.6.0",
|
"mobx": "^6.6.0",
|
||||||
"moment": "^2.29.3",
|
"moment": "^2.29.3",
|
||||||
"node-fetch": "^3.2.4",
|
"node-fetch": "^3.2.4",
|
||||||
"sass": "^1.52.3",
|
|
||||||
"numeral": "^2.0.6",
|
"numeral": "^2.0.6",
|
||||||
"react": "^17.0.2",
|
"react": "^17.0.2",
|
||||||
"react-copy-to-clipboard": "^5.1.0",
|
"react-copy-to-clipboard": "^5.1.0",
|
||||||
@@ -35,8 +36,9 @@
|
|||||||
"react-syntax-highlighter": "^15.5.0",
|
"react-syntax-highlighter": "^15.5.0",
|
||||||
"react-toastify": "^8.2.0",
|
"react-toastify": "^8.2.0",
|
||||||
"redoc": "^2.0.0-rc.71",
|
"redoc": "^2.0.0-rc.71",
|
||||||
|
"sass": "^1.52.3",
|
||||||
"styled-components": "^5.3.5",
|
"styled-components": "^5.3.5",
|
||||||
"typescript": "^4.7.2",
|
"typescript": "^4.5.3",
|
||||||
"web-vitals": "^2.1.4",
|
"web-vitals": "^2.1.4",
|
||||||
"xml-formatter": "^2.6.1"
|
"xml-formatter": "^2.6.1"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import oasModalOpenAtom from './recoil/oasModalOpen/atom';
|
|||||||
import trafficStatsModalOpenAtom from "./recoil/trafficStatsModalOpen";
|
import trafficStatsModalOpenAtom from "./recoil/trafficStatsModalOpen";
|
||||||
import { OasModal } from '@up9/mizu-common';
|
import { OasModal } from '@up9/mizu-common';
|
||||||
import Api from './helpers/api';
|
import Api from './helpers/api';
|
||||||
import {ThemeProvider, StyledEngineProvider, createTheme} from '@mui/material';
|
import { ThemeProvider, StyledEngineProvider, createTheme } from '@mui/material';
|
||||||
import { TrafficStatsModal } from '@up9/mizu-common';
|
import { TrafficStatsModal } from '@up9/mizu-common';
|
||||||
|
|
||||||
const api = Api.getInstance()
|
const api = Api.getInstance()
|
||||||
@@ -36,7 +36,7 @@ const App = () => {
|
|||||||
openModal={oasModalOpen}
|
openModal={oasModalOpen}
|
||||||
handleCloseModal={() => setOasModalOpen(false)}
|
handleCloseModal={() => setOasModalOpen(false)}
|
||||||
/>}
|
/>}
|
||||||
<TrafficStatsModal isOpen={trafficStatsModalOpen} onClose={() => setTrafficStatsModalOpen(false)} getTrafficStatsDataApi={api.getTrafficStats}/>
|
<TrafficStatsModal isOpen={trafficStatsModalOpen} onClose={() => setTrafficStatsModalOpen(false)} getTrafficStatsDataApi={api.getTrafficStats} />
|
||||||
</div>
|
</div>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</StyledEngineProvider>
|
</StyledEngineProvider>
|
||||||
|
|||||||
@@ -116,8 +116,8 @@ export default class Api {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getTrafficStats = async () => {
|
getTrafficStats = async (startTimeMs, endTimeMs) => {
|
||||||
const response = await client.get("/status/trafficStats");
|
const response = await client.get("/status/trafficStats", {params: {startTimeMs, endTimeMs}});
|
||||||
return response.data;
|
return response.data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user