utils

package
v0.0.0-...-9625d7e Latest Latest
Warning

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

Go to latest
Published: May 21, 2020 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// HB_CRON_JOB_TIME_SECOND ...
	HB_CRON_JOB_TIME_SECOND            = 60
	DetailDataCronJobTimeSecond        = 10
	DisableDetailDataCronJobTimeSecond = 60
	HTTP_CLIENT_TIME_OUT               = 30
	POST_HEART_BEAT_URI                = "/agent-status"

	AgentNameWin   = "agent.exe"
	AgentNameLinux = "agent"

	DaemonNameWin   = "telescope.exe"
	DaemonNameLinux = "telescope"

	// GetOpenstackMetaDataUrl ...
	GetOpenstackMetaDataUrl = "http://169.254.169.254/openstack/latest/meta_data.json"
	// OpenStackURL4AKSK details
	// https://support.huaweicloud.com/usermanual-ecs/zh-cn_topic_0042400609.html
	OpenStackURL4AKSK = "http://169.254.169.254/openstack/latest/securitykey"

	CPU1stPctThreshold float64 = 10                // 10%
	Memory1stThreshold uint64  = 200 * 1024 * 1024 // 200MB
	CPU2ndPctThreshold float64 = 30                // 30%
	Memory2ndThreshold uint64  = 700 * 1024 * 1024 // 700MB
)
View Source
const (
	// COMMA ...
	COMMA          string = ","
	SEMICOLON      string = ";"
	COLON          string = ":"
	EQUALSIGN      string = "="
	BLANK          string = " "
	SLASH          string = "/"
	LINE_SEPARATOR string = "\n"

	BasicDateFormat      = "20060102T150405Z"
	BasicDateFormatShort = "20060102"
	TerminationString    = "sdk_request"
	Algorithm            = "SDK-HMAC-SHA256"
	PreSKString          = "SDK"
	HeaderXDate          = "x-sdk-date"
	HeaderDate           = "date"
	HeaderHost           = "host"
	HeaderAuthorization  = "Authorization"
	HeaderProjectId      = "X-Project-Id"
	HeaderAuthToken      = "X-Auth-Token"

	HeaderConnection  = "connection"
	HeaderUserAgent   = "user-agent"
	HeaderContentType = "content-type"
)
View Source
const (
	// FieldRequiredErrCode ...
	FieldRequiredErrCode  = "ParamRequiredError"     //the field value is required
	FieldMaxSizeErrCode   = "FieldMaxSizeError"      //the size of field error code
	FieldLenErrCode       = "FieldLengthError"       //the length of field error code
	FieldValueExistedCode = "FieldValueExistedError" //the field value existed code
)
View Source
const (
	AgentVersion  = "1.0.14.1"
	APICESVersion = "V1.0"
)

Variables

View Source
var (
	DefaultTimeFormat     = "hh:mm:ss"
	DefaultDateFormat     = "YYYY-MM-DD"
	DefaultDateTimeFormat = "YYYY-MM-DDThh:mm:ss"
)
View Source
var (
	HTTPClient *http.Client

	CLIENT_POINT = 0
)
View Source
var (

	// DefaultMetricDeltaDataTimeInSecond is the interval to get metrics
	DefaultMetricDeltaDataTimeInSecond = DisableDetailDataCronJobTimeSecond
)
View Source
var Errors = logdErrors{
	NoConfigFileFound:         errors.New("no config file found, please check if missing"),
	ConfigFileValidationError: errors.New("config file validation failed, please re-check the content on it"),
	NoMatchedFileFound:        errors.New("no matched file found with a pattern"),
	NoTimeInTheLog:            errors.New("there is no time in the log text"),
	NoTimeFormat:              errors.New("no dateformat for the log agent in the configuration file"),
	AkskStrInvalid:            errors.New("aksk data is invalid"),
}

Errors ...

