appmesh

package
v0.0.0-...-23d8a47 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package appmesh provides TCP communication functionality.

Index

Constants

View Source
const (
	DEFAULT_HTTP_URI             = "https://localhost:6060"
	DEFAULT_TCP_URI              = "localhost:6059"
	DEFAULT_CLIENT_CERT_FILE     = "/opt/appmesh/ssl/client.pem"
	DEFAULT_CLIENT_CERT_KEY_FILE = "/opt/appmesh/ssl/client-key.pem"
	DEFAULT_CA_FILE              = "/opt/appmesh/ssl/ca.pem"

	HTTP_USER_AGENT_HEADER_NAME        = "User-Agent"
	HTTP_USER_AGENT                    = "appmesh/golang"
	HTTP_USER_AGENT_TCP                = "appmesh/golang/tcp"
	HTTP_HEADER_KEY_X_SEND_FILE_SOCKET = "X-Send-File-Socket"
	HTTP_HEADER_KEY_X_RECV_FILE_SOCKET = "X-Recv-File-Socket"
	HTTP_HEADER_KEY_File_Path          = "X-File-Path"

	DEFAULT_TOKEN_EXPIRE_SECONDS = 7 * (60 * 60 * 24) // default 7 day(s)

	DEFAULT_JWT_AUDIENCE = "appmesh-service"
)
View Source
const (
	TCP_MESSAGE_HEADER_LENGTH = 8                  // 8 bytes TCP message header: 4 bytes Magic number + 4 bytes Body length
	TCP_MESSAGE_MAGIC         = uint32(0x07C707F8) // 4-byte magic number used to identify and validate TCP messages.
	TCP_CHUNK_BLOCK_SIZE      = 16*1024 - 256      // Target block size: 16KB, with 256 bytes reserved for protocol overhead or alignment.
	TCP_MAX_BLOCK_SIZE        = 1024 * 1024 * 100  // Maximum allowed block size: 100 MB
)
View Source
const TCP_CONNECT_TIMEOUT_SECONDS = 30

Variables

This section is empty.

Functions

func GetFileAttributes

func GetFileAttributes(filePath string) (map[string]string, error)

GetFileAttributes returns a map with file attributes: mode, user ID, and group ID.

func IsFileExist

func IsFileExist(path string) bool

IsFileExist checks if the file at the given path exists.

func LoadCA

func LoadCA(caPath string) (*x509.CertPool, error)

LoadCA loads a CA certificate, either from a single file or from a directory of certificates.

func LoadCACertificate

func LoadCACertificate(certFile string) (*x509.CertPool, error)

LoadCACertificate loads a single CA certificate from a file and returns a CertPool containing it.

func LoadCACertificates

func LoadCACertificates(certDir string) (*x509.CertPool, error)

LoadCACertificates loads multiple CA certificates from a directory.

func LoadCertificatePair

func LoadCertificatePair(pem, key string) (tls.Certificate, error)

LoadCertificatePair loads a TLS certificate and key from the given PEM and key file paths.

func MergeStringMaps

func MergeStringMaps(map1, map2 map[string]string)

MergeStringMaps merges two string maps, with values from the second map overwriting those in the first.

func ParseURL

func ParseURL(input string) (*url.URL, error)

ParseURL parses the given input string into a URL object. It ensures that the URL has a valid scheme and host, adding "https://" as the default scheme if necessary.

func SetFileAttributes

func SetFileAttributes(filePath string, headers http.Header) error

SetFileAttributes applies file mode and ownership (UID, GID) to a given file based on HTTP headers.

func SetTcpNoDelay

func SetTcpNoDelay(conn net.Conn) error

SetTcpNoDelay disables Nagle's algorithm for the given net.Conn, and supports both TCP and TLS connections.

Types

type AppMeshClient

type AppMeshClient struct {
	Proxy ClientRequester
	// contains filtered or unexported fields
}

AppMeshClient interacts with the REST server using REST API requests.

func NewHttpClient

func NewHttpClient(options Option) *AppMeshClient

NewHttpClient creates a new AppMeshClient instance for interacting with a REST server.

func (*AppMeshClient) AddApp

func (r *AppMeshClient) AddApp(app Application) (*Application, error)

AddApp adds an application.

func (*AppMeshClient) Authenticate

func (r *AppMeshClient) Authenticate(jwtToken string, permission string, audience string) (bool, error)

Authenticate authenticates the user with an existing JWT token and optional permission check.

