example

package module
v0.0.0-...-2942c55 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2022 License: Apache-2.0 Imports: 29 Imported by: 0

README

example

Name

example - prints "example" after a query is handled.

Description

The example plugin prints "example" on every query that got handled by the server. It serves as documentation for writing CoreDNS plugins.

Compilation

This package will always be compiled as part of CoreDNS and not in a standalone way. It will require you to use go get or as a dependency on plugin.cfg.

The manual will have more information about how to configure and extend the server with external plugins.

A simple way to consume this plugin, is by adding the following on plugin.cfg, and recompile it as detailed on coredns.io.

example:github.com/coredns/example

Put this early in the plugin list, so that example is executed before any of the other plugins.

After this you can compile coredns by:

go generate
go build

Or you can instead use make:

make

Syntax

example

Metrics

If monitoring is enabled (via the prometheus directive) the following metric is exported:

  • coredns_example_request_count_total{server} - query count to the example plugin.

The server label indicated which server handled the request, see the metrics plugin for details.

Ready

This plugin reports readiness to the ready plugin. It will be immediately ready.

Examples

In this configuration, we forward all queries to 9.9.9.9 and print "example" whenever we receive a query.

. {
  forward . 9.9.9.9
  example
}

Or without any external connectivity:

. {
  whoami
  example
}

Also See

See the manual.

Documentation

Overview

Package example is a CoreDNS plugin that prints "example" to stdout on every packet received.

It serves as an example CoreDNS plugin with numerous code comments.

Index

Constants

View Source
const DefaultTimeoutInSec = 2
View Source
const (
	// INSTANCE_ID key for hostname in os env
	INSTANCE_ID = "INSTANCE_ID"
)

Variables

This section is empty.

Functions

func CustomLevelEncoder

func CustomLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder)

func GetDefaultLogger

func GetDefaultLogger() (*zap.SugaredLogger, error)

GetDefaultLogger get a default logger

func GetLogger

func GetLogger(name string) (*zap.SugaredLogger, error)

GetLogger get a named logger, if name is empty, use the default logger

func InitLogger

func InitLogger(logPath string, logLevel zapcore.Level, enableStdOut bool)

InitLogger initializes a thread-safe singleton logger This would be called from a main method when the application starts up

func InitStdOutLogger

func InitStdOutLogger(logLevel zapcore.Level)

InitStdOutLogger initialize a stdout logger, just for UT

func SendRequest

func SendRequest(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string) (int, []byte, error)

SendRequest send given http request with a 2s timeout

func SendRequestWithFullReturn

func SendRequestWithFullReturn(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string, timeoutInSec int64, isTlsBypass bool) (int, http.Header, []byte, error)

SendRequestWithFullReturn encapsulate error handling of http request. Return HTTP status code, response header, pointer of response body byte slice and error. A non-2xx status code doesn't cause an error.

func SendRequestWithTimeout

func SendRequestWithTimeout(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string, timeoutInSec int64) (int, []byte, error)

SendRequest encapsulate error handling of http request. Return HTTP status code, response header, pointer of response body byte slice and error. A non-2xx status code doesn't cause an error.

func SendRequestWithTlsBypass

func SendRequestWithTlsBypass(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string) (int, []byte, error)

SendRequest send given http request with TLS bypass

func SyslogTimeEncoder

func SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

Types

type CertificateConfig

type CertificateConfig struct {
	EnvoyCertName string
	MdsdCertName  string
	LocalCertPath string
}

CertificateConfig certificates related config

type Client

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

Client kubelet client interface

func NewClient

func NewClient(kubeletConfig *KubeletConfig, tlsBypassHttpsClient TlsBypassHttpsClient) *Client

NewClient create a kubelet client

func (*Client) GetHealthStatus

func (kc *Client) GetHealthStatus() (bool, error)

GetHealthStatus get kubelet healthz status from kubelet "/healthz" api return true if kubelet is in good health

func (*Client) GetPodsInfo

func (kc *Client) GetPodsInfo() ([]v1.Pod, error)

GetPodsInfo get kubelet pods info from kubelet "/pods" api

func (*Client) GetRunningPods

func (kc *Client) GetRunningPods() (*v1.PodList, error)

GetRunningPods get all running pods in kubelet via the "runningpods" api

type Configuration

