-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: support postgres query hook #51
Merged
+413
−14
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
/* | ||
Copyright © 2022 CFC4N <[email protected]> | ||
|
||
*/ | ||
package cmd | ||
|
||
import ( | ||
"context" | ||
"ecapture/user" | ||
"log" | ||
"os" | ||
"os/signal" | ||
"syscall" | ||
|
||
"github.com/spf13/cobra" | ||
) | ||
|
||
var postgresConfig = user.NewPostgresConfig() | ||
|
||
//postgres Cmd represents the postgres command | ||
var postgresCmd = &cobra.Command{ | ||
Use: "postgres", | ||
Short: "capture sql queries from postgres 10+.", | ||
Run: postgresCommandFunc, | ||
} | ||
|
||
func init() { | ||
postgresCmd.PersistentFlags().StringVarP(&postgresConfig.PostgresPath, "postgres", "m", "/usr/bin/postgres", "postgres binary file path, use to hook") | ||
postgresCmd.PersistentFlags().StringVarP(&postgresConfig.FuncName, "funcname", "f", "", "function name to hook") | ||
rootCmd.AddCommand(postgresCmd) | ||
} | ||
|
||
// postgres CommandFunc executes the "psql" command. | ||
func postgresCommandFunc(command *cobra.Command, args []string) { | ||
stopper := make(chan os.Signal, 1) | ||
signal.Notify(stopper, os.Interrupt, syscall.SIGTERM) | ||
ctx, cancelFun := context.WithCancel(context.TODO()) | ||
|
||
mod := user.GetModuleByName(user.MODULE_NAME_POSTGRES) | ||
|
||
logger := log.Default() | ||
|
||
logger.Printf("start to run %s module", mod.Name()) | ||
|
||
// save global config | ||
gConf, e := getGlobalConf(command) | ||
if e != nil { | ||
logger.Fatal(e) | ||
os.Exit(1) | ||
} | ||
postgresConfig.Pid = gConf.Pid | ||
postgresConfig.Debug = gConf.Debug | ||
postgresConfig.IsHex = gConf.IsHex | ||
|
||
log.Printf("pid info: %d", os.Getpid()) | ||
//bc.Pid = globalFlags.Pid | ||
if e := postgresConfig.Check(); e != nil { | ||
logger.Fatal(e) | ||
os.Exit(1) | ||
} | ||
// init | ||
err := mod.Init(ctx, logger, postgresConfig) | ||
if err != nil { | ||
logger.Fatal(err) | ||
os.Exit(1) | ||
} | ||
|
||
// 加载ebpf,挂载到hook点上,开始监听 | ||
go func(module user.IModule) { | ||
err := module.Run() | ||
if err != nil { | ||
logger.Fatalf("%v", err) | ||
} | ||
}(mod) | ||
<-stopper | ||
cancelFun() | ||
os.Exit(0) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
#include "ecapture.h" | ||
|
||
struct data_t { | ||
u64 pid; | ||
u64 timestamp; | ||
char query[MAX_DATA_SIZE_POSTGRES]; | ||
char comm[TASK_COMM_LEN]; | ||
}; | ||
|
||
struct | ||
{ | ||
__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY); | ||
} events SEC(".maps"); | ||
|
||
// https://github.com/postgres/postgres/blob/7b7ed046cb2ad9f6efac90380757d5977f0f563f/src/backend/tcop/postgres.c#L987-L992 | ||
// hook function exec_simple_query | ||
// versions 10 - now | ||
// static void exec_simple_query(const char *query_string) | ||
SEC("uprobe/exec_simple_query") | ||
int postgres_query(struct pt_regs *ctx) { | ||
|
||
u64 current_pid_tgid = bpf_get_current_pid_tgid(); | ||
u32 pid = current_pid_tgid >> 32; | ||
|
||
#ifndef KERNEL_LESS_5_2 | ||
// if target_ppid is 0 then we target all pids | ||
if (target_pid != 0 && target_pid != pid) { | ||
return 0; | ||
} | ||
#endif | ||
|
||
struct data_t data = {}; | ||
data.pid = pid; // only process id | ||
data.timestamp = bpf_ktime_get_ns(); | ||
|
||
char *sql_string= (char *)PT_REGS_PARM1(ctx); | ||
bpf_get_current_comm(&data.comm, sizeof(data.comm)); | ||
bpf_probe_read(&data.query, sizeof(data.query), sql_string); | ||
bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, &data, sizeof(data)); | ||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/* | ||
Copyright © 2022 CFC4N <[email protected]> | ||
|
||
*/ | ||
package user | ||
|
||
import ( | ||
"os" | ||
"strings" | ||
|
||
"github.com/pkg/errors" | ||
) | ||
|
||
type PostgresConfig struct { | ||
eConfig | ||
PostgresPath string `json:"postgresPath"` | ||
FuncName string `json:"funcName"` | ||
} | ||
|
||
func NewPostgresConfig() *PostgresConfig { | ||
config := &PostgresConfig{} | ||
return config | ||
} | ||
|
||
func (this *PostgresConfig) Check() error { | ||
|
||
if this.PostgresPath == "" || len(strings.TrimSpace(this.PostgresPath)) <= 0 { | ||
return errors.New("Postgres path cant be null.") | ||
} | ||
|
||
_, e := os.Stat(this.PostgresPath) | ||
if e != nil { | ||
return e | ||
} | ||
|
||
this.FuncName = "exec_simple_query" | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ import ( | |
"bytes" | ||
"encoding/binary" | ||
"fmt" | ||
|
||
"golang.org/x/sys/unix" | ||
) | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
/* | ||
Copyright © 2022 CFC4N <[email protected]> | ||
|
||
*/ | ||
package user | ||
|
||
import ( | ||
"bytes" | ||
"encoding/binary" | ||
"fmt" | ||
|
||
"golang.org/x/sys/unix" | ||
) | ||
|
||
/* | ||
u64 pid; | ||
u64 timestamp; | ||
char query[MAX_DATA_SIZE]; | ||
char comm[TASK_COMM_LEN]; | ||
*/ | ||
const POSTGRES_MAX_DATA_SIZE = 256 | ||
|
||
type postgresEvent struct { | ||
module IModule | ||
Pid uint64 | ||
Timestamp uint64 | ||
query [POSTGRES_MAX_DATA_SIZE]uint8 | ||
comm [16]uint8 | ||
} | ||
|
||
func (this *postgresEvent) Decode(payload []byte) (err error) { | ||
buf := bytes.NewBuffer(payload) | ||
if err = binary.Read(buf, binary.LittleEndian, &this.Pid); err != nil { | ||
return | ||
} | ||
if err = binary.Read(buf, binary.LittleEndian, &this.Timestamp); err != nil { | ||
return | ||
} | ||
if err = binary.Read(buf, binary.LittleEndian, &this.query); err != nil { | ||
return | ||
} | ||
if err = binary.Read(buf, binary.LittleEndian, &this.comm); err != nil { | ||
return | ||
} | ||
return nil | ||
} | ||
|
||
func (this *postgresEvent) String() string { | ||
s := fmt.Sprintf(fmt.Sprintf(" PID: %d, Comm: %s, Time: %d, Query: %s", this.Pid, this.comm, this.Timestamp, unix.ByteSliceToString((this.query[:])))) | ||
return s | ||
} | ||
|
||
func (this *postgresEvent) StringHex() string { | ||
s := fmt.Sprintf(fmt.Sprintf(" PID: %d, Comm: %s, Time: %d, Query: %s", this.Pid, this.comm, this.Timestamp, unix.ByteSliceToString((this.query[:])))) | ||
return s | ||
} | ||
|
||
func (this *postgresEvent) SetModule(module IModule) { | ||
this.module = module | ||
} | ||
|
||
func (this *postgresEvent) Module() IModule { | ||
return this.module | ||
} | ||
|
||
func (this *postgresEvent) Clone() IEventStruct { | ||
return new(postgresEvent) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what is the difference between
exec_simple_query
andexec_parse_message
, Why notexec_parse_message
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
exec_parse_message called in exec_simple_query.