func (*AppMeshClient) DisableApp

func (r *AppMeshClient) DisableApp(appName string) error

DisableApp disables an application.

func (*AppMeshClient) DisableTotp

func (r *AppMeshClient) DisableTotp() (bool, error)

DisableTotp disables TOTP for the user.

func (*AppMeshClient) DownloadFile

func (r *AppMeshClient) DownloadFile(remoteFile, localFile string, applyFileAttributes bool) error

DownloadFile downloads a file from the server.

func (*AppMeshClient) EnableApp

func (r *AppMeshClient) EnableApp(appName string) error

EnableApp enables an application.

func (*AppMeshClient) GetAppOutput

func (r *AppMeshClient) GetAppOutput(appName string, stdoutPosition int64, stdoutIndex int, stdoutMaxsize int, processUuid string) AppOutput

GetAppOutput retrieves the stdout of an application.

func (*AppMeshClient) GetTotpSecret

func (r *AppMeshClient) GetTotpSecret() (string, error)

GetTotpSecret retrieves the TOTP secret for the user.

func (*AppMeshClient) Login

func (r *AppMeshClient) Login(user string, password string, totpCode string, timeoutSeconds int, audience string) (bool, string, error)

Login authenticates the user with username and password.

func (*AppMeshClient) Logoff

func (r *AppMeshClient) Logoff() (bool, error)

Logoff logs the user off from the server.

func (*AppMeshClient) RemoveApp

func (r *AppMeshClient) RemoveApp(appName string) error

RemoveApp removes an application.

func (*AppMeshClient) RenewToken

func (r *AppMeshClient) RenewToken() (bool, error)

RenewToken renews the JWT token.

func (*AppMeshClient) RunAppAsync

func (r *AppMeshClient) RunAppAsync(app Application, maxTimeoutSeconds int) (int, error)

RunAppAsync runs an application asynchronously.

func (*AppMeshClient) RunAppSync

func (r *AppMeshClient) RunAppSync(app Application, maxTimeoutSeconds int) (*int, string, error)

RunAppSync runs an application synchronously.

func (*AppMeshClient) SetupTotp

func (r *AppMeshClient) SetupTotp(totpCode string) (bool, error)

SetupTotp sets up TOTP for the user.

func (*AppMeshClient) UploadFile

func (r *AppMeshClient) UploadFile(localFile, remoteFile string, applyFileAttributes bool) error

UploadFile uploads a file to the server.

func (*AppMeshClient) ValidateTotp

func (r *AppMeshClient) ValidateTotp(username string, challenge string, totpCode string, timeoutSeconds int) (string, error)

ValidateTotp validates the TOTP code and returns a new JWT token.

func (*AppMeshClient) ViewAllApps

func (r *AppMeshClient) ViewAllApps() ([]Application, error)

ViewAllApps retrieves all applications.

func (*AppMeshClient) ViewApp

func (r *AppMeshClient) ViewApp(appName string) (*Application, error)

ViewApp retrieves a specific application by name.

func (*AppMeshClient) ViewHostResources

func (r *AppMeshClient) ViewHostResources() ([]byte, error)

ViewHostResources retrieves resources.

func (*AppMeshClient) ViewTags

func (r *AppMeshClient) ViewTags() (Labels, error)

ViewTags retrieves all labels.

type AppMeshClientTCP

type AppMeshClientTCP struct {
	*AppMeshClient
	TcpExecutor *ClientRequesterTcp // Used for file operations.
}

AppMeshClientTCP interacts with the TCP server using REST API requests via a socket.

func NewTcpClient

func NewTcpClient(options Option) (*AppMeshClientTCP, error)

NewTcpClient creates a new AppMeshClientTCP instance for interacting with a TCP server.

func (*AppMeshClientTCP) CloseConnection

func (client *AppMeshClientTCP) CloseConnection()

CloseConnection closes the TCP connection.

func (*AppMeshClientTCP) FileDownload

func (r *AppMeshClientTCP) FileDownload(remoteFile, localFile string, applyFileAttributes bool) error

FileDownload downloads a file from the server to the local file system.

func (*AppMeshClientTCP) FileUpload

func (client *AppMeshClientTCP) FileUpload(localFile, remoteFile string, applyFileAttributes bool) error

FileUpload uploads a local file to the server.

type AppOutput

type AppOutput struct {
	HttpSuccess    bool
	HttpBody       string
	OutputPosition *int64
	ExitCode       *int
	Error          error
}

AppOutput represents the output of an application.

type Application

type Application struct {
	// Main definition
	Name           string  `json:"name"`
	Owner          *string `json:"owner"`
	Permission     *int    `json:"permission"`
	ShellMode      *bool   `json:"shell"`
	SessionLogin   *bool   `json:"session_login"`
	Command        *string `json:"command"`
	Description    *string `json:"description"`
	WorkingDir     *string `json:"working_dir"`
	HealthCheckCMD *string `json:"health_check_cmd"`
	Status         int     `json:"status"`
	StdoutCacheNum *int    `json:"stdout_cache_num"`
	Metadata       *string `json:"metadata"`

	// Time
	StartTime     *int64 `json:"start_time"`
	EndTime       *int64 `json:"end_time"`
	LastStartTime *int64 `json:"last_start_time"`
	LastExitTime  *int64 `json:"last_exit_time"`
	NextStartTime *int64 `json:"next_start_time"`
	RegisterTime  *int64 `json:"register_time"`

	StopRetention *string   `json:"retention"`
	Behavior      *Behavior `json:"behavior"`
	// Short running definition
	StartIntervalSeconds       *string `json:"start_interval_seconds"`
	StartIntervalSecondsIsCron *bool   `json:"cron"`

	// Runtime attributes
	Pid            *int    `json:"pid"`
	User           *string `json:"pid_user"`
	ReturnCode     *int    `json:"return_code"`
	Health         *int    `json:"health"`
	FileDescritors *int    `json:"fd"`
	Starts         *int    `json:"starts"`
	PsTree         *string `json:"pstree"`
	ContainerID    *string `json:"container_id"`

	CPU             *float64 `json:"cpu"`
	Memory          *int     `json:"memory"`
	Uuid            *string  `json:"process_uuid"` // For run application
	StdoutCacheSize *int     `json:"stdout_cache_size"`

	Version   *int    `json:"version"`
	LastError *string `json:"last_error"`

	DockerImage *string `json:"docker_image"`

	DailyLimit    *DailyLimitation    `json:"daily_limitation"`
	ResourceLimit *ResourceLimitation `json:"resource_limit"`
	Env           *Environments       `json:"env"`
	SecEnv        *Environments       `json:"sec_env"`
}

Application represents the application configuration and status.

type Behavior

type Behavior struct {
	Exit string `json:"exit"`
}

Behavior represents the behavior configuration of an application.

type ClientRequester

type ClientRequester interface {
	DoRequest(method string, apiPath string, queries url.Values, headers map[string]string, body io.Reader, token string, forwardingHost string) (int, []byte, http.Header, error)
}

ClientRequester defines the interface for making HTTP requests.

type ClientRequesterRest

type ClientRequesterRest struct {
	// contains filtered or unexported fields
}

HTTP Request executor

func (*ClientRequesterRest) DoRequest

func (r *ClientRequesterRest) DoRequest(method string, apiPath string, queries url.Values, headers map[string]string, body io.Reader, token string, forwardingHost string) (int, []byte, http.Header, error)

REST request

type ClientRequesterTcp

type ClientRequesterTcp struct {
	*TCPConnection
	BaseURL string
}

ClientRequesterTcp handles TCP requests.

func (*ClientRequesterTcp) DoRequest

func (r *ClientRequesterTcp) DoRequest(method, apiPath string, queries url.Values, headers map[string]string, body io.Reader, token string, forwardingHost string) (int, []byte, http.Header, error)

DoRequest performs a REST-like request over TCP.

type DailyLimitation

type DailyLimitation struct {
	DailyStart string `json:"daily_start"`
	DailyEnd   string `json:"daily_end"`
}

DailyLimitation represents the daily time limitation for an application.

type Environments

type Environments = map[string]string

Environments represents a map of environment variables.

type Headers

type Headers = map[string]string

Headers represents a map of HTTP headers.

type JWTResponse

type JWTResponse struct {
	AccessToken   string `json:"access_token"`
	ExpireSeconds int    `json:"expire_seconds"`
	ExpireTime    int    `json:"expire_time"`
	Profile       struct {
		AuthTime int    `json:"auth_time"`
		Name     string `json:"name"`
	} `json:"profile"`
	TokenType string `json:"token_type"`
}

JWTResponse represents the response containing JWT token information.

type Labels

type Labels = map[string]string

Labels represents a map of labels.

type Option