type Configuration struct {
	Server          ServerConfig
	PodSpecSetting  PodSpecConfig
	Log             LogConfig
	Kubelet         KubeletConfig
	ScheduledEvents ScheduledEventsConfig
	ManyModel       ManyModelConfig
	Xds             XdsConfig
	UpstreamToken   UpstreamTokenConfig
	DownstreamToken DownstreamTokenConfig
	Drain           DrainConfig
	Certificate     CertificateConfig
	Flight          FlightConfig
	DefaultEnvVars  map[string]string
}

Configuration vmagent configuration definition

func GetDefaultConfig

func GetDefaultConfig() *Configuration

func InitConfig

func InitConfig(configPath string) (*Configuration, error)

type DefaultHttpRequestSender

type DefaultHttpRequestSender struct {
	Logger *zap.SugaredLogger
}

func NewDefaultHttpRequestSender

func NewDefaultHttpRequestSender() *DefaultHttpRequestSender

func (*DefaultHttpRequestSender) SendRequest

func (se *DefaultHttpRequestSender) SendRequest(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string) (int, []byte, error)

func (*DefaultHttpRequestSender) SendRequestWithFullReturn

func (se *DefaultHttpRequestSender) SendRequestWithFullReturn(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string, timeoutInSec int64, isTlsBypass bool) (int, http.Header, []byte, error)

func (*DefaultHttpRequestSender) SendRequestWithTimeout

func (se *DefaultHttpRequestSender) SendRequestWithTimeout(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string, timeoutInSec int64) (int, []byte, error)

func (*DefaultHttpRequestSender) SendRequestWithTlsBypass

func (se *DefaultHttpRequestSender) SendRequestWithTlsBypass(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string) (int, []byte, error)

type DefaultTlsBypassHttpsClient

type DefaultTlsBypassHttpsClient struct {
	Logger *zap.SugaredLogger
	Client *http.Client
}

func NewDefaultTlsBypassHttpsClient

func NewDefaultTlsBypassHttpsClient() *DefaultTlsBypassHttpsClient

func (*DefaultTlsBypassHttpsClient) HttpGet

func (dg *DefaultTlsBypassHttpsClient) HttpGet(url string) ([]byte, int, error)

HttpGet get http GET response body pointer from given url

type DownstreamTokenConfig

type DownstreamTokenConfig struct {
	// DownstreamMsiTokenEndpoint is endpoint of MSI of VMAgent.
	DownstreamMsiTokenEndpoint string
	// DownstreamAcrTokenEndpoint is endpoint of ACR of VMAgent.
	DownstreamAcrTokenEndpoint string
	// DownstreamBlobKeyEndpoint is endpoint of BLOB of VMAgent.
	DownstreamBlobKeyEndpoint        string
	DownstreamSecretArtifactEndpoint string
}

type DrainConfig

type DrainConfig struct {
	EnvoyDrainEndpoint          string
	EnvoyStatsEndpoint          string
	SLBMarkUnhealthyMaxDuration int
}

type Example

type Example struct {
	Next       plugin.Handler
	KubeClient *Client
	Logger     *zap.SugaredLogger

	Records []*PodRecord
	// contains filtered or unexported fields
}

Example is an example plugin to show how to write a plugin.

func (*Example) BackgroundLoop

func (e *Example) BackgroundLoop()

func (*Example) GetEnvConfig

func (e *Example) GetEnvConfig(envVar string, default_val int) (int, error)

func (*Example) GetRecords

func (e *Example) GetRecords() []*PodRecord

func (*Example) GetUserPodRecords

func (e *Example) GetUserPodRecords(pods []v1.Pod) []*PodRecord

func (*Example) Name

func (e *Example) Name() string

Name implements the Handler interface.

func (*Example) QueryForPodRecord

func (e *Example) QueryForPodRecord(name string, state request.Request, ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error)

func (Example) Ready

func (e Example) Ready() bool

Ready implements the ready.Readiness interface, once this flips to true CoreDNS assumes this plugin is ready for queries; it is not checked again.

func (*Example) ServeDNS

func (e *Example) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error)

func (*Example) ServeDNS_Example

func (e *Example) ServeDNS_Example(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error)

ServeDNS implements the plugin.Handler interface. This method gets called when example is used in a Server.

func (*Example) ServeDNS_WhoAmI

func (e *Example) ServeDNS_WhoAmI(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error)

func (*Example) UpdateRecords

func (e *Example) UpdateRecords(records []*PodRecord)

type FlightConfig

