|
| 1 | +package logical |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "strconv" |
| 8 | + |
| 9 | + "github.com/docker/docker/api/types" |
| 10 | + "github.com/docker/docker/client" |
| 11 | + "github.com/jackc/pgx/v4" |
| 12 | + |
| 13 | + "gitlab.com/postgres-ai/database-lab/v3/internal/retrieval/engine/postgres/tools" |
| 14 | + "gitlab.com/postgres-ai/database-lab/v3/internal/retrieval/engine/postgres/tools/activity" |
| 15 | + "gitlab.com/postgres-ai/database-lab/v3/internal/retrieval/engine/postgres/tools/db" |
| 16 | + "gitlab.com/postgres-ai/database-lab/v3/pkg/config/global" |
| 17 | + "gitlab.com/postgres-ai/database-lab/v3/pkg/log" |
| 18 | +) |
| 19 | + |
| 20 | +const ( |
| 21 | + dleRetrieval = "dle_retrieval" |
| 22 | + |
| 23 | + // queryFieldsNum defines the expected number of fields in the query result. |
| 24 | + queryFieldsNum = 5 |
| 25 | + |
| 26 | + customRecordSeparator = "\\\\" |
| 27 | + |
| 28 | + // statQuery defines the query to get activity of the DLE retrieval. |
| 29 | + statQuery = `select |
| 30 | + coalesce(usename, ''), |
| 31 | + coalesce(extract(epoch from (clock_timestamp() - query_start)),0) as duration, |
| 32 | + left(regexp_replace(coalesce(query, ''), E'[ \\t\\r\\n]+', ' ', 'g'),100) as query_cut, |
| 33 | + coalesce(wait_event_type, ''), coalesce(wait_event, '') |
| 34 | + from pg_stat_activity |
| 35 | + where application_name = '` + dleRetrieval + "'" |
| 36 | +) |
| 37 | + |
| 38 | +func dbSourceActivity(ctx context.Context, dbCfg Connection) ([]activity.PGEvent, error) { |
| 39 | + connStr := db.ConnectionString(dbCfg.Host, strconv.Itoa(dbCfg.Port), dbCfg.Username, dbCfg.DBName, dbCfg.Password) |
| 40 | + |
| 41 | + querier, err := pgx.Connect(ctx, connStr) |
| 42 | + if err != nil { |
| 43 | + return nil, fmt.Errorf("failed to connect to DB: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + rows, err := querier.Query(ctx, statQuery) |
| 47 | + if err != nil { |
| 48 | + return nil, fmt.Errorf("failed to perform query to get DB activity: %w", err) |
| 49 | + } |
| 50 | + |
| 51 | + pgeList := make([]activity.PGEvent, 0) |
| 52 | + |
| 53 | + for rows.Next() { |
| 54 | + var pge activity.PGEvent |
| 55 | + if err := rows.Scan(&pge.User, &pge.Duration, &pge.Query, &pge.WaitEventType, &pge.WaitEvent); err != nil { |
| 56 | + return nil, fmt.Errorf("failed to scan the next row to the PG Activity result set: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + pgeList = append(pgeList, pge) |
| 60 | + } |
| 61 | + |
| 62 | + if err := rows.Err(); err != nil { |
| 63 | + return nil, err |
| 64 | + } |
| 65 | + |
| 66 | + return pgeList, nil |
| 67 | +} |
| 68 | + |
| 69 | +func pgContainerActivity(ctx context.Context, docker *client.Client, containerID string, db global.Database) ([]activity.PGEvent, error) { |
| 70 | + ins, err := docker.ContainerInspect(ctx, containerID) |
| 71 | + if err != nil { |
| 72 | + return nil, fmt.Errorf("failed to check PG container activity: %w", err) |
| 73 | + } |
| 74 | + |
| 75 | + if ins.State.Health.Status != types.Healthy { |
| 76 | + log.Dbg("Target container is not ready yet: ", ins.State.Health.Status) |
| 77 | + return []activity.PGEvent{}, nil |
| 78 | + } |
| 79 | + |
| 80 | + activityCmd := []string{"psql", "-U", db.User(), "-d", db.Name(), "--record-separator='" + customRecordSeparator + "'", "-XAtc", statQuery} |
| 81 | + |
| 82 | + log.Msg("Running activity command: ", activityCmd) |
| 83 | + |
| 84 | + execCfg := types.ExecConfig{ |
| 85 | + Tty: true, |
| 86 | + Cmd: activityCmd, |
| 87 | + } |
| 88 | + |
| 89 | + out, err := tools.ExecCommandWithOutput(ctx, docker, containerID, execCfg) |
| 90 | + |
| 91 | + if err != nil { |
| 92 | + log.Dbg("Activity command failed:", out) |
| 93 | + return nil, err |
| 94 | + } |
| 95 | + |
| 96 | + return parseStatActivity(out), nil |
| 97 | +} |
| 98 | + |
| 99 | +func parseStatActivity(queryResult string) []activity.PGEvent { |
| 100 | + activities := make([]activity.PGEvent, 0) |
| 101 | + |
| 102 | + // Cut out line breaks from the psql output and split records by the custom separator. |
| 103 | + lines := bytes.Split(bytes.ReplaceAll([]byte(queryResult), []byte("\r\n"), []byte("")), []byte(customRecordSeparator)) |
| 104 | + |
| 105 | + for _, line := range lines { |
| 106 | + byteLine := bytes.TrimSpace(line) |
| 107 | + |
| 108 | + if len(byteLine) == 0 { |
| 109 | + continue |
| 110 | + } |
| 111 | + |
| 112 | + fields := bytes.Split(byteLine, []byte("|")) |
| 113 | + |
| 114 | + if fieldsLen := len(fields); fieldsLen != queryFieldsNum { |
| 115 | + log.Dbg(fmt.Sprintf("an invalid activity line given: %d fields are available, but requires %d", |
| 116 | + fieldsLen, queryFieldsNum), fields) |
| 117 | + continue |
| 118 | + } |
| 119 | + |
| 120 | + var queryDuration float64 |
| 121 | + |
| 122 | + if durationString := string(fields[1]); durationString != "" { |
| 123 | + parsedDuration, err := strconv.ParseFloat(durationString, 64) |
| 124 | + if err != nil { |
| 125 | + log.Dbg("Cannot parse query duration:", durationString) |
| 126 | + } |
| 127 | + |
| 128 | + queryDuration = parsedDuration |
| 129 | + } |
| 130 | + |
| 131 | + activities = append(activities, activity.PGEvent{ |
| 132 | + User: string(fields[0]), |
| 133 | + Duration: queryDuration, |
| 134 | + Query: string(fields[2]), |
| 135 | + WaitEventType: string(fields[3]), |
| 136 | + WaitEvent: string(fields[4]), |
| 137 | + }) |
| 138 | + } |
| 139 | + |
| 140 | + return activities |
| 141 | +} |
0 commit comments