View Source
var Placeholder = []p{
	p{"hh", "15", "\\d{2}"},
	p{"h", "03", "\\d{2}"},
	p{"mm", "04", "\\d{2}"},
	p{"ss", "05", "\\d{2}"},
	p{"SSS", "999", "\\d{3}"},
	p{"MMMM", "January", "\\w{3,9}"},
	p{"MMM", "Jan", "\\w{3}"},
	p{"MM", "01", "\\d{2}"},
	p{"M", "1", "\\d{1}"},
	p{"T", "T", "\\w{1}"},
	p{"pm", "PM", "\\w{2}"},
	p{"ZZZZ", "-0700", "(-|\\+)\\d{4}"},
	p{"ZZZ", "MST", "\\w{3}"},
	p{"ZZ", "Z07:00", "\\w{1}"},
	p{"YYYY", "2006", "\\d{4}"},
	p{"YY", "06", "\\d{2}"},
	p{"DDDD", "Monday", "\\w{6,9}"},
	p{"DDD", "Mon", "\\w{3}"},
	p{"DD", "02", "\\d{2}"},
	p{"D", "2", "\\d{1}"},
}

Functions

func AuthHeaderValue

func AuthHeaderValue(signature, accessKey, credentialScope, signedHeaders string) string

AuthHeaderValue Get the finalized value for the "Authorization" header. The signature parameter is the output from SignStringToSign

func CanonicalRequest

func CanonicalRequest(req *http.Request) (string, error)

CanonicalRequest ...

func CheckCurrentUser

func CheckCurrentUser(args []string) bool

CheckCurrentUser check current user,if user is root ,do not start this agent

func ChooseConfOrApiAksk

func ChooseConfOrApiAksk(needExchange bool)

ChooseConfOrApiAksk ... Use it after a api response, if the response is 401/403, increase the now_method_count if now_method_count greater than retry_count, change the get aksk method to the other

func CompareFiles

func CompareFiles(srcFile, tarFile string) bool

CompareFiles compare two files with md5 of file

func ConcatStr

func ConcatStr(str1 string, str2 string) string

ConcatStr Concat the two str, str1 first, strs follows

func CopyFile

func CopyFile(srcFilePath, destFilePath string) error

CopyFile copy file

func CreateDir

func CreateDir(dir string) error

CreateDir create dir

func FileListSortTimeAsc

func FileListSortTimeAsc(fileStrArr []string) (fileStrArrSortResult []string)

FileListSortTimeAsc sort the file in ascending order

func Format

func Format(format string, date time.Time) string

Format formats a date based on Microsoft Excel (TM) conventions

func GetClientPort

func GetClientPort() int

GetClientPort ...

func GetCurrTSInMs

func GetCurrTSInMs() int64

GetCurrTSInMs ... We don't use the time.Millisecond Because 1000000 is more accurate and efficient

func GetHostName

func GetHostName() string

GetHostName get system host name

func GetHttpClient

func GetHttpClient() *http.Client

func GetLocalIp

func GetLocalIp() (ip string)

GetLocalIp get local ip

func GetMd5FromBytes

func GetMd5FromBytes(contentBytes []byte) string

GetMd5FromBytes get md5 hash from bytes

func GetMd5OfFile

func GetMd5OfFile(file string) string

GetMd5OfFile get md5 of file

func GetMsFromTime

func GetMsFromTime(t time.Time) int64

GetMsFromTime ...

func GetOsType

func GetOsType() string

GetOsType return os type, eg: windows_amd64

func GetReg

func GetReg(in string) (reg string)

func GetWorkingPath

func GetWorkingPath() string

func HTTPGet

func HTTPGet(url string) ([]byte, error)

HTTPGet get result by http

func HTTPSend

func HTTPSend(req *http.Request, service string) (*http.Response, error)

HTTPSend ...

func InitConfig

func InitConfig()

InitConfig Initialize configuration

func IsFileExist

func IsFileExist(path string) bool

IsFileExist check if file exist

func IsFileOrDir

func IsFileOrDir(fileName string, decideDirBool bool) bool

IsFileOrDir according the file name and decideDirBool to judge file or directory

func IsWindowsOs

func IsWindowsOs() bool