type FlightConfig struct {
	// EnableParallelInitContainers whether to enable parallel mode for customer init container(image fetch and model mount)
	EnableParallelInitContainers bool
}

FlightConfig flight related config

type HealthStatusGetter

type HealthStatusGetter interface {
	GetHealthStatus() (bool, error)
}

HealthStatusGetter is a interface that help to get kubelet healthz status

type HttpRequestSender

type HttpRequestSender interface {
	// SendRequestWithFullReturn encapsulate error handling of http request.
	// Return HTTP status code, response header, pointer of response body byte slice and error.
	// A non-2xx status code doesn't cause an error.
	SendRequestWithFullReturn(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string, timeoutInSec int64, isTlsBypass bool) (int, http.Header, []byte, error)

	// SendRequest encapsulate error handling of http request.
	// Return HTTP status code, response header, pointer of response body byte slice and error.
	// A non-2xx status code doesn't cause an error.
	SendRequestWithTimeout(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string, timeoutInSec int64) (int, []byte, error)

	// SendRequest send given http request with a DefaultTimeoutInSec timeout
	SendRequest(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string) (int, []byte, error)

	// SendRequest send given http request with TLS bypass and with a DefaultTimeoutInSec timeout
	SendRequestWithTlsBypass(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string) (int, []byte, error)
}

type KubeletConfig

type KubeletConfig struct {
	// ServiceAddr kubelet endpoint
	ServiceAddr string
	// PodsAPI api path for getting pod info
	PodsAPI string
	// HealthzAPI api path for getting kubelet health info
	HealthzAPI string
	// RunningPodsAPI api path for getting running pods
	RunningPodsAPI string
	// StatsSummaryAPI api path for getting states summary
	StatsSummaryAPI string
	// ManifestsFolderPath path for kubelet pod manifests folder
	ManifestsFolderPath string
}

KubeletConfig vmagent kubelet config

type LogConfig

type LogConfig struct {
	// The server log file path
	LogPath string
	// The server log level(debug", "info", "warn",
	// "error", "dpanic", "panic", and "fatal")
	LogLevel string
	// Enable writing to standard output
	EnableStdOut bool
}

LogConfig vmagent log config

type ManyModelConfig

type ManyModelConfig struct {
	// ManyModelUpdateTimerInterval update timer interval
	ManyModelUpdateTimerInterval int
}

manyModelConfig many model config section

type MyError

type MyError struct {
	When time.Time
	What string
}

func (*MyError) Error

func (e *MyError) Error() string

func (*MyError) Errors

func (e *MyError) Errors() string

func (*MyError) Strings

func (e *MyError) Strings() string

type PodInfoGetter

type PodInfoGetter interface {
	GetPodsInfo() ([]v1.Pod, error)
}

PodInfoGetter is a interface that help to get kubelet pods info

type PodRecord

type PodRecord struct {
	Name string
	Ip   string
	Port int32
}

func MakeCopy

func MakeCopy(records []*PodRecord) []*PodRecord

type PodRetryLimitConfig

type PodRetryLimitConfig struct {
	// Max retry count for infra containers
	InfraDefault int32
	// Default max retry count for customer containers
	CustomerDefault int32
	// Limits override for specific containers, key is the container name, only for infra containers
	Limits map[string]int32
}

type PodSpecConfig

type PodSpecConfig struct {
	// CustomerPodKey customer pod key in pod annotations map
	CustomerPodKey string
	// CustomerPodValue customer pod value in pod annotations map to indicate a customer pod
	CustomerPodValue string
	// LabelMsiTokenKey is the key of MSI token of label.
	LabelMsiTokenKey string
	// LabelMsiTokenValue is the value of MSI token of label.
	LabelMsiTokenValue string
	// LabelMdsdCertKey Label key for msds cert
	LabelMdsdCertKey string
	// LabelMdsdCertValue label value for mdsd cert
	LabelMdsdCertValue string
	// LabelInitContainerAsPodKey Label key for init container pod
	LabelInitContainerAsPodKey string
	// LabelInitContainerAsPodValue Label value for init container pod
	LabelInitContainerAsPodValue string
	// LabelSkipQuotaValidation Label key for skip quota validation pod
	LabelSkipQuotaValidationKey string
	// LabelSkipQuotaValidation Label value for skip quota validation pod
	LabelSkipQuotaValidationValue string
	// The folder where built in agent podspecs locate.
	BuiltInPodSpecFolder string
	// Namespace for Infra pods
	InfraNamespace string
	// Namespace for Customer pods
	CustomerNamespace string
	// Name for VMAgent pod
	VMAgentPodName string
	// ModelMount model mount podspec config
	ModelMount PodSpecModelMountConfig
	// ImageFetcher image fetcher podspec config
	ImageFetcher PodSpecImageFetcherConfig
	// ManyModel many model podspec config
	ManyModel PodSpecManyModelConfig
	// QuotaSettings a map of container quota setting
	QuotaSettings map[string]QuotaSettingConfig
	// Pod retry limit config
	PodRetryLimit PodRetryLimitConfig
	// CuratedImageAcr list
	CuratedAcrList []string
}

