Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion pkg/cli/initconfig/cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ func createOrUpdateMongodbIndex(ctx context.Context) {
commonrepo.NewEnvInfoColl(),
commonrepo.NewApprovalTicketColl(),
commonrepo.NewWorkflowTaskRevertColl(),
commonrepo.NewTerminalSessionColl(),
commonrepo.NewTerminalCommandColl(),

// msg queue
commonrepo.NewMsgQueueCommonColl(),
Expand Down Expand Up @@ -304,7 +306,7 @@ func createBuiltinApplicationFieldDefinitions() error {
{Key: "update_time", Name: "更新时间", Type: aslanconfig.ApplicationCustomFieldTypeDatetime, ShowInList: true, Source: aslanconfig.ApplicationFieldSourceBuiltin, Description: "业务服务的更新时间"},
}

// Upsert per key to be idempotent. Keep user-changed attributes for custom fields; for built-ins we only enforce Source="builtin" and Type.
// Upsert per key to be idempotent. Keep user-changed attributes for custom fields; for built-ins we only enforce Source="builtin", Type, Name, Description, and Required.
for i := range builtin {
b := builtin[i]
existing, err := coll.GetByKey(ctx, b.Key)
Expand Down
116 changes: 116 additions & 0 deletions pkg/microservice/aslan/core/common/repository/models/terminal_audit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package models

import "go.mongodb.org/mongo-driver/bson/primitive"

type TerminalSessionType string

const (
TerminalSessionTypeSSH TerminalSessionType = "ssh"
TerminalSessionTypePodExec TerminalSessionType = "podexec"
TerminalSessionTypeWorkflowDebug TerminalSessionType = "workflow_debug"
)

type TerminalSessionStatus string

const (
TerminalSessionStatusRunning TerminalSessionStatus = "running"
TerminalSessionStatusFinished TerminalSessionStatus = "finished"
TerminalSessionStatusAborted TerminalSessionStatus = "aborted"
TerminalSessionStatusFailed TerminalSessionStatus = "failed"
)

type TerminalSession struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
SessionID string `bson:"session_id" json:"session_id"`
SessionType TerminalSessionType `bson:"session_type" json:"session_type"`
Status TerminalSessionStatus `bson:"status" json:"status"`
UserID string `bson:"user_id" json:"user_id"`
Username string `bson:"username" json:"username"`
Account string `bson:"account" json:"account"`
ProjectName string `bson:"project_name" json:"project_name"`
EnvName string `bson:"env_name" json:"env_name"`
ServiceName string `bson:"service_name" json:"service_name"`
WorkflowName string `bson:"workflow_name" json:"workflow_name"`
JobName string `bson:"job_name" json:"job_name"`
TaskID int64 `bson:"task_id" json:"task_id"`
TargetName string `bson:"target_name" json:"target_name"`
Protocol string `bson:"protocol" json:"protocol"`
RemoteAddr string `bson:"remote_addr" json:"remote_addr"`
LoginAccount string `bson:"login_account" json:"login_account"`
HostID string `bson:"host_id" json:"host_id"`
HostName string `bson:"host_name" json:"host_name"`
HostIP string `bson:"host_ip" json:"host_ip"`
ClusterID string `bson:"cluster_id" json:"cluster_id"`
Namespace string `bson:"namespace" json:"namespace"`
PodName string `bson:"pod_name" json:"pod_name"`
ContainerName string `bson:"container_name" json:"container_name"`
ClientIP string `bson:"client_ip" json:"client_ip"`
UserAgent string `bson:"user_agent" json:"user_agent"`
StartedAt int64 `bson:"started_at" json:"started_at"`
EndedAt int64 `bson:"ended_at" json:"ended_at"`
DurationSeconds int64 `bson:"duration_seconds" json:"duration_seconds"`
LastActivityAt int64 `bson:"last_activity_at" json:"last_activity_at"`
CommandCount int64 `bson:"command_count" json:"command_count"`
StorageID string `bson:"storage_id" json:"storage_id"`
Bucket string `bson:"bucket" json:"bucket"`
ObjectKey string `bson:"object_key" json:"object_key"`
FileSize int64 `bson:"file_size" json:"file_size"`
ErrorMessage string `bson:"error_message" json:"error_message"`
CreatedAt int64 `bson:"created_at" json:"created_at"`
UpdatedAt int64 `bson:"updated_at" json:"updated_at"`
}

func (TerminalSession) TableName() string {
return "terminal_session"
}

type TerminalCommand struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"`
SessionID string `bson:"session_id" json:"session_id"`
Seq int64 `bson:"seq" json:"seq"`
Command string `bson:"command" json:"command"`
RiskLevel string `bson:"risk_level" json:"risk_level"`
UserID string `bson:"user_id" json:"user_id"`
Username string `bson:"username" json:"username"`
Account string `bson:"account" json:"account"`
ProjectName string `bson:"project_name" json:"project_name"`
EnvName string `bson:"env_name" json:"env_name"`
TargetName string `bson:"target_name" json:"target_name"`
Protocol string `bson:"protocol" json:"protocol"`
RemoteAddr string `bson:"remote_addr" json:"remote_addr"`
LoginAccount string `bson:"login_account" json:"login_account"`
TimeOffsetMS int64 `bson:"time_offset_ms" json:"time_offset_ms"`
CreatedAt int64 `bson:"created_at" json:"created_at"`
}

func (TerminalCommand) TableName() string {
return "terminal_command"
}