IsWindowsOs ...

func Limit2Decimal

func Limit2Decimal(number float64) float64

Limit2Decimal limit float number to two decimal points

func MergeStringArr

func MergeStringArr(oriArr []string, destArr []string) []string

MergeStringArr merge the oriArr to destArr

func Parse

func Parse(format string, value string) (time.Time, error)

Parse parses a value to a date based on Microsoft Excel (TM) formats

func ReuseDial

func ReuseDial(network, addr string) (net.Conn, error)

ReuseDial ...

func StrArrContainsStr

func StrArrContainsStr(strArr []string, str string) bool

StrArrContainsStr An array which type is string if contain a string

func SubStr

func SubStr(str string, size int) string

SubStr cut out string according to the size

func UncompressFile

func UncompressFile(zipFilePath string, destPath string) (string, error)

UncompressFile ...

func UncompressTgzFile

func UncompressTgzFile(tgzFilePath string, destPath string) (string, error)

UncompressTgzFile uncompress .tar.gz or .tgz file

func UncompressZipFile

func UncompressZipFile(zipFilePath string, destPath string) (string, error)

UncompressZipFile uncompress .zip

func WriteStrToFile

func WriteStrToFile(str string, filepath string) error

WriteStrToFile ...

func WriteToFile

func WriteToFile(obj interface{}, filepath string) error

WriteToFile Persiste the struct to file

Types

type ErrFieldMaxLen

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

ErrFieldMaxLen field length over the threshold

func NewErrFieldMaxLen

func NewErrFieldMaxLen(field string, size int) *ErrFieldMaxLen

NewErrFieldMaxLen ...

func (*ErrFieldMaxLen) Code

func (e *ErrFieldMaxLen) Code() string

Code returns the error code for the type of invalid field.

func (*ErrFieldMaxLen) Error

func (e *ErrFieldMaxLen) Error() string

Error returns the string version of the invalid parameter error.

func (*ErrFieldMaxLen) Field

func (e *ErrFieldMaxLen) Field() string

Field Returns the field and object the error occurred.

func (*ErrFieldMaxLen) Msg

func (e *ErrFieldMaxLen) Msg() string

Msg returns the reason the field was invalid, and its context.

func (*ErrFieldMaxLen) SetObject

func (e *ErrFieldMaxLen) SetObject(obj string)

SetObject ...

type ErrFieldMaxSize

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

ErrFieldMaxSize field size over the max, eg.The max size of field "message" is 10KB

func NewErrFieldMaxSize

func NewErrFieldMaxSize(field string, size int) *ErrFieldMaxSize

NewErrFieldMaxSize ...

func (*ErrFieldMaxSize) Code

func (e *ErrFieldMaxSize) Code() string

Code returns the error code for the type of invalid field.

func (*ErrFieldMaxSize) Error

func (e *ErrFieldMaxSize) Error() string

Error returns the string version of the invalid parameter error.

func (*ErrFieldMaxSize) Field

func (e *ErrFieldMaxSize) Field() string

Field Returns the field and object the error occurred.

func (*ErrFieldMaxSize) Msg

func (e *ErrFieldMaxSize) Msg() string

Msg returns the reason the field was invalid, and its context.

func (*ErrFieldMaxSize) SetObject

func (e *ErrFieldMaxSize) SetObject(obj string)

SetObject ...

type ErrFieldRequired

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

ErrFieldRequired An ErrFieldRequired means the field need value,not nil.

func NewErrFieldRequired

func NewErrFieldRequired(field string) *ErrFieldRequired

NewErrFieldRequired creates a new required parameter error.

func (*ErrFieldRequired) Code

func (e *ErrFieldRequired) Code() string

Code returns the error code for the type of invalid field.

func (*ErrFieldRequired) Error

func (e *ErrFieldRequired) Error() string

Error returns the string version of the invalid parameter error.

func (*ErrFieldRequired) Field

func (e *ErrFieldRequired) Field() string

Field Returns the field and object the error occurred.

func (*ErrFieldRequired) Msg