PodSpecConfig vmagent podspec config

type PodSpecImageFetcherConfig

type PodSpecImageFetcherConfig struct {
	// VolumeName name of image fatcher volume name
	VolumeName string
	// VolumeMountpath mount path of image fetcher
	VolumeMountpath string
	// InitContainerName name of image fetcher init container
	InitContainerName string
	// InitContainerImage image of image fetcher init container
	InitContainerImage string
	// pod name for standalone image fetcher pod
	PodName string
	// host containerd grpc address
	ContainerdAddress string
}

PodSpecImageFetcherConfig image fetcher pod spec config

type PodSpecManyModelConfig

type PodSpecManyModelConfig struct {
	// ManyModelSideCarImageUrl side car image url
	SideCarImageUrl string
	SideCarPort     int32
}

PodSpecManyModelConfig many model side car container config

type PodSpecModelMountConfig

type PodSpecModelMountConfig struct {
	// InitContainerName name of model mount init container
	InitContainerName string
	// InitContainerImage image of model mount init container
	InitContainerImage string
	// PodName name for standalone storage initializer pod
	PodName string
	// HostModelDir dir on the vm to store the downloaded model files
	HostModelDir string
}

PodSpecModelMountConfig model mount pod spec config

type QuotaSettingConfig

type QuotaSettingConfig struct {
	// CpuResourceInPercent container cpu resource limit in percentage
	CpuResourceInPercent float64
	// MemoryResourceInGb container memory resource limit
	MemoryResourceInGb float64
	// NeedResourceLimit if container need resource limit
	NeedResourceLimit bool
}

QuotaSettingConfig podspec quota setting config

type ResponsePrinter

type ResponsePrinter struct {
	dns.ResponseWriter
}

ResponsePrinter wrap a dns.ResponseWriter and will write example to standard output when WriteMsg is called.

func NewResponsePrinter

func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter

NewResponsePrinter returns ResponseWriter.

func (*ResponsePrinter) WriteMsg

func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error

WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard output.

type RunningPodsGetter

type RunningPodsGetter interface {
	GetRunningPods() (*v1.PodList, error)
}

RunningPodsGetter interface for getting all running pods

type ScheduledEventsConfig

type ScheduledEventsConfig struct {
	// MetadataUrl Url of scheduled events Metadata Service
	MetadataUrl string
	// SchduleEventsUpdateTimerInterval update timer interval
	SchduleEventsUpdateTimerInterval int
	// FreezeAckMinWaitTimeInSec is the minimum wait second for acknowledging Freeze event in Pause State
	FreezeAckMinWaitTimeInSec int
}

ScheduledEventsConfig vmagent scheduled events config section

type SendHttpRequestFunc

type SendHttpRequestFunc func(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string) (int, []byte, error)

type SendHttpRequestWithTimeoutFunc

type SendHttpRequestWithTimeoutFunc func(method string, uri string, paramMap map[string]string, body []byte, headerMap map[string]string, timeoutInSec int64) (int, []byte, error)

type ServerConfig

type ServerConfig struct {
	// The port the server listens to
	Port                                                       int `json:",string"`
	DeploymentTimerInterval                                    int
	DeploymentHealthMaxRetries                                 int
	DeploymentTimeout                                          int
	DeploymentHealthSystemPath                                 string
	DeploymentHealthUserPath                                   string
	DeploymentDataPath                                         string
	DeploymentDefaultPodsHealthyThreshold                      int
	DeploymentCustomerPodsWithoutLivenessProbeHealthyThreshold int
	DeploymentHealthCheckIntervalInMilliSec                    int
	RecoveringStateCustomerContainerRestartLimit               int
	VMStatePersistPath                                         string
	VMUnusableFilePath                                         string
	VMRebootSignalFilePath                                     string
}