type TerminalSessionListArgs struct {
Status string `form:"status" json:"status"`
SessionType string `form:"sessionType" json:"sessionType"`
ProjectName string `form:"projectName" json:"projectName"`
EnvName string `form:"envName" json:"envName"`
ServiceName string `form:"serviceName" json:"serviceName"`
Username string `form:"username" json:"username"`
TargetName string `form:"targetName" json:"targetName"`
RemoteAddr string `form:"remoteAddr" json:"remoteAddr"`
StartTime int64 `form:"startTime" json:"startTime"`
EndTime int64 `form:"endTime" json:"endTime"`
PageNum int64 `form:"pageNum" json:"pageNum"`
PageSize int64 `form:"pageSize" json:"pageSize"`
}

type TerminalCommandListArgs struct {
SessionID string `form:"sessionID" json:"sessionID"`
ProjectName string `form:"projectName" json:"projectName"`
Username string `form:"username" json:"username"`
TargetName string `form:"targetName" json:"targetName"`
RemoteAddr string `form:"remoteAddr" json:"remoteAddr"`
Command string `form:"command" json:"command"`
StartTime int64 `form:"startTime" json:"startTime"`
EndTime int64 `form:"endTime" json:"endTime"`
PageNum int64 `form:"pageNum" json:"pageNum"`
PageSize int64 `form:"pageSize" json:"pageSize"`
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package mongodb

import (
"context"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"

"github.com/koderover/zadig/v2/pkg/microservice/aslan/config"
"github.com/koderover/zadig/v2/pkg/microservice/aslan/core/common/repository/models"
mongotool "github.com/koderover/zadig/v2/pkg/tool/mongo"
)

type TerminalCommandColl struct {
*mongo.Collection

coll string
}

func NewTerminalCommandColl() *TerminalCommandColl {
name := models.TerminalCommand{}.TableName()
return &TerminalCommandColl{
Collection: mongotool.Database(config.MongoDatabase()).Collection(name),
coll: name,
}
}

func (c *TerminalCommandColl) GetCollectionName() string {
return c.coll
}

func (c *TerminalCommandColl) EnsureIndex(ctx context.Context) error {
indexes := []mongo.IndexModel{
{
Keys: bson.D{{Key: "session_id", Value: 1}, {Key: "seq", Value: 1}},
Options: options.Index().SetUnique(true),
},
{
Keys: bson.D{{Key: "project_name", Value: 1}, {Key: "created_at", Value: -1}},
Options: options.Index().SetUnique(false),
},
{
Keys: bson.D{{Key: "username", Value: 1}, {Key: "created_at", Value: -1}},
Options: options.Index().SetUnique(false),
},
{
Keys: bson.D{{Key: "command", Value: "text"}},
Options: options.Index().SetUnique(false),
},
}
_, err := c.Indexes().CreateMany(ctx, indexes, mongotool.CreateIndexOptions(ctx))
return err
}

func (c *TerminalCommandColl) Create(command *models.TerminalCommand) error {
if command == nil {
return nil
}
_, err := c.InsertOne(context.TODO(), command)
return err
}

func (c *TerminalCommandColl) CreateMany(commands []*models.TerminalCommand) error {
if len(commands) == 0 {
return nil
}
docs := make([]interface{}, 0, len(commands))
for _, command := range commands {
if command == nil {
continue
}
docs = append(docs, command)
}
if len(docs) == 0 {
return nil
}
_, err := c.InsertMany(context.TODO(), docs)
return err
}

func (c *TerminalCommandColl) List(args *models.TerminalCommandListArgs) ([]*models.TerminalCommand, int64, error) {
resp := make([]*models.TerminalCommand, 0)
query := bson.M{}
if args != nil {
if args.SessionID != "" {
query["session_id"] = args.SessionID
}
if args.ProjectName != "" {
query["project_name"] = buildRegexQuery(args.ProjectName)
}
if args.Username != "" {
query["username"] = buildRegexQuery(args.Username)
}
if args.TargetName != "" {
query["target_name"] = buildRegexQuery(args.TargetName)
}
if args.RemoteAddr != "" {
query["remote_addr"] = buildRegexQuery(args.RemoteAddr)
}
if args.Command != "" {
query["command"] = buildRegexQuery(args.Command)
}
if args.StartTime > 0 || args.EndTime > 0 {
timeQuery := bson.M{}
if args.StartTime > 0 {
timeQuery["$gte"] = args.StartTime
}
if args.EndTime > 0 {
timeQuery["$lte"] = args.EndTime
}
query["created_at"] = timeQuery
}
}

opts := options.Find().SetSort(bson.D{{Key: "created_at", Value: -1}, {Key: "seq", Value: -1}})
if args != nil && args.PageNum > 0 && args.PageSize > 0 {
opts.SetSkip((args.PageNum - 1) * args.PageSize).SetLimit(args.PageSize)
}
cursor, err := c.Find(context.TODO(), query, opts)
if err != nil {
return nil, 0, err
}
defer cursor.Close(context.TODO())

if err := cursor.All(context.TODO(), &resp); err != nil {
return nil, 0, err
}
total, err := c.CountDocuments(context.TODO(), query)
return resp, total, err
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mongodb

import (
"regexp"

"go.mongodb.org/mongo-driver/bson"
)

func buildRegexQuery(value string) bson.M {
return bson.M{"$regex": regexp.QuoteMeta(value)}
}
Loading
Loading