func (e *ErrFieldRequired) Msg() string

Msg returns the reason the field was invalid, and its context.

func (*ErrFieldRequired) SetObject

func (e *ErrFieldRequired) SetObject(obj string)

SetObject ...

type ErrFieldValueExisted

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

ErrFieldValueExisted ...

func NewErrFieldValueExisted

func NewErrFieldValueExisted(field string) *ErrFieldValueExisted

NewErrFieldValueExisted field value existed

func (*ErrFieldValueExisted) Code

func (e *ErrFieldValueExisted) Code() string

Code returns the error code for the type of invalid field.

func (*ErrFieldValueExisted) Error

func (e *ErrFieldValueExisted) Error() string

Error returns the string version of the invalid parameter error.

func (*ErrFieldValueExisted) Field

func (e *ErrFieldValueExisted) Field() string

Field Returns the field and object the error occurred.

func (*ErrFieldValueExisted) Msg

func (e *ErrFieldValueExisted) Msg() string

Msg returns the reason the field was invalid, and its context.

func (*ErrFieldValueExisted) SetObject

func (e *ErrFieldValueExisted) SetObject(obj string)

SetObject ...

type ErrInvalidField

type ErrInvalidField interface {
	error

	//error code
	Code() string

	//error message
	Msg() string

	// Field name the error occurred on.
	Field() string

	// SetObject updates the object of the error,eg."User" is the object of the field "name".
	SetObject(string)
}

An ErrInvalidField represents an invalid field.

type ErrInvalidFields

type ErrInvalidFields struct {
	Object string
	Errs   []ErrInvalidField
}

ErrInvalidFields ...

func (*ErrInvalidFields) Add

func (fields *ErrInvalidFields) Add(field ErrInvalidField)

Add a new field invalid error

func (ErrInvalidFields) Error

func (fieldsfields ErrInvalidFields) Error() string

Error returns the string formatted form of the invalid parameters.

func (*ErrInvalidFields) Len

func (fields *ErrInvalidFields) Len() int

Len get number of invalid field error

type GeneralConfig

type GeneralConfig struct {
	InstanceId      string
	ProjectId       string
	AppTask         string
	AccessKey       string
	SecretKey       string
	ClientPort      int
	PortNum         int
	AKSKToken       string
	RegionId        string
	ExternalService string
	BmsFlag         bool

	// default false: 10s collect switch off
	DetailMonitorEnable bool
	CPU1stPctThreshold  float64 `json:"cpu_first_pct_threshold"`
	Memory1stThreshold  uint64  `json:"memory_first_threshold"`
	CPU2ndPctThreshold  float64 `json:"cpu_second_pct_threshold"`
	Memory2ndThreshold  uint64  `json:"memory_second_threshold"`
}

GeneralConfig ...

func GetConfig

func GetConfig() *GeneralConfig

GetConfig Get wrapper

func ReadConfig

func ReadConfig(i, j *int) (*GeneralConfig, error)

ReadConfig Read the config from conf.json

func ReloadConfig

func ReloadConfig(i, j *int) *GeneralConfig

ReloadConfig to support hot load config file

type MetaData

type MetaData struct {
	InstanceId      string
	ProjectId       string
	RegionId        string
	ExternalService string
	AppTask         string
}

MetaData ...

type QueryStringParser

type QueryStringParser interface {
	Build(v url.Values)
	Parse() (interface{}, error)
}

QueryStringParser ...

type SecurityData

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

SecurityData ...

type Signer

type Signer struct {
	AccessKey string
	SecretKey string
	AKSKToken string
	Region    string
	Service   string
	// contains filtered or unexported fields
}

Signer ...

func NewSigner

func NewSigner(serviceName string) *Signer

NewSigner ...

func (*Signer) GetAuthorization

func (sig *Signer) GetAuthorization(req *http.Request) (string, error)

GetAuthorization ...

type Validator

type Validator interface {
	Validate() error
	ParseJson(bytes []byte) error
}

Validator ...

Jump to

Keyboard shortcuts

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