ServerConfig vmagent server config section

type TlsBypassHttpsClient

type TlsBypassHttpsClient interface {
	HttpGet(url string) ([]byte, int, error)
}

type UpstreamTokenConfig

type UpstreamTokenConfig struct {
	// UpstreamMsiTokenEndpoint is endpoint of MSI of token server.
	UpstreamMsiTokenEndpoint string
	// UpstreamAcrTokenEndpoint is endpoint of ACR of token server.
	UpstreamAcrTokenEndpoint string
	// UpstreamAcrTokenEndpoint is endpoint of Blob key of token server
	UpstreamBlobKeyEndpoint string
	// upstreamCertEndpoint is endpoint of cert server
	UpstreamSecretArtifactEndpoint string
}

type XdsConfig

type XdsConfig struct {
	// Port is xds server listening port
	Port int `json:",string"`
	// EnvoyMeshPort is the port of mesh listener
	EnvoyMeshPort int `json:",string"`
	// EnvoyNodeID is the envoy node_id of mesh first layer
	EnvoyNodeID string
	// EnvoyLayer2NodeID is the envoy node_id of mesh second layer
	EnvoyLayer2NodeID string
	// DefaultEnvoySDSTlsSecretName is the SDS config name defined in Envoy configuration file
	DefaultEnvoySDSTlsSecretName string
	// DefaultEnvoySDSHttpValidationSecretName is the SDS config name defined in Envoy configuration file
	DefaultEnvoySDSHttpValidationSecretName string
	// DefaultEnvoySDSDiagValidationSecretName is the SDS config name defined in Envoy configuration file
	DefaultEnvoySDSDiagValidationSecretName string
	// EnvoyHealthCheckPath is the health check path defined in Envoy configuration file
	EnvoyHealthCheckPath string
	// EnvoyHealthCheckClusterName is the CDS config name defined in Envoy configuration file
	EnvoyHealthCheckClusterName string
	// EnvoyHealthCheckEndpointName is the EDS config name defined in Envoy configuration file
	EnvoyHealthCheckEndpointName string
	// EnvoyHealthCheckPort is the port of health check listener
	EnvoyHealthCheckPort int
	// EnvoyFDMeshClusterName
	EnvoyFDMeshClusterName string
	// EnvoyFDMeshEndpointName is the EDS config name defined in Envoy configuration file
	EnvoyFDMeshEndpointName string
	// EnvoyMeshRouteConfigName is the RDS config name defined in Envoy configuration file
	EnvoyMeshRouteConfigName string
	// HealthCheckTimeoutMilliseconds defines health check route timeout in milliseconds
	HealthCheckTimeoutMilliseconds int
	// RouteTimeoutMilliseconds defines the route request timeout in milliseconds
	RouteTimeoutMilliseconds int
	// UpstreamClusterConnectTimeoutMilliseconds defines the connection timeout to an upstream cluster
	UpstreamClusterConnectTimeoutMilliseconds int
	// EnvoyMeshEndpointUpdateTimerInterval time interval config for update envoy mesh endpoints
	EnvoyMeshEndpointUpdateTimerInterval int
	// CACertificateFileName is the CA certificates file used by envoy mTLS validation
	CACertificateFileName string
	// CertificateChainSortingEnabled indicates whether to sort certificate chain on exporting public key from PEM or PFX
	CertificateChainSortingEnabled bool
	// RequestHeadersToRemove contains a list of header names that need to remove before sending to custom container
	RequestHeadersToRemove []string
	// RequestHeadersToPassBy contains a list of header names that need to pass by sending to custom container, add back to response.
	RequestHeadersToPassBy []string

	// EnvoyManyModelRouteConfigName used for triton manymodel flight.
	EnvoyManyModelRouteConfigName string
	// EnvoyManyModelDirectRouteHeaderName used for triton manymodel flight.
	EnvoyManyModelDirectRouteHeaderName string
	// EnvoyManyModelDirectRouteHeaderName used for triton manymodel flight.
	EnvoyManyModelDirectRouteHeaderValue string
	// EnvoyManyModelRequestPathPattern used for triton manymodel flight.
	EnvoyManyModelRequestPathPattern string

	// ModelConcurrencyThresholdToDisableLogs
	ModelConcurrencyThresholdToDisableLogs int
}

XdsConfig vmagent envoy xds server config section

Jump to

Keyboard shortcuts

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