Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: impl GetTaskRunSession for pg (#12852)
p0ny8cf18b2e3211
diff --git a/backend/api/v1/acl_config.go b/backend/api/v1/acl_config.goindex 250f28b774..8737d7c932 100644--- a/backend/api/v1/acl_config.go+++ b/backend/api/v1/acl_config.go@@ -130,6 +130,7 @@ var methodPermissionMap = map[string]iam.Permission{v1pb.RolloutService_PreviewRollout_FullMethodName: iam.PermissionRolloutsPreview,v1pb.RolloutService_ListTaskRuns_FullMethodName: iam.PermissionTaskRunsList,v1pb.RolloutService_GetTaskRunLog_FullMethodName: iam.PermissionTaskRunsList,+ v1pb.RolloutService_GetTaskRunSession_FullMethodName: iam.PermissionTaskRunsList,v1pb.PlanService_ListPlans_FullMethodName: iam.PermissionPlansList,v1pb.PlanService_SearchPlans_FullMethodName: iam.PermissionPlansGet,v1pb.PlanService_GetPlan_FullMethodName: iam.PermissionPlansGet,diff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.goindex 58bbaaaa0b..161c3b01e7 100644--- a/backend/api/v1/rollout_service.go+++ b/backend/api/v1/rollout_service.go@@ -2,6 +2,7 @@ package v1import ("context"+ "database/sql""fmt""log/slog""sort"@@ -12,6 +13,7 @@ import ("google.golang.org/grpc/codes""google.golang.org/grpc/status""google.golang.org/protobuf/testing/protocmp"+ "google.golang.org/protobuf/types/known/timestamppb""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"@@ -23,6 +25,7 @@ import ("github.com/bytebase/bytebase/backend/component/webhook"enterprise "github.com/bytebase/bytebase/backend/enterprise/api"api "github.com/bytebase/bytebase/backend/legacyapi"+ "github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/store""github.com/bytebase/bytebase/backend/utils"storepb "github.com/bytebase/bytebase/proto/generated-go/store"@@ -251,6 +254,154 @@ func (s *RolloutService) GetTaskRunLog(ctx context.Context, request *v1pb.GetTasreturn convertToTaskRunLog(request.Parent, logs), nil}+func (s *RolloutService) GetTaskRunSession(ctx context.Context, request *v1pb.GetTaskRunSessionRequest) (*v1pb.TaskRunSession, error) {+ _, _, _, taskUID, taskRunUID, err := common.GetProjectIDRolloutIDStageIDTaskIDTaskRunID(request.Parent)+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, "failed to get task run uid, error: %v", err)+ }+ connIDAny, ok := s.stateCfg.TaskRunConnectionID.Load(taskRunUID)+ if !ok {+ return nil, status.Errorf(codes.FailedPrecondition, "connection id not found for task run %d", taskRunUID)+ }+ connID, ok := connIDAny.(string)+ if !ok {+ return nil, status.Errorf(codes.Internal, "expect connection id to be of type string but found %T", connIDAny)+ }++ task, err := s.store.GetTaskV2ByID(ctx, taskUID)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to get task, error: %v", err)+ }++ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to get instance, error: %v", err)+ }++ driver, err := s.dbFactory.GetAdminDatabaseDriver(ctx, instance, nil, db.ConnectionContext{})+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to get driver, error: %v", err)+ }++ session, err := getSession(ctx, instance.Engine, driver.GetDB(), connID)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to get session, error: %v", err)+ }++ session.Name = request.Parent + "/session"++ return session, nil+}++func getSession(ctx context.Context, engine storepb.Engine, db *sql.DB, connID string) (*v1pb.TaskRunSession, error) {+ switch engine {+ case storepb.Engine_POSTGRES:+ query := `+ SELECT+ pid,+ query,+ state,+ wait_event_type,+ wait_event,+ datname,+ usename,+ application_name,+ client_addr,+ client_port,+ backend_start,+ xact_start,+ query_start+ FROM (+ SELECT+ 1 AS lvl,+ pid,+ query,+ state,+ wait_event_type,+ wait_event,+ datname,+ usename,+ application_name,+ client_addr,+ client_port,+ backend_start,+ xact_start,+ query_start+ FROM+ pg_stat_activity+ WHERE pid = $1+ UNION+ SELECT+ 2 AS lvl,+ pid,+ query,+ state,+ wait_event_type,+ wait_event,+ datname,+ usename,+ application_name,+ client_addr,+ client_port,+ backend_start,+ xact_start,+ query_start+ FROM+ pg_stat_activity+ WHERE pid = ANY(pg_blocking_pids($1))+ ORDER BY lvl, pid+ ) t+ `+ rows, err := db.QueryContext(ctx, query, connID)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to query rows")+ }+ defer rows.Close()++ ss := &v1pb.TaskRunSession_Postgres{}+ for rows.Next() {+ var s v1pb.TaskRunSession_Postgres_Session++ var bs, xs, qs time.Time+ if err := rows.Scan(+ &s.Pid,+ &s.Query,+ &s.State,+ &s.WaitEventType,+ &s.WaitEvent,+ &s.Datname,+ &s.Usename,+ &s.ApplicationName,+ &s.ClientAddr,+ &s.ClientPort,+ &bs,+ &xs,+ &qs,+ ); err != nil {+ return nil, errors.Wrapf(err, "failed to scan")+ }++ s.BackendStart = timestamppb.New(bs)+ s.XactStart = timestamppb.New(xs)+ s.QueryStart = timestamppb.New(qs)++ ss.Sessions = append(ss.Sessions, &s)+ }++ if err := rows.Err(); err != nil {+ return nil, errors.Wrapf(err, "failed to scan rows")+ }++ return &v1pb.TaskRunSession{+ Session: &v1pb.TaskRunSession_Postgres_{+ Postgres: ss,+ },+ }, nil+ default:+ return nil, errors.Errorf("unsupported engine type %v", engine.String())+ }+}+// BatchRunTasks runs tasks in batch.func (s *RolloutService) BatchRunTasks(ctx context.Context, request *v1pb.BatchRunTasksRequest) (*v1pb.BatchRunTasksResponse, error) {if len(request.Tasks) == 0 {diff --git a/backend/component/state/state.go b/backend/component/state/state.goindex f67488c48d..0e38d31d40 100644--- a/backend/component/state/state.go+++ b/backend/component/state/state.go@@ -31,6 +31,9 @@ type State struct {// TaskRunExecutionStatuses is the map from task run ID to task run execution status.TaskRunExecutionStatuses sync.Map // map[taskRunID]TaskRunExecutionStatus+ // TaskRunConnectionID is the map from task run ID to the connection id of the connection to the database.+ TaskRunConnectionID sync.Map // map[taskRunID]string+// RunningTaskRuns is the set of running taskruns.RunningTaskRuns sync.Map // map[taskRunID]bool// RunningTaskRunsCancelFunc is the cancelFunc of running taskruns.diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex 7bb4f80a72..694f121477 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -356,6 +356,10 @@ type ExecuteOptions struct {CreateDatabase boolUpdateExecutionStatus func(*v1pb.TaskRun_ExecutionDetail)CreateTaskRunLog func(time.Time, *storepb.TaskRunLog) error++ // Record the connection id first before executing.+ SetConnectionID func(id string)+ DeleteConnectionID func()}func (o *ExecuteOptions) LogSchemaDumpStart() {diff --git a/backend/plugin/db/pg/pg.go b/backend/plugin/db/pg/pg.goindex a5f21db0e6..f65a1df603 100644--- a/backend/plugin/db/pg/pg.go+++ b/backend/plugin/db/pg/pg.go@@ -419,13 +419,25 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.ExeoriginalIndex = []int32{0}}- if isPlsql {- conn, err := driver.db.Conn(ctx)- if err != nil {- return 0, errors.Wrapf(err, "failed to get connection")+ conn, err := driver.db.Conn(ctx)+ if err != nil {+ return 0, errors.Wrapf(err, "failed to get connection")+ }+ defer conn.Close()++ if opts.SetConnectionID != nil {+ var pid string+ if err := conn.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil {+ return 0, errors.Wrapf(err, "failed to get connection id")}- defer conn.Close()+ opts.SetConnectionID(pid)+ if opts.DeleteConnectionID != nil {+ defer opts.DeleteConnectionID()+ }+ }++ if isPlsql {// USE SET SESSION ROLE to set the role for the current session.if _, err := conn.ExecContext(ctx, fmt.Sprintf("SET SESSION ROLE '%s'", owner)); err != nil {return 0, errors.Wrapf(err, "failed to set role to database owner %q", owner)@@ -441,11 +453,6 @@ func (driver *Driver) Execute(ctx context.Context, statement string, opts db.Exe}totalRowsAffected := int64(0)- conn, err := driver.db.Conn(ctx)- if err != nil {- return 0, errors.Wrapf(err, "failed to get connection")- }- defer conn.Close()totalCommands := len(commands)if totalCommands > 0 {diff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex 8e37e0db52..f07c0f30ef 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -218,6 +218,13 @@ func executeMigration(var migrationID stringopts := db.ExecuteOptions{}+ opts.SetConnectionID = func(id string) {+ stateCfg.TaskRunConnectionID.Store(taskRunUID, id)+ }+ opts.DeleteConnectionID = func() {+ stateCfg.TaskRunConnectionID.Delete(taskRunUID)+ }+if profile.ExecuteDetail && stateCfg != nil {switch task.Type {case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseDataUpdate: