common

package
v0.4.7 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package common is to include common methods for managing multi-cloud infra

Package common is to include common methods for managing multi-cloud infra

Package common provides common utilities for the CM-Beetle system. This file (request-manager.go) manages HTTP requests: - API Request Tracking: Tracking API requests coming into Beetle (RequestMap, RequestDetails) - Internal HTTP Client: Executing API calls to Tumblebug (ExecuteHttpRequest, caching, circuit breaker)

Package common is to include common methods for managing multi-cloud infra

Index

Constants

View Source
const (
	StrTumblebugRestUrl           string = "TUMBLEBUG_REST_URL"
	StrAutocontrolDurationMs      string = "AUTOCONTROL_DURATION_MS"
	CbStoreKeyNotFoundErrorString string = "key not found"
	StrAdd                        string = "add"
	StrDelete                     string = "delete"
	StrSSHKey                     string = "sshKey"
	StrImage                      string = "image"
	StrCustomImage                string = "customImage"
	StrSecurityGroup              string = "securityGroup"
	StrSpec                       string = "spec"
	StrVNet                       string = "vNet"
	StrSubnet                     string = "subnet"
	StrDataDisk                   string = "dataDisk"
	StrNLB                        string = "nlb"
	StrVM                         string = "vm"
	StrMCI                        string = "mci"
	StrDefaultResourceName        string = "-systemdefault-"

	// SystemCommonNs is const for SystemCommon NameSpace ID
	SystemCommonNs string = "system-purpose-common-ns"
)
View Source
const (
	// RequestStatusHandling indicates the request is currently being processed.
	RequestStatusHandling = "Handling"
	// RequestStatusSuccess indicates the request completed successfully.
	RequestStatusSuccess = "Success"
	// RequestStatusError indicates the request failed with an error.
	RequestStatusError = "Error"
)

RequestStatus constants define the possible states of a request. Status Flow: Handling → Success/Error - Handling: Request is currently being processed - Success: Request completed successfully - Error: Request failed with an error Note: These values are aligned with CB-Tumblebug's status values.

View Source
const (
	// VeryShortDuration is a duration for very short-term cache
	VeryShortDuration = 1 * time.Second
	// ShortDuration is a duration for short-term cache
	ShortDuration = 2 * time.Second
	// MediumDuration is a duration for medium-term cache
	MediumDuration = 5 * time.Second
	// LongDuration is a duration for long-term cache
	LongDuration = 10 * time.Second
)
View Source
const DefaultRequestRetentionPeriod = 7 * 24 * time.Hour // 1 week

DefaultRequestRetentionPeriod is the default retention period for completed/failed requests.

View Source
const MaxDebugBodyLength = 50000

MaxDebugBodyLength is the maximum length of response body for debug logs

View Source
const NoBody = "NOBODY"

NoBody is a constant for empty body

Variables

View Source
var AutocontrolDurationMs string
View Source
var DefaulNamespaceId = "mig01"
View Source
var StartTime string
View Source
var SystemReady bool

SystemReady is global variable for checking SystemReady status

View Source
var TumblebugRestUrl string

Functions

func ChangeIdString

func ChangeIdString(name string) string

ChangeIdString is func to change strings in id or name (special chars to -, to lower string )

func CheckElement

func CheckElement(a string, list []string) bool

func CheckString

func CheckString(name string) error

CheckString is func to check string by the given rule `[a-z]([-a-z0-9]*[a-z0-9])?`

func CleanupOldRequests added in v0.4.6

func CleanupOldRequests(maxAge time.Duration) int

CleanupOldRequests removes completed or failed requests older than the specified duration. Requests with "Handling" status are not removed regardless of age. Returns the number of removed requests.

func ConvertToMessage

func ConvertToMessage(inType string, inData string, obj interface{}) error

ConvertToMessage is func to change input data to gRPC message

func ConvertToOutput

func ConvertToOutput(outType string, obj interface{}) (string, error)

ConvertToOutput is func to convert gRPC message to print format

func CopySrcToDest

func CopySrcToDest(src interface{}, dest interface{}) error

CopySrcToDest is func to copy data from source to target

func ExecuteHttpRequest

func ExecuteHttpRequest[B any, T any](
	client *resty.Client,
	method string,
	url string,
	headers map[string]string,
	useBody bool,
	body *B,
	result *T,
	cacheDuration time.Duration,
) error

ExecuteHttpRequest performs the HTTP request and fills the result (var requestBody interface{} = nil for empty body)

func GenChildResourceKey

func GenChildResourceKey(nsId string, resourceType string, parentResourceId string, resourceId string) string

GenChildResourceKey is func to generate a key from resource type and id

func GenMciKey added in v0.2.1

func GenMciKey(nsId string, mciId string, vmId string) string

GenMciKey is func to generate a key used in keyValue store

func GenMciPolicyKey added in v0.2.1

func GenMciPolicyKey(nsId string, mciId string, vmId string) string

GenMciPolicyKey is func to generate Mci policy key

func GenMciSubGroupKey added in v0.2.1

func GenMciSubGroupKey(nsId string, mciId string, groupId string) string

GenMciSubGroupKey is func to generate a key from subGroupId used in keyValue store

func GenRandomPassword

func GenRandomPassword(length int) string

GenRandomPassword is func to return a RandomPassword

func GenResourceKey

func GenResourceKey(nsId string, resourceType string, resourceId string) string

GenResourceKey is func to generate a key from resource type and id

func GenUid

func GenUid() string

GenUid is func to return a UUID string

func GenerateNewRandomString

func GenerateNewRandomString(n int) string

generate a random string (from CB-MCKS source code)

func GetFuncName

func GetFuncName() string

GetFuncName is func to get the name of the running function

func HasRequest added in v0.4.6

func HasRequest(reqID string) bool

HasRequest checks if a request with the given ID exists.

func LookupKeyValueList

func LookupKeyValueList(kvl []KeyValue, key string) string

LookupKeyValueList is func to lookup KeyValue list

func NVL

func NVL(str string, def string) string

NVL is func for null value logic

func PrintJsonPretty

func PrintJsonPretty(v interface{})

PrintJsonPretty is func to print JSON pretty with indent

func RandomSleep

func RandomSleep(from int, to int)

RandomSleep is func to make a caller waits for during random time seconds (random value within x~y)

func RemoveAllRequests added in v0.4.6

func RemoveAllRequests()

RemoveAllRequests deletes all request tracking records.

func RemoveRequest added in v0.4.6

func RemoveRequest(reqID string)

RemoveRequest deletes request details by request ID.

func SetRequest added in v0.4.6

func SetRequest(reqID string, details RequestDetails) error

SetRequest stores request details with the given request ID. It uses lkvstore for persistence across server restarts.

func SetUseBody

func SetUseBody(requestBody any) bool

SetUseBody returns false if the given body is NoBody

func StartRequestCleanupScheduler added in v0.4.6

func StartRequestCleanupScheduler(interval time.Duration, maxAge time.Duration)

StartRequestCleanupScheduler starts a background goroutine that periodically cleans up old request records. It runs cleanup at the specified interval.

func ToLower

func ToLower(name string) string

ToLower is func to change strings (_ to -, " " to -, to lower string ) (deprecated soon)

func UpdateRequestProgress added in v0.4.6

func UpdateRequestProgress(reqID string, progressData any)

UpdateRequestProgress updates the handling status of the request.

Types

type CacheItem

type CacheItem[T any] struct {
	Response  T
	ExpiresAt time.Time
}

CacheItem is a struct to store cached item

type CircuitBreakerState added in v0.4.6

type CircuitBreakerState struct {
	FailureCount int
	LastFailure  time.Time
	IsOpen       bool
}

CircuitBreakerState represents the state of a circuit breaker for a specific request

type IID

type IID struct {
	NameId   string // NameID by user
	SystemId string // SystemID by CloudOS
}

Spider 2020-03-30 https://github.com/cloud-barista/cb-spider/blob/master/cloud-control-manager/cloud-driver/interfaces/resources/IId.go

type IdList

type IdList struct {
	IdList []string `json:"output"`
}

type KeyValue

type KeyValue struct {
	Key   string
	Value string
}

type NsInfo

type NsInfo struct {
	Id          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

NsInfo is struct for namespace information

type NsReq

type NsReq struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

NsReq is struct for namespace creation

type ProgressInfo added in v0.4.6

type ProgressInfo struct {
	Title string    `json:"title"`
	Info  any       `json:"info"`
	Time  time.Time `json:"time"`
}

ProgressInfo contains the progress information of a request.

type RequestDetails added in v0.1.1

type RequestDetails struct {
	StartTime     time.Time   `json:"startTime"`     // The time when the request was received by the server.
	EndTime       time.Time   `json:"endTime"`       // The time when the request was fully processed.
	Status        string      `json:"status"`        // The current status of the request (e.g., "Handling", "Error", "Success").
	RequestInfo   RequestInfo `json:"requestInfo"`   // Extracted information about the request.
	ResponseData  any         `json:"responseData"`  // The data sent back in response to the request.
	ErrorResponse string      `json:"errorResponse"` // A message describing any error that occurred during request processing.
}

RequestDetails contains detailed information about an HTTP request and its processing status.

func GetAllRequests added in v0.4.6

func GetAllRequests(filter *RequestFilter) []RequestDetails

GetAllRequests retrieves all request details with optional filtering. If filter is nil, all requests are returned.

func GetRequest added in v0.4.6

func GetRequest(reqID string) (RequestDetails, bool)

GetRequest retrieves request details by request ID. Returns the details and a boolean indicating if the request was found.

type RequestFilter added in v0.4.6

type RequestFilter struct {
	Status string    // Filter by status (Handling, Success, Error)
	Method string    // Filter by HTTP method
	URL    string    // Filter by URL (partial match)
	Since  time.Time // Filter by start time (requests after this time)
}

RequestFilter defines filter criteria for querying requests

type RequestInfo added in v0.1.1

type RequestInfo struct {
	Method string            `json:"method"`         // HTTP method (GET, POST, etc.), indicating the request's action type.
	URL    string            `json:"url"`            // The URL the request is made to.
	Header map[string]string `json:"header"`         // Key-value pairs of the request headers.
	Body   any               `json:"body,omitempty"` // Optional: request body
}

RequestInfo stores the essential details of an HTTP request.

func ExtractRequestInfo added in v0.1.1

func ExtractRequestInfo(r *http.Request) RequestInfo

ExtractRequestInfo extracts necessary information from http.Request

type RestGetAllNsResponse added in v0.1.1

type RestGetAllNsResponse struct {
	//Name string     `json:"name"`
	Ns []NsInfo `json:"ns"`
}

Response structure for RestGetAllNs

type SimpleMsg

type SimpleMsg struct {
	Message string `json:"message" example:"Any message"`
}

SimpleMsg is struct for JSON Simple message

type SpiderConnectionName

type SpiderConnectionName struct {
	ConnectionName string `json:"ConnectionName"`
}

Jump to

Keyboard shortcuts

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