type Option struct {
	AppMeshUri string // URI of the App Mesh server; use "https://localhost:6060" for HTTP or "localhost:6059" for TCP.
	Token      string // JWT authentication token for API requests.
	ForwardTo  string // The target host to which all requests will be forwarded; with this set, AppMeshUri will act as a proxy to forward requests.

	SslClientCertificateFile    string // Path to the client certificate file (PEM format), leave empty to disable client authentication.
	SslClientCertificateKeyFile string // Path to the client certificate private key (PEM format), leave empty to disable client authentication.

	// SslTrustedCA controls server certificate verification:
	//   - Empty string (""): disables server certificate verification
	//   - nil: uses default App Mesh CA at /opt/appmesh/ssl/ca.pem
	//   - File path: uses custom CA file or directory
	// Note: System CAs are not included by default. Create a combined CA bundle if needed.
	SslTrustedCA *string

	HttpTimeoutMinutes *time.Duration // Timeout for http.Client requests in minutes.
	// contains filtered or unexported fields
}

Option represents the configuration options for the AppMeshClient.

type Request

type Request struct {
	Uuid          string            `msg:"uuid" msgpack:"uuid"`
	RequestUri    string            `msg:"request_uri" msgpack:"request_uri"`
	HttpMethod    string            `msg:"http_method" msgpack:"http_method"`
	ClientAddress string            `msg:"client_addr" msgpack:"client_addr"`
	Body          string            `msg:"body" msgpack:"body"`
	Headers       map[string]string `msg:"headers" msgpack:"headers"`
	Queries       map[string]string `msg:"querys" msgpack:"querys"`
}

Request represents the message sent over TCP.

func (*Request) Serialize

func (r *Request) Serialize() ([]byte, error)

Serialize serializes the Request into a byte slice.

type ResourceLimitation

type ResourceLimitation struct {
	MemoryMb        int `json:"memory_mb"`
	MemoryVirtualMb int `json:"memory_virt_mb"`
	CpuShares       int `json:"cpu_shares"`
}

ResourceLimitation represents the CPU and memory limitations for an application.

type Response

type Response struct {
	Uuid        string            `msg:"uuid" msgpack:"uuid"`
	RequestUri  string            `msg:"request_uri" msgpack:"request_uri"`
	HttpStatus  int               `msg:"http_status" msgpack:"http_status"`
	BodyMsgType string            `msg:"body_msg_type" msgpack:"body_msg_type"`
	Body        string            `msg:"body" msgpack:"body"`
	Headers     map[string]string `msg:"headers" msgpack:"headers"`
}

Response represents the message received over TCP.

func (*Response) Deserialize

func (r *Response) Deserialize(data []byte) error

Deserialize deserializes the byte slice into a Response.

type SSLConfig

type SSLConfig struct {
	VerifyClient                bool   `yaml:"VerifyClient"`
	VerifyServer                bool   `yaml:"VerifyServer"`
	VerifyServerDelegate        bool   `yaml:"VerifyServerDelegate"`
	SSLCaPath                   string `yaml:"SSLCaPath"`
	SSLCertificateFile          string `yaml:"SSLCertificateFile"`
	SSLCertificateKeyFile       string `yaml:"SSLCertificateKeyFile"`
	SSLClientCertificateFile    string `yaml:"SSLClientCertificateFile"`
	SSLClientCertificateKeyFile string `yaml:"SSLClientCertificateKeyFile"`
}

SSLConfig represents the SSL configuration.

type TCPConnection

type TCPConnection struct {
	// contains filtered or unexported fields
}

TCPConnection represents a non-thread-safe TCP connection wrapper.

func NewTCPConnection

func NewTCPConnection() *TCPConnection

NewTCPConnection initializes and returns a TCPConnection.

func (*TCPConnection) ClientAddress

func (r *TCPConnection) ClientAddress() string

ClientAddress returns the socket client address.

func (*TCPConnection) Close

func (r *TCPConnection) Close()

Close closes the underlying TCP connection.

func (*TCPConnection) Connect

func (r *TCPConnection) Connect(url string, sslClientCert string, sslClientCertKey string, sslCAPath string) error

Connect establishes a secure TLS TCP connection to an App Mesh server.

func (*TCPConnection) ReadMessage

func (r *TCPConnection) ReadMessage() ([]byte, error)

ReadMessage reads and returns a complete message from the TCP connection.

func (*TCPConnection) SendMessage

func (r *TCPConnection) SendMessage(buffer []byte) error

SendMessage sends a complete message over the TCP